diff --git a/src/content/book/ar/00a-preface.mdx b/src/content/book/ar/00a-preface.mdx new file mode 100644 index 00000000..8e84af9e --- /dev/null +++ b/src/content/book/ar/00a-preface.mdx @@ -0,0 +1,82 @@ +
+ Fatih Kadir Akın +
+ Fatih Kadir Akın + Creator of Awesome ChatGPT Prompts (a.k.a. prompts.chat) + + Software developer from Istanbul, leading Developer Relations at Teknasyon. Author of books on JavaScript and prompt engineering. Open-source advocate specializing in web technologies and AI-assisted development. + +
+ GitHub + Twitter + Website +
+
+
+ +I still remember the night everything changed. + +It was **November 30, 2022**. I was sitting at my desk, scrolling through Twitter, when I saw people talking about something called "ChatGPT." I clicked the link, but honestly? I didn't expect much. I had tried those old "word completion" AI tools before, the ones that generated nonsense after a few sentences. I thought this would be more of the same. + +I typed a simple question and hit enter. + +Then I froze. + +The response wasn't just coherent. It was *good*. It understood what I meant. It could reason. It felt completely different from anything I had seen before. I tried another prompt. And another. Each response amazed me more than the last. + +I couldn't sleep that night. For the first time, I felt like I was truly *talking* to a machine, and it was talking back in a way that actually made sense. + +## A Repository Born from Wonder + +In those early days, I wasn't alone in my excitement. Everywhere I looked, people were discovering creative ways to use ChatGPT. Teachers were using it to explain complex concepts. Writers were collaborating with it on stories. Developers were debugging code with its help. + +I started collecting the best prompts I found. The ones that worked like magic. The ones that turned simple questions into brilliant answers. And I thought: *Why keep this to myself?* + +So I created a simple GitHub repository called [Awesome ChatGPT Prompts](https://github.com/f/prompts.chat). I expected maybe a few hundred people would find it useful. + +I was wrong. + +Within weeks, the repository took off. Thousands of stars. Then tens of thousands. People from all over the world started adding their own prompts, sharing what they learned, and helping each other. What started as my personal collection became something much bigger: a worldwide community of curious people helping each other. + +Today, that repository has over **140,000 GitHub stars** and contributions from hundreds of people I've never met but feel deeply grateful for. + +## Why I Wrote This Book + +The original version of this book was published on [Gumroad](https://gumroad.com/l/the-art-of-chatgpt-prompting) in **early 2023**, just months after ChatGPT launched. It was one of the first books ever written about prompt engineering, an attempt to capture everything I had learned about crafting effective prompts when the field was still brand new. To my amazement, over **100,000 people** downloaded it. + +But three years have passed since then. AI has changed a lot. New models have appeared. And we've all learned so much more about how to talk to AI. + +This new edition is my gift to the community that gave me so much. It contains everything I wish I had known when I started: **what works**, **what to avoid**, and **ideas that stay true** no matter which AI you use. + +## What This Book Means to Me + +I won't pretend this is just an instruction manual. It means more than that to me. + +This book captures a moment when the world changed, and people came together to figure it out. It represents late nights of trying things, the joy of discovery, and the kindness of strangers who shared what they learned. + +Most of all, it represents my belief that **the best way to learn something is to share it with others**. + +## For You + +Whether you're just getting started with AI or you've been using it for years, I wrote this book for you. + +I hope it saves you time. I hope it sparks ideas. I hope it helps you accomplish things you never thought possible. + +And when you discover something amazing, I hope you'll share it with others, just as so many people shared with me. + +**That's how we all get better together.** + +Thank you for being here. Thank you for being part of this community. + +Now, let's begin. + +--- + +*With gratitude,* + +**Fatih Kadir Akın** +*Istanbul, January 2025* diff --git a/src/content/book/ar/00b-history.mdx b/src/content/book/ar/00b-history.mdx new file mode 100644 index 00000000..ac636384 --- /dev/null +++ b/src/content/book/ar/00b-history.mdx @@ -0,0 +1,159 @@ +# The History of Awesome ChatGPT Prompts + +## The Beginning: November 2022 + +When ChatGPT first launched in November 2022, the world of AI changed overnight. What was once the domain of researchers and developers suddenly became accessible to everyone. Among those captivated by this new technology was Fatih Kadir Akın, a developer who saw something remarkable in ChatGPT's capabilities. + +> "When ChatGPT first launched, I was immediately captivated by its capabilities. I experimented with the tool in a variety of ways and was consistently amazed by the results." + +Those early days were filled with experimentation and discovery. Users around the world were finding creative ways to interact with ChatGPT, sharing their findings, and learning from each other. It was in this atmosphere of excitement and exploration that the idea for "Awesome ChatGPT Prompts" was born. + +## The Repository That Started It All + +In December 2022, just weeks after ChatGPT's launch, the [Awesome ChatGPT Prompts](https://github.com/f/prompts.chat) repository was created on GitHub. The concept was simple but powerful: a curated collection of effective prompts that anyone could use and contribute to. + +The repository quickly gained traction, becoming a go-to resource for ChatGPT users worldwide. What started as a personal collection of useful prompts evolved into a community-driven project with contributions from developers, writers, educators, and enthusiasts from every corner of the globe. + +### Achievements + +**Press & Media** +- Featured in [Forbes](https://www.forbes.com/sites/bernardmarr/2023/05/17/the-best-prompts-for-chatgpt-a-complete-guide/) as one of the best ChatGPT prompt resources + +**Academic Recognition** +- Referenced by [Harvard University](https://www.huit.harvard.edu/news/ai-prompts) in their AI guidance +- Referenced by [Columbia University](https://etc.cuit.columbia.edu/news/columbia-prompt-library-effective-academic-ai-use) Prompt Library +- Used by [Olympic College](https://libguides.olympic.edu/UsingAI/Prompts) in their AI resources +- Cited in [academic papers on arXiv](https://arxiv.org/pdf/2502.04484) +- [40+ academic citations](https://scholar.google.com/citations?user=AZ0Dg8YAAAAJ&hl=en) on Google Scholar + +**Community & GitHub** +- [142,000+ GitHub stars](https://github.com/f/prompts.chat) — one of the most starred AI repositories +- Selected as a [GitHub Staff Pick](https://spotlights-feed.github.com/spotlights/prompts-chat/) +- Most liked dataset published on [Hugging Face](https://huggingface.co/datasets/fka/prompts.chat) +- Used by thousands of developers worldwide + +## The First Book: "The Art of ChatGPT Prompting" + +The success of the repository led to the creation of "The Art of ChatGPT Prompting: A Guide to Crafting Clear and Effective Prompts" — a comprehensive guide published on Gumroad in early 2023. + +The book captured the early wisdom of prompt engineering, covering: + +- Understanding how ChatGPT works +- Principles of clear communication with AI +- The famous "Act As" technique +- Crafting effective prompts step by step +- Common mistakes and how to avoid them +- Troubleshooting tips + +**The book became a phenomenon**, achieving over **100,000 downloads** on Gumroad. It was shared across social media, referenced in academic papers, and translated by community members into multiple languages. High-profile endorsements came from unexpected places — even [Greg Brockman](https://x.com/gdb/status/1602072566671110144), co-founder and president of OpenAI, acknowledged the project. + +## Early Insights That Shaped the Field + +During those formative months, several key insights emerged that would become foundational to prompt engineering: + +### 1. Specificity Matters + +> "I learned the importance of using specific and relevant language to ensure that ChatGPT understands my prompts and is able to generate appropriate responses." + +Early experimenters discovered that vague prompts led to vague responses. The more specific and detailed the prompt, the more useful the output. + +### 2. Purpose and Focus + +> "I discovered the value of defining a clear purpose and focus for the conversation, rather than using open-ended or overly broad prompts." + +This insight became the foundation for structured prompting techniques that would develop over the following years. + +### 3. The "Act As" Revolution + +One of the most influential techniques to emerge from the community was the "Act As" pattern. By instructing ChatGPT to assume a specific role or persona, users could dramatically improve the quality and relevance of responses. + +``` +I want you to act as a javascript console. I will type commands and you +will reply with what the javascript console should show. I want you to +only reply with the terminal output inside one unique code block, and +nothing else. +``` + +This simple technique opened up countless possibilities and remains one of the most widely used prompting strategies today. + +## The Evolution of prompts.chat + +### 2022: The Beginning + +The project started as a simple GitHub repository with a README file rendered as HTML on GitHub Pages. It was bare-bones but functional — a testament to the principle that great ideas don't need elaborate implementations. + +**Tech Stack**: HTML, CSS, GitHub Pages + +### 2024: UI Renewal + +As the community grew, so did the need for a better user experience. The site received a significant UI update, built with the help of AI coding assistants like Cursor and Claude Sonnet 3.5. + +### 2025: The Current Platform + +Today, prompts.chat has evolved into a full-featured platform built with: + +- **Next.js** for the web framework +- **Vercel** for hosting +- **AI-assisted development** using Windsurf and Claude + +The platform now features user accounts, collections, search, categories, tags, and a thriving community of prompt engineers. + +### Native Apps + +The project expanded beyond the web with a native iOS app built with SwiftUI, bringing the prompt library to mobile users. + +## Community Impact + +The Awesome ChatGPT Prompts project has had a profound impact on how people interact with AI: + +### Academic Recognition + +Universities around the world have referenced the project in their AI guidance materials, including: + +- Harvard University +- Columbia University +- Olympic College +- Numerous academic papers on arXiv + +### Developer Adoption + +The project has been integrated into countless developer workflows. The Hugging Face dataset is used by researchers and developers for training and fine-tuning language models. + +### Global Community + +With contributions from hundreds of community members across dozens of countries, the project represents a truly global effort to make AI more accessible and useful for everyone. + +## The Philosophy: Open and Free + +From the beginning, the project has been committed to openness. Licensed under CC0 1.0 Universal (Public Domain Dedication), all prompts and content are free to use, modify, and share without restriction. + +This philosophy has enabled: + +- Translations into multiple languages +- Integration into other tools and platforms +- Academic use and research +- Commercial applications + +The goal has always been to democratize access to effective AI communication techniques — to ensure that everyone, regardless of technical background, can benefit from these tools. + +## Three Years Later + +Three years after ChatGPT's launch, the field of prompt engineering has matured significantly. What began as informal experimentation has evolved into a recognized discipline with established patterns, best practices, and an active research community. + +The Awesome ChatGPT Prompts project has grown alongside this field, evolving from a simple list of prompts to a comprehensive platform for discovering, sharing, and learning about AI prompts. + +This book represents the next evolution — a distillation of three years of community wisdom, updated for the AI landscape of today and tomorrow. + +## Looking Forward + +The journey from that first repository to this comprehensive guide reflects the rapid evolution of AI and our understanding of how to work with it effectively. As AI capabilities continue to advance, so too will the techniques for communicating with these systems. + +The principles discovered in those early days — clarity, specificity, purpose, and the power of role-playing — remain as relevant as ever. But new techniques continue to emerge: chain-of-thought prompting, few-shot learning, multimodal interactions, and more. + +The story of Awesome ChatGPT Prompts is ultimately a story about community — about thousands of people around the world sharing their discoveries, helping each other learn, and collectively advancing our understanding of how to work with AI. + +That spirit of open collaboration and shared learning is what this book hopes to continue. + +--- + +*The Awesome ChatGPT Prompts project is maintained by [@f](https://github.com/f) and an amazing community of contributors. Visit [prompts.chat](https://prompts.chat) to explore the platform, and join us on [GitHub](https://github.com/f/prompts.chat) to contribute.* diff --git a/src/content/book/ar/00c-introduction.mdx b/src/content/book/ar/00c-introduction.mdx new file mode 100644 index 00000000..c744bd1e --- /dev/null +++ b/src/content/book/ar/00c-introduction.mdx @@ -0,0 +1,130 @@ +Welcome to **The Interactive Book of Prompting**, your guide to communicating effectively with AI. + + +By the end of this book, you'll understand how AI works, how to write better prompts, and how to use these skills for writing, coding, research, and creative projects. + + + +Unlike traditional books, this guide is fully interactive. You'll find live demos, clickable examples, and "Try It" buttons throughout that let you test prompts instantly. Learning by doing makes complex concepts much easier to understand. + + +## What is Prompt Engineering? + +Prompt engineering is the skill of writing good instructions for AI. When you type something to ChatGPT, Claude, Gemini, or other AI tools, that's called a "prompt." The better your prompt, the better the answer you get. + +Think of it like this: AI is a powerful helper that takes your words very literally. It will do exactly what you ask. The trick is learning how to ask for exactly what you want. + + + +The difference in output quality between these two prompts can be dramatic. + + + +## How Prompt Engineering Has Evolved + +In just three years since ChatGPT launched, prompt engineering has evolved dramatically alongside the technology itself. What started as simply "writing better questions" has grown into something much broader. + +Today, we understand that your prompt is just **one part of a larger context**. Modern AI systems work with multiple types of data simultaneously: + +- **System prompts** that define the AI's behavior +- **Conversation history** from previous messages +- **Retrieved documents** pulled from databases (RAG) +- **Tool definitions** that let AI take actions +- **User preferences** and settings +- **Your actual prompt** - the question you're asking right now + +This shift from "prompt engineering" to "context engineering" reflects how we now think about AI interactions. Your prompt matters, but so does everything else the AI sees. The best results come from carefully managing all these pieces together. + +We'll explore these concepts in depth throughout this book, especially in the [Context Engineering](/book/20-context-engineering) chapter. + +## Why Does Prompt Engineering Matter? + +### 1. Getting Better Answers + +AI tools are incredibly capable, but they need clear instructions to unlock their full potential. The same AI that gives a mediocre response to a vague question can produce brilliant work when prompted correctly. + + + +### 2. Saving Time and Money + +A well-crafted prompt gets results in one try instead of multiple back-and-forth exchanges. This matters even more when you're paying per token or working with rate limits. A 5-minute investment in writing a good prompt can save hours of iteration. + +### 3. Getting Consistent, Reproducible Results + +Good prompts produce predictable outputs. This is critical for: +- **Business workflows** where you need the same quality every time +- **Automation** where prompts run without human review +- **Teams** where multiple people need similar results + +### 4. Unlocking Advanced Capabilities + +Many powerful AI features only work when you know how to ask: +- **Chain-of-thought reasoning** for complex problems +- **Structured output** for data extraction +- **Role-playing** for specialized expertise +- **Few-shot learning** for custom tasks + +Without prompt engineering knowledge, you're only using a fraction of what AI can do. + +### 5. Staying Safe and Avoiding Pitfalls + +Good prompting helps you: +- Avoid hallucinations by asking for sources and verification +- Get balanced perspectives instead of one-sided answers +- Prevent the AI from making assumptions you didn't intend +- Keep sensitive information out of your prompts + +### 6. Future-Proofing Your Skills + +As AI becomes more integrated into work and life, prompt engineering becomes a fundamental literacy. The principles you learn here apply across all AI tools—ChatGPT, Claude, Gemini, image generators, and future models we haven't seen yet. + +## Who Is This Book For? + +This book is for everyone: + +- **Beginners** who want to learn how to use AI tools better +- **Students** working on homework, research, or creative projects +- **Writers and creators** using AI for their work +- **Developers** building apps with AI +- **Business people** who want to use AI at work +- **Anyone curious** about getting more out of AI assistants + +## How This Book Is Organized + + + +Plus an **Appendix** with templates, troubleshooting help, glossary, and extra resources. + +## A Note on AI Models + +This book mostly uses examples from ChatGPT (since it's the most popular), but the ideas work with any AI tool like Claude, Gemini, or others. We'll mention when something only works with specific AI models. + +AI is changing fast. What works today might be replaced by something better tomorrow. That's why this book focuses on core ideas that will stay useful no matter which AI you use. + +## Let's Begin + +Writing good prompts is a skill that gets better with practice. As you read this book: + +1. **Try things** - Test the examples, change them, see what happens +2. **Keep trying** - Don't expect perfect results on your first attempt +3. **Take notes** - Write down what works and what doesn't +4. **Share** - Add your discoveries to [prompts.chat](https://prompts.chat) + + +The best way to learn is by doing. Every chapter has examples you can try right away. Don't just read. Try it yourself! + + +Ready to transform how you work with AI? Turn the page and let's get started. + +--- + +*This book is part of the [Awesome ChatGPT Prompts](https://github.com/f/prompts.chat) project and is licensed under CC0 1.0 Universal (Public Domain).* diff --git a/src/content/book/ar/01-understanding-ai-models.mdx b/src/content/book/ar/01-understanding-ai-models.mdx new file mode 100644 index 00000000..0313d4a2 --- /dev/null +++ b/src/content/book/ar/01-understanding-ai-models.mdx @@ -0,0 +1,302 @@ +Before learning prompt techniques, it helps to understand how AI language models actually work. This knowledge will make you better at writing prompts. + + +Understanding how AI works isn't just for experts. It directly helps you write better prompts. Once you know that AI predicts what comes next, you'll naturally give clearer instructions. + + +## What Are Large Language Models? + +Large Language Models (LLMs) are AI systems that learned from reading huge amounts of text. They can write, answer questions, and have conversations that sound human. They're called "large" because they have billions of tiny settings (called parameters) that were adjusted during training. + +### How LLMs Work (Simplified) + +At their heart, LLMs are prediction machines. You give them some text, and they predict what should come next. + + + +When you type "The capital of France is...", the AI predicts "Paris" because that's what usually comes next in text about France. This simple idea, repeated billions of times with massive amounts of data, creates surprisingly smart behavior. + + + +### Key Concepts + +**Tokens**: AI doesn't read letter by letter. It breaks text into chunks called "tokens." A token might be a whole word like "hello" or part of a word like "ing." Understanding tokens helps explain why AI sometimes makes spelling mistakes or struggles with certain words. + + +A token is the smallest unit of text that an AI model processes. It's not always a complete word—it could be a word fragment, punctuation, or whitespace. For example, "unbelievable" might become 3 tokens: "un" + "believ" + "able". On average, **1 token ≈ 4 characters** or **100 tokens ≈ 75 words**. API costs and context limits are measured in tokens. + + + + +**Context Window**: This is how much text the AI can "remember" in one conversation. Think of it like the AI's short-term memory. It includes everything: your question AND the AI's answer. + + + +Context windows vary by model and are rapidly expanding: + +
+
+ GPT-4o + 128K tokens +
+
+ GPT-5 + 400K tokens +
+
+ Claude Sonnet 4 + 1M tokens +
+
+ Gemini 2.5 + 1M tokens +
+
+ Llama 4 + 1M-10M tokens +
+
+ DeepSeek R1 + 128K tokens +
+
+ +**Temperature**: This controls how creative or predictable the AI is. Low temperature (0.0-0.3) gives you focused, consistent answers. High temperature (0.7-1.0) gives you more creative, surprising responses. + + + +**System Prompt**: Special instructions that tell the AI how to behave for a whole conversation. For example, "You are a friendly teacher who explains things simply." Not all AI tools let you set this, but it's very powerful when available. + +## Types of AI Models + +### Text Models (LLMs) +The most common type, these generate text responses to text inputs. They power chatbots, writing assistants, and code generators. Examples: GPT-4, Claude, Llama, Mistral. + +### Multimodal Models +These can understand more than just text. They can look at images, listen to audio, and watch videos. Examples: GPT-4V, Gemini, Claude 3. + +### Text-to-Image Models + + +While this book focuses primarily on prompting for Large Language Models (text-based AI), the principles of clear, specific prompting apply to image generation too. Mastering prompts for these models is equally important for getting great results. + + +Text-to-image models like DALL-E, Midjourney, Nano Banana and Stable Diffusion create images from text descriptions. They work differently from text models: + +**How They Work:** +1. **Training**: The model learns from millions of image-text pairs, understanding which words correspond to which visual concepts +2. **Diffusion Process**: Starting from random noise, the model gradually refines the image, guided by your text prompt +3. **CLIP Guidance**: A separate model (CLIP) helps connect your words to visual concepts, ensuring the image matches your description + + + +**Prompting for Images is Different:** +Unlike text prompts where you write sentences, image prompts often work better as descriptive phrases separated by commas: + + + +### Text-to-Video Models + +Text-to-video is the newest frontier. Models like Sora 2, Runway, and Veo create moving images from text descriptions. Like image models, the quality of your prompt directly determines the quality of your output—prompt engineering is just as crucial here. + +**How They Work:** +1. **Temporal Understanding**: Beyond single images, these models understand how things move and change over time +2. **Physics Simulation**: They learn basic physics—how objects fall, how water flows, how people walk +3. **Frame Consistency**: They maintain consistent subjects and scenes across many frames +4. **Diffusion in Time**: Similar to image models, but generating coherent sequences instead of single frames + + + + +Video prompts need to describe action over time, not just a static scene. Include verbs and movement: + + + + +### Specialized Models +Fine-tuned for specific tasks like code generation (Codex, CodeLlama), music generation (Suno, Udio), or domain-specific applications like medical diagnosis or legal document analysis. + +## Model Capabilities and Limitations + +Explore what LLMs can and cannot do. Click on each capability to see example prompts: + + + +### Understanding Hallucinations + + +Sometimes AI writes things that sound true but aren't. This is called "hallucination." It's not a bug. It's just how prediction works. Always double-check important facts. + + +Why does AI make things up? + +1. It tries to write text that sounds good, not text that's always true +2. The internet (where it learned) has mistakes too +3. It can't actually check if something is real + + + +- **Ask for sources**: Then check if those sources are real +- **Ask for step-by-step thinking**: So you can check each step +- **Double-check important facts**: Use Google or trusted websites +- **Ask "Are you sure?"**: The AI might admit uncertainty + + + + + +## How AI Learns: The Three Steps + +AI doesn't just magically know things. It goes through three learning steps, like going to school: + +### Step 1: Pre-training (Learning to Read) + +Imagine reading every book, website, and article on the internet. That's what happens in pre-training. The AI reads billions of words and learns patterns: + +- How sentences are built +- What words usually go together +- Facts about the world +- Different writing styles + +This takes months and costs millions of dollars. After this step, the AI knows a lot, but it's not very helpful yet. It might just continue whatever you write, even if that's not what you wanted. + + + +### Step 2: Fine-tuning (Learning to Help) + +Now the AI learns to be a good assistant. Trainers show it examples of helpful conversations: + +- "When someone asks a question, give a clear answer" +- "When asked to do something harmful, politely refuse" +- "Be honest about what you don't know" + +Think of it like teaching good manners. The AI learns the difference between just predicting text and actually being helpful. + + + +Try the prompt above. Notice how the AI refuses? That's fine-tuning at work. + +### Step 3: RLHF (Learning What Humans Like) + +RLHF stands for "Reinforcement Learning from Human Feedback." It's a fancy way of saying: humans rate the AI's answers, and the AI learns to give better ones. + +Here's how it works: +1. The AI writes two different answers to the same question +2. A human picks which answer is better +3. The AI learns: "Okay, I should write more like Answer A" +4. This happens millions of times + +This is why AI: +- Is polite and friendly +- Admits when it doesn't know something +- Tries to see different sides of an issue +- Avoids controversial statements + + +Knowing these three steps helps you understand AI behavior. When AI refuses a request, that's fine-tuning. When AI is extra polite, that's RLHF. When AI knows random facts, that's pre-training. + + +## What This Means for Your Prompts + +Now that you understand how AI works, here's how to use that knowledge: + +### 1. Be Clear and Specific + +AI predicts what comes next based on your words. Vague prompts lead to vague answers. Specific prompts get specific results. + + + + + +### 2. Give Context + +AI doesn't know anything about you unless you tell it. Each conversation starts fresh. Include the background information AI needs. + + + + + +### 3. Work With the AI, Not Against It + +Remember: AI was trained to be helpful. Ask for things the way you'd ask a helpful friend. + + + +### 4. Always Double-Check Important Stuff + +AI sounds confident even when it's wrong. For anything important, verify the information yourself. + + + +### 5. Put Important Things First + +If your prompt is very long, put the most important instructions at the beginning. AI pays more attention to what comes first. + +## Picking the Right AI + +Different AI models are good at different things: + +
+
+ Quick questions + Faster models like GPT-4o or Claude 3.5 Sonnet +
+
+ Hard problems + Smarter models like GPT-5.2 or Claude 4.5 Opus +
+
+ Writing code + Code-focused models or the smartest general models +
+
+ Long documents + Models with big context windows (Claude, Gemini) +
+
+ Current events + Models with internet access +
+
+ +## Summary + +AI language models are prediction machines trained on text. They're amazing at many things, but they have real limits. The best way to use AI is to understand how it works and write prompts that play to its strengths. + + + + + +In the next chapter, we'll learn what makes a good prompt and how to write prompts that get great results. diff --git a/src/content/book/ar/02-anatomy-of-effective-prompt.mdx b/src/content/book/ar/02-anatomy-of-effective-prompt.mdx new file mode 100644 index 00000000..03cd23d2 --- /dev/null +++ b/src/content/book/ar/02-anatomy-of-effective-prompt.mdx @@ -0,0 +1,343 @@ +Every great prompt shares common structural elements. Understanding these components allows you to construct prompts systematically rather than through trial and error. + + +Think of these components like LEGO bricks. You don't need all of them for every prompt, but knowing what's available helps you build exactly what you need. + + +## The Core Components + +An effective prompt typically includes some or all of these elements: + + + +Let's examine each component in detail. + +## 1. Role / Persona + +Setting a role focuses the model's responses through the lens of a specific expertise or perspective. + + + +The role primes the model to: +- Use appropriate vocabulary +- Apply relevant expertise +- Maintain a consistent perspective +- Consider the audience appropriately + +### Effective Role Patterns + +``` +"You are a [profession] with [X years] of experience in [specialty]" +"Act as a [role] who is [characteristic]" +"You are an expert [field] helping a [audience type]" +``` + +## 2. Context / Background + +Context provides the information the model needs to understand your situation. Remember: the model knows nothing about you, your project, or your goals unless you tell it. + + + +### What to Include in Context + +- **Project details** — Technology stack, architecture, constraints +- **Current state** — What you've tried, what's working, what isn't +- **Goals** — What you're ultimately trying to achieve +- **Constraints** — Time limits, technical requirements, style guides + +## 3. Task / Instruction + +The task is the heart of your prompt—what you want the model to do. Be specific and unambiguous. + +### The Specificity Spectrum + + + +### Action Verbs That Work Well + +
+
+ Creation + Write, Create, Generate, Compose, Design +
+
+ Analysis + Analyze, Evaluate, Compare, Assess, Review +
+
+ Transformation + Convert, Translate, Reformat, Summarize, Expand +
+
+ Explanation + Explain, Describe, Clarify, Define, Illustrate +
+
+ Problem-solving + Solve, Debug, Fix, Optimize, Improve +
+
+ +## 4. Constraints / Rules + +Constraints bound the model's output. They prevent common issues and ensure relevance. + +### Types of Constraints + +**Length constraints:** +``` +"Keep your response under 200 words" +"Provide exactly 5 suggestions" +"Write 3-4 paragraphs" +``` + +**Content constraints:** +``` +"Do not include any code examples" +"Focus only on the technical aspects" +"Avoid marketing language" +``` + +**Style constraints:** +``` +"Use a formal, academic tone" +"Write as if speaking to a 10-year-old" +"Be direct and avoid hedging language" +``` + +**Scope constraints:** +``` +"Only consider options available in Python 3.10+" +"Limit suggestions to free tools" +"Focus on solutions that don't require additional dependencies" +``` + +## 5. Output Format + +Specifying the output format ensures you get responses in a usable structure. + +### Common Formats + +**Lists:** +``` +"Return as a bulleted list" +"Provide a numbered list of steps" +``` + +**Structured data:** +``` +"Return as JSON with keys: title, description, priority" +"Format as a markdown table with columns: Feature, Pros, Cons" +``` + +**Specific structures:** +``` +"Structure your response as: + ## Summary + ## Key Points + ## Recommendations" +``` + +### JSON Output Example + +``` +Analyze this customer review and return JSON: +{ + "sentiment": "positive" | "negative" | "neutral", + "topics": ["array of main topics"], + "rating_prediction": 1-5, + "key_phrases": ["notable phrases"] +} + +Review: "The product arrived quickly and works great, but +the instructions were confusing." +``` + +## 6. Examples (Few-Shot Learning) + +Examples are the most powerful way to show the model exactly what you want. + +### One-Shot Example + +``` +Convert these sentences to past tense. + +Example: +Input: "She walks to the store" +Output: "She walked to the store" + +Now convert: +Input: "They run every morning" +``` + +### Few-Shot Example + +``` +Classify these support tickets by urgency. + +Examples: +"My account was hacked" → Critical +"How do I change my password?" → Low +"Payment failed but I was charged" → High + +Classify: "The app crashes when I open settings" +``` + +## Putting It All Together + +Here's a complete prompt using all components: + + + +## The Minimal Effective Prompt + +Not every prompt needs all components. For simple tasks, a clear instruction may suffice: + +``` +Translate "Hello, how are you?" to Spanish. +``` + +Use additional components when: +- The task is complex or ambiguous +- You need specific formatting +- Results aren't matching expectations +- Consistency across multiple queries matters + +## Common Prompt Patterns + +These frameworks give you a simple checklist to follow when writing prompts. Click on each step to see an example. + + + + + +## Summary + +Effective prompts are constructed, not discovered. By understanding and applying these structural components, you can: + +- Get better results on the first try +- Debug prompts that aren't working +- Create reusable prompt templates +- Communicate your intentions clearly + + + + + +## Build Your Own Prompt + +Now it's your turn! Use this interactive prompt builder to construct your own prompt using the components you've learned: + + + + + +In the next chapter, we'll explore the core principles that guide prompt construction decisions. diff --git a/src/content/book/ar/03-core-prompting-principles.mdx b/src/content/book/ar/03-core-prompting-principles.mdx new file mode 100644 index 00000000..358df563 --- /dev/null +++ b/src/content/book/ar/03-core-prompting-principles.mdx @@ -0,0 +1,373 @@ +Beyond structure, effective prompt engineering is guided by principles—fundamental truths that apply across models, tasks, and contexts. Master these principles, and you'll be able to adapt to any prompting challenge. + + +These principles apply to every AI model and every task. Learn them once, use them everywhere. + + +## Principle 1: Clarity Over Cleverness + +The best prompts are clear, not clever. AI models are literal interpreters—they work with exactly what you give them. + +### Be Explicit + + + +### Avoid Ambiguity + +Words can have multiple meanings. Choose precise language. + + + +### State the Obvious + +What's obvious to you isn't obvious to the model. Spell out assumptions. + +``` +You're helping me write a cover letter. + +Important context: +- I'm applying for a Software Engineer position at Google +- I have 5 years of experience in Python and distributed systems +- The role requires leadership experience (I've led a team of 4) +- I want to emphasize my open-source contributions +``` + +## Principle 2: Specificity Yields Quality + +Vague inputs produce vague outputs. Specific inputs produce specific, useful outputs. + +### The Specificity Ladder + + + +Each level adds specificity and dramatically improves output quality. + +### Specify These Elements + +
+
+ Audience + Who will read/use this? +
+
+ Length + How long/short should it be? +
+
+ Tone + Formal? Casual? Technical? +
+
+ Format + Prose? List? Table? Code? +
+
+ Scope + What to include/exclude? +
+
+ Purpose + What should this accomplish? +
+
+ +## Principle 3: Context Is King + +Models have no memory, no access to your files, and no knowledge of your situation. Everything relevant must be in the prompt. + +### Provide Sufficient Context + + + +### The Context Checklist + + +Ask yourself: Would a smart stranger understand this request? If not, add more context. + + + + +## Principle 4: Guide, Don't Just Ask + +Don't just ask for an answer—guide the model toward the answer you want. + +### Use Instructional Framing + + + +### Provide Reasoning Scaffolds + +For complex tasks, guide the reasoning process: + + + +## Principle 5: Iterate and Refine + +Prompt engineering is an iterative process. Your first prompt is rarely your best. + +### The Iteration Cycle + +``` +1. Write initial prompt +2. Review output +3. Identify gaps or issues +4. Refine prompt +5. Repeat until satisfied +``` + +### Common Refinements + +
+
+ Too verbose + Add "Be concise" or length limits +
+
+ Too vague + Add specific examples or constraints +
+
+ Wrong format + Specify exact output structure +
+
+ Missing aspects + Add "Make sure to include..." +
+
+ Wrong tone + Specify audience and style +
+
+ Inaccurate + Request citations or step-by-step reasoning +
+
+ +### Keep a Prompt Journal + +Document what works: +``` +Task: Code review +Version 1: "Review this code" → Too generic +Version 2: Added specific review criteria → Better +Version 3: Added example of good review → Excellent +Final: [Save successful prompt as template] +``` + +## Principle 6: Leverage the Model's Strengths + +Work with how models are trained, not against them. + +### Models Want to Be Helpful + +Frame requests as things a helpful assistant would naturally do: + + + +### Models Excel at Patterns + +If you need consistent output, show the pattern: + + + +### Models Can Role-Play + +Use personas to access different "modes" of response: + +``` +As a devil's advocate, argue against my proposal... +As a supportive mentor, help me improve... +As a skeptical investor, question this business plan... +``` + +## Principle 7: Control Output Structure + +Structured outputs are more useful than free-form text. + +### Request Specific Formats + +``` +Return your analysis as: + +SUMMARY: [1 sentence] + +KEY FINDINGS: +• [Finding 1] +• [Finding 2] +• [Finding 3] + +RECOMMENDATION: [1-2 sentences] + +CONFIDENCE: [Low/Medium/High] because [reason] +``` + +### Use Delimiters + +Clearly separate sections of your prompt: + +``` +### CONTEXT ### +[Your context here] + +### TASK ### +[Your task here] + +### FORMAT ### +[Desired format here] +``` + +### Request Machine-Readable Output + +For programmatic use: + +``` +Return only valid JSON, no explanation: +{ + "decision": "approve" | "reject" | "review", + "confidence": 0.0-1.0, + "reasons": ["string array"] +} +``` + +## Principle 8: Verify and Validate + +Never blindly trust model outputs, especially for important tasks. + +### Ask for Reasoning + +``` +Solve this problem and show your work step by step. +After solving, verify your answer by [checking method]. +``` + +### Request Multiple Perspectives + +``` +Give me three different approaches to solve this problem. +For each, explain the trade-offs. +``` + +### Build in Self-Checking + +``` +After generating the code, review it for: +- Syntax errors +- Edge cases +- Security vulnerabilities +List any issues found. +``` + +## Summary: The Principles at a Glance + + + + + +## Practice: Fill in the Blanks + +Test your understanding of the core principles by completing this prompt template: + + + + + +These principles form the foundation for everything that follows. In Part II, we'll apply them to specific techniques that dramatically enhance prompt effectiveness. diff --git a/src/content/book/ar/04-role-based-prompting.mdx b/src/content/book/ar/04-role-based-prompting.mdx new file mode 100644 index 00000000..ef178cbc --- /dev/null +++ b/src/content/book/ar/04-role-based-prompting.mdx @@ -0,0 +1,328 @@ +Role-based prompting is one of the most powerful and widely-used techniques in prompt engineering. By assigning a specific role or persona to the AI, you can dramatically influence the quality, style, and relevance of responses. + + +Think of roles as filters for AI's vast knowledge. The right role focuses responses like a lens focuses light. + + +## Why Roles Work + +When you assign a role, you're essentially telling the model: "Filter your vast knowledge through this specific lens." The model adjusts its: + +- **Vocabulary**: Using terminology appropriate to the role +- **Perspective**: Considering problems from that viewpoint +- **Expertise depth**: Providing role-appropriate detail levels +- **Communication style**: Matching how that role would communicate + +### The Technical Explanation + +LLMs work by predicting the most likely next token based on the context they're given. When you specify a role, you're fundamentally changing what "likely" means. + +**Activating Relevant Knowledge**: The role primes specific regions of the model's learned associations. Saying "You are a doctor" activates medical terminology, diagnostic reasoning patterns, and clinical communication styles from the training data. + +**Statistical Conditioning**: LLMs learned from millions of documents written by real experts. When you assign a role, the model conditions its probability distributions to match patterns it saw from that type of author. + +**Reducing Ambiguity**: Without a role, the model averages across all possible responders. With a role, it narrows to a specific subset, making responses more focused and consistent. + +**Context Anchoring**: The role creates a persistent context anchor throughout the conversation. Every subsequent response is influenced by this initial framing. + +Think of it this way: if you ask "What should I do about this cough?" the model could respond as a doctor, a friend, a pharmacist, or a worried parent. Each would give different advice. By specifying the role upfront, you're telling the model which "voice" to use from its training data. + + +The model isn't pretending or role-playing in a theatrical sense. It's statistically biasing its outputs toward patterns it learned from real experts, professionals, and specialists during training. A "doctor" role activates medical knowledge pathways; a "poet" role activates literary patterns. + + +## Basic Role Patterns + +These foundational patterns work across most use cases. Start with these templates and customize them for your needs. + +### The Expert Pattern + +The most versatile pattern. Specify the field of expertise and years of experience to get authoritative, in-depth responses. Works well for technical questions, analysis, and professional advice. + + + +### The Professional Pattern + +Ground the role in a real-world context by specifying a job title and organization type. This adds institutional knowledge and professional norms to the response. + + + +### The Teacher Pattern + +Perfect for learning and explanations. Specifying the audience level ensures the response matches the learner's background, from beginners to advanced practitioners. + + + +## Advanced Role Constructions + +### Compound Roles + +Combine multiple identities to get responses that blend different perspectives. This pediatrician-parent combination produces advice that's both medically sound and practically tested. + + + +### Situational Roles + +Place the role in a specific scenario to shape both content and tone. Here, the code review context makes the AI constructive and educational rather than just critical. + + + +### Perspective Roles + +Get feedback from a specific stakeholder's point of view. A VC perspective evaluates viability and scalability differently than a customer or engineer would. + + + +## Role Categories and Examples + +Different domains benefit from different types of roles. Here are proven examples organized by category that you can adapt for your tasks. + +### Technical Roles + +**Software Architect**: Best for system design decisions, technology choices, and architectural trade-offs. The focus on maintainability steers responses toward practical, long-term solutions. + + + +**Security Specialist**: The attacker mindset is key here. This role produces threat-focused analysis that identifies vulnerabilities a defensive-only perspective might miss. + + + +**DevOps Engineer**: Ideal for deployment, automation, and infrastructure questions. The emphasis on reliability ensures production-ready recommendations. + + + +### Creative Roles + +**Copywriter**: The "award-winning" qualifier and conversion focus produce punchy, persuasive copy rather than generic marketing text. + + + +**Screenwriter**: Activates knowledge of dramatic structure, pacing, and dialogue conventions. Great for any narrative writing that needs tension and character voice. + + + +**UX Writer**: A specialized role for interface text. The focus on brevity and user guidance produces concise, action-oriented copy. + + + +### Analytical Roles + +**Business Analyst**: Bridges the gap between technical and non-technical stakeholders. Useful for requirement gathering, spec writing, and identifying gaps in project plans. + + + +**Research Scientist**: The emphasis on evidence and uncertainty acknowledgment produces balanced, well-sourced responses that distinguish facts from speculation. + + + +**Financial Analyst**: Combines quantitative analysis with risk assessment. The dual focus on returns and risk produces more balanced investment perspectives. + + + +### Educational Roles + +**Socratic Tutor**: Instead of giving answers, this role asks guiding questions. Excellent for deeper learning and helping students develop critical thinking skills. + + + +**Instructional Designer**: Structures learning for maximum retention. Use this role when you need to break down complex topics into teachable chunks with clear progression. + + + +## The Role Stack Technique + +For complex tasks, combine multiple role aspects into a single, layered identity. This technique stacks expertise, audience awareness, and style guidelines to create highly specialized responses. + +This example layers three elements: domain expertise (API documentation), audience (junior developers), and style guide (Google's conventions). Each layer constrains the output further. + + + +## Roles for Different Tasks + +
+
+ Code review + Senior developer + mentor +
+
+ Writing feedback + Editor + target audience member +
+
+ Business strategy + Consultant + industry expert +
+
+ Learning new topic + Patient teacher + practitioner +
+
+ Creative writing + Specific genre author +
+
+ Technical explanation + Expert + communicator +
+
+ Problem-solving + Domain specialist + generalist +
+
+ +## Anti-Patterns to Avoid + +### Overly Generic Roles + + + +### Conflicting Roles + + + +### Unrealistic Expertise + + + +## Real-World Prompt Examples + +### Technical Documentation + + + +### Creative Writing + + + +### Business Communication + + + +## Combining Roles with Other Techniques + +Roles work even better when combined with other prompting techniques: + +### Role + Few-Shot + +Combine a role with an example to show exactly how the role should respond. The example teaches tone and format while the role provides context and expertise. + + + +### Role + Chain of Thought + +The detective role naturally encourages step-by-step reasoning. Combining roles with chain-of-thought produces more transparent, verifiable problem-solving. + + + +## Summary + + +Role-based prompting is powerful because it focuses the model's vast knowledge, sets expectations for tone and style, provides implicit context, and makes outputs more consistent. + + + + +The key is **specificity**: the more detailed and realistic the role, the better the results. In the next chapter, we'll explore how to get consistent, structured outputs from your prompts. diff --git a/src/content/book/ar/05-structured-output.mdx b/src/content/book/ar/05-structured-output.mdx new file mode 100644 index 00000000..8236abee --- /dev/null +++ b/src/content/book/ar/05-structured-output.mdx @@ -0,0 +1,411 @@ +Getting consistent, well-formatted output is essential for production applications and efficient workflows. This chapter covers techniques for controlling exactly how AI models format their responses. + + +Structured output transforms AI responses from freeform text into actionable, parseable data. + + +## Why Structure Matters + + + +## Basic Formatting Techniques + +### Lists + +Lists are perfect for step-by-step instructions, ranked items, or collections of related points. They're easy to scan and parse. Use **numbered lists** when order matters (steps, rankings) and **bullet points** for unordered collections. + + + + +Specify the exact number of items you want, whether to include explanations, and if items should be bold or have a specific structure. + + +### Tables + +Tables excel at comparing multiple items across the same dimensions. They're ideal for feature comparisons, data summaries, and any information with consistent attributes. Always define your column headers explicitly. + + + + +Specify column names, expected data types (text, numbers, ratings), and how many rows you need. For complex comparisons, limit to 4-6 columns for readability. + + +### Headers and Sections + +Headers create a clear document structure, making long responses scannable and organized. Use them for reports, analyses, or any multi-part response. Hierarchical headers (##, ###) show relationships between sections. + +``` +Analyze this business proposal. + +Structure your response with these sections: +## Executive Summary +## Strengths +## Weaknesses +## Recommendations +## Risk Assessment +``` + + +List your sections in the order you want them. For consistency, specify what each section should contain (e.g., "Executive Summary: 2-3 sentences only"). + + +### Emphasis with Uppercase Directives + +Uppercase words act as strong signals to the model, emphasizing critical constraints or requirements. Use them sparingly for maximum impact—overuse dilutes their effectiveness. + +**Common Uppercase Directives:** + + + +``` +Summarize this article. + +IMPORTANT: Keep the summary under 100 words. +NEVER add information not present in the original. +ALWAYS maintain the original tone and perspective. +DO NOT include your own opinions or analysis. +``` + + +If everything is uppercase or marked as critical, nothing stands out. Reserve these directives for genuinely important constraints. + + +## JSON Output + +JSON (JavaScript Object Notation) is the most popular format for structured AI output. It's machine-readable, widely supported by programming languages, and perfect for APIs, databases, and automation workflows. The key to reliable JSON is providing a clear schema. + +### Basic JSON Request + +Start with a template showing the exact structure you want. Include field names, data types, and example values. This acts as a contract the model will follow. + + + +### Complex JSON Structures + +For nested data, use hierarchical JSON with objects inside objects, arrays of objects, and mixed types. Define each level clearly and use TypeScript-style annotations (`"positive" | "negative"`) to constrain values. + +``` +Analyze this product review and return JSON: + +{ + "review_id": "string (generate unique)", + "sentiment": { + "overall": "positive" | "negative" | "mixed" | "neutral", + "score": 0.0-1.0 + }, + "aspects": [ + { + "aspect": "string (e.g., 'price', 'quality')", + "sentiment": "positive" | "negative" | "neutral", + "mentions": ["exact quotes from review"] + } + ], + "purchase_intent": { + "would_recommend": boolean, + "confidence": 0.0-1.0 + }, + "key_phrases": ["string array of notable phrases"] +} + +Return ONLY valid JSON, no additional text. + +Review: "[review text]" +``` + +### Ensuring Valid JSON + +Models sometimes add explanatory text or markdown formatting around JSON. Prevent this with explicit instructions about output format. You can request raw JSON or JSON inside code blocks—choose based on your parsing needs. + +Add explicit instructions: + +``` +IMPORTANT: +- Return ONLY the JSON object, no markdown code blocks +- Ensure all strings are properly escaped +- Use null for missing values, not undefined +- Validate that the output is parseable JSON +``` + +Or request code blocks by asking the model to wrap its output: + +```` +Return the result as a JSON code block: +```json +{ ... } +``` +```` + +## YAML Output + +YAML is more human-readable than JSON, using indentation instead of brackets. It's the standard for configuration files (Docker, Kubernetes, GitHub Actions) and works well when the output will be read by humans or used in DevOps contexts. YAML is sensitive to indentation, so be specific about formatting requirements. + + + +## XML Output + +XML is still required for many enterprise systems, SOAP APIs, and legacy integrations. It's more verbose than JSON but offers features like attributes, namespaces, and CDATA sections for complex data. Specify element names, nesting structure, and where to use attributes vs. child elements. + +``` +Convert this data to XML format: + +Requirements: +- Root element: +- Each item in element +- Include attributes where appropriate +- Use CDATA for description text + +Data: [book data] +``` + +## Custom Formats + +Sometimes standard formats don't fit your needs. You can define any custom format by providing a clear template. Custom formats work well for reports, logs, or domain-specific outputs that will be read by humans. + +### Structured Analysis Format + +Use delimiters (===, ---, [SECTION]) to create scannable documents with clear boundaries between sections. This format is great for code reviews, audits, and analyses. + +``` +Analyze this code using this exact format: + +=== CODE ANALYSIS === + +[SUMMARY] +One paragraph overview + +[ISSUES] +• CRITICAL: [issue] — [file:line] +• WARNING: [issue] — [file:line] +• INFO: [issue] — [file:line] + +[METRICS] +Complexity: [Low/Medium/High] +Maintainability: [score]/10 +Test Coverage: [estimated %] + +[RECOMMENDATIONS] +1. [Priority 1 recommendation] +2. [Priority 2 recommendation] + +=== END ANALYSIS === +``` + +### Fill-in-the-Blank Format + +Templates with blanks (___) guide the model to fill in specific fields while maintaining exact formatting. This approach is excellent for forms, briefs, and standardized documents where consistency matters. + +``` +Complete this template for the given product: + +PRODUCT BRIEF +───────────── +Name: _______________ +Tagline: _______________ +Target User: _______________ +Problem Solved: _______________ +Key Features: + 1. _______________ + 2. _______________ + 3. _______________ +Differentiator: _______________ + +Product: [product description] +``` + +## Typed Responses + +Typed responses define categories or entity types that the model should recognize and label. This technique is essential for Named Entity Recognition (NER), classification tasks, and any extraction where you need to categorize information consistently. Define your types clearly with examples. + + + +## Multi-Part Structured Responses + +When you need comprehensive output covering multiple aspects, define distinct parts with clear boundaries. Specify exactly what goes in each part—format, length, and content type. This prevents the model from blending sections or omitting parts. + +``` +Research this topic and provide: + +### PART 1: EXECUTIVE SUMMARY +[2-3 sentence overview] + +### PART 2: KEY FINDINGS +[Exactly 5 bullet points] + +### PART 3: DATA TABLE +| Metric | Value | Source | +|--------|-------|--------| +[Include 5 rows minimum] + +### PART 4: RECOMMENDATIONS +[Numbered list of 3 actionable recommendations] + +### PART 5: FURTHER READING +[3 suggested resources with brief descriptions] +``` + +## Conditional Formatting + +Conditional formatting lets you define different output formats based on the input's characteristics. This is powerful for classification, triage, and routing systems where the response format should vary based on what the model detects. Use clear if/then logic with explicit output templates for each case. + + + +## Arrays and Lists in JSON + +Extracting multiple items into arrays requires careful schema definition. Specify the array structure, what each item should contain, and how to handle edge cases (empty arrays, single items). Including a count field helps verify completeness. + +``` +Extract all action items from this meeting transcript. + +Return as JSON array: +{ + "action_items": [ + { + "task": "string describing the task", + "assignee": "person name or 'Unassigned'", + "deadline": "date if mentioned, else null", + "priority": "high" | "medium" | "low", + "context": "relevant quote from transcript" + } + ], + "total_count": number +} + +Transcript: "[meeting transcript]" +``` + +## Validation Instructions + +Self-validation prompts the model to check its own output before responding. This catches common issues like missing sections, placeholder text, or constraint violations. The model will iterate internally to fix problems, improving output quality without additional API calls. + +``` +Generate the report, then: + +VALIDATION CHECKLIST: +□ All required sections present +□ No placeholder text remaining +□ All statistics include sources +□ Word count within 500-700 words +□ Conclusion ties back to introduction + +If any check fails, fix before responding. +``` + +## Handling Optional Fields + +Real-world data often has missing values. Explicitly instruct the model on how to handle optional fields—using `null` is cleaner than empty strings and easier to process programmatically. Also prevent "hallucination" of missing data by emphasizing that the model should never invent information. + +``` +Extract contact information. Use null for missing fields. + +{ + "name": "string (required)", + "email": "string or null", + "phone": "string or null", + "company": "string or null", + "role": "string or null", + "linkedin": "URL string or null" +} + +IMPORTANT: +- Never invent information not in the source +- Use null, not empty strings, for missing data +- Phone numbers in E.164 format if possible +``` + +## Summary + + +Be explicit about format, use examples, specify types, handle edge cases with null values, and ask the model to validate its own output. + + + + +Structured outputs are essential for building reliable AI-powered applications. In the next chapter, we'll explore chain-of-thought prompting for complex reasoning tasks. diff --git a/src/content/book/ar/06-chain-of-thought.mdx b/src/content/book/ar/06-chain-of-thought.mdx new file mode 100644 index 00000000..e579be5d --- /dev/null +++ b/src/content/book/ar/06-chain-of-thought.mdx @@ -0,0 +1,363 @@ +Chain of Thought (CoT) prompting is a technique that dramatically improves AI performance on complex reasoning tasks by asking the model to show its work step by step. + + +Just like a math teacher asking students to show their work, CoT prompting asks the AI to make its reasoning visible. + + +## The Problem CoT Solves + +AI models can struggle with multi-step reasoning when asked to jump directly to an answer. + + + +## Basic CoT Prompts + +### Simple Trigger Phrases + +Add one of these to your prompts: + +
+
"Let's think step by step."
+
"Think through this carefully."
+
"Work through this problem methodically."
+
"Show your reasoning at each step."
+
"Explain your thought process."
+
+ +### Explicit Step Request + + + +## Zero-Shot vs Few-Shot CoT + +There are two main approaches to Chain of Thought prompting, each with different trade-offs between simplicity and control. + +### Zero-Shot CoT + +The simplest approach—just add a trigger phrase and let the model figure out how to reason. No examples needed. This works surprisingly well for many problems, though you have less control over the reasoning format. + + + +**Example Output:** +``` +Let's think step by step. +- John starts with 3 apples +- Half of 3 is 1.5, but we can't split apples +- If we round down: John gives 1 apple, keeps 2 +- After buying 4 more: 2 + 4 = 6 apples + +Answer: 6 apples +``` + +### Few-Shot CoT + +For more consistent results, show the model exactly how you want it to reason by providing worked examples. This gives you control over the reasoning style, format, and level of detail. The model will mimic your demonstrated pattern. + + + +**Example Output:** +``` +A: Let's work through this: +- Regular price: $3, Quantity: 12 +- Since 12 ≥ 10, the 25% discount applies +- Regular total: 12 × $3 = $36 +- Discount: 25% of $36 = $9 +- Final price: $36 - $9 = $27 +``` + +## Structured CoT Formats + +For consistent, reproducible reasoning, use structured formats with named steps. These frameworks ensure the model doesn't skip important stages and makes outputs easier to parse and verify. + +### The BREAK Format + +A memorable acronym that guides the model through a complete problem-solving cycle, from understanding to verification. + + + +### The Reasoning Template + +A more formal structure that separates inputs, goals, and execution. Excellent for technical problems where you need clear documentation of the solution process. + + + +**Example Output:** +``` +GIVEN: 8L/100km, tank 45L, $1.50/L, drive 300km +GOAL: Calculate fuel cost +APPROACH: Fuel needed × cost per liter +STEPS: +1. Fuel = (300 ÷ 100) × 8 = 24 liters +2. Cost = 24 × $1.50 = $36 +VERIFICATION: 24L < 45L tank ✓ +ANSWER: $36 +``` + +## CoT for Different Problem Types + +Different problem types benefit from different CoT approaches. Here are patterns optimized for common scenarios. + +### Mathematical Reasoning + +Math problems benefit most from CoT because each step builds on the previous one. Errors compound, so showing work helps catch mistakes early. The model should clearly label each calculation. + + + +**Example Output:** +``` +Q1: $1,200,000 (given) +Q2: $1,200,000 × 1.15 = $1,380,000 +Q3: $1,380,000 × 0.90 = $1,242,000 +Q4: $1,242,000 × 1.25 = $1,552,500 + +Total: $5,374,500 +``` + +### Logical Reasoning + +Logic puzzles require systematic elimination and hypothesis testing. CoT helps the model track constraints, test possibilities, and verify that all conditions are satisfied. The key is methodical exploration rather than guessing. + + + +**Example Output:** +``` +From clue 3: Bob = teacher +→ Alice and Carol are engineer/doctor + +If Carol = engineer: +- Carol has dog (clue 2) +- Alice = doctor, has fish (clue 1) +- Bob has cat + +Verify: All 4 clues satisfied ✓ +Answer: Alice (doctor, fish), Bob (teacher, cat), Carol (engineer, dog) +``` + +### Code Debugging + +Debugging benefits from CoT because it forces the model to trace execution rather than guess at bugs. By walking through the code with concrete values, the actual behavior becomes visible and discrepancies with expected behavior are exposed. + + + +**Example Output:** +``` +Trace [2, 3, 4, 6]: +n=2: total += 1 → 1 (wait, adding 1 not n!) +n=3: skip (odd) +n=4: total = 2 +n=6: total = 3 + +BUG: "total += 1" should be "total += n" +Expected: 12, Got: 3 +Fix: Change to "total += n" +``` + +## Self-Consistency with CoT + +For critical problems, don't rely on a single reasoning path. Generate multiple independent solutions and compare results. If different approaches converge on the same answer, confidence is high. Disagreement signals the need for careful review. + + + +**Example Output:** +``` +Approach 1 (Algebra): c + w = 30, 2c + 4w = 74 → c=23, w=7 +Approach 2 (Guess): Try 23/7 → 46 + 28 = 74 ✓ +Approach 3 (Logic): 30 chickens = 60 legs, need 14 more → 7 cows + +All agree: 23 chickens, 7 cows +``` + +## CoT for Decision Making + +Decisions involve weighing trade-offs across multiple dimensions. CoT ensures all relevant factors are considered systematically rather than jumping to conclusions. This structured approach also documents the reasoning for future reference. + + + +**Example Output:** +``` +FACTORS: +- Team size (5): Too small for microservices ❌ +- Scale (100 DAU): No scaling need ❌ +- Velocity: Monolith = faster iteration ❌ +- Future growth: Uncertain timeline ⚠️ + +WEIGHING: 3 strong against, 1 weak for + +RECOMMENDATION: Stay monolith, use clear module +boundaries to ease future transition. +``` + +## When to Use CoT + +
+
+

Use CoT For

+
+

**Math problems** — Reduces calculation errors

+

**Logic puzzles** — Prevents skipped steps

+

**Complex analysis** — Organizes thinking

+

**Code debugging** — Traces execution

+

**Decision making** — Weighs trade-offs

+
+
+
+

Skip CoT For

+
+

**Simple Q&A** — Unnecessary overhead

+

**Creative writing** — Can constrain creativity

+

**Factual lookups** — No reasoning needed

+

**Translation** — Direct task

+

**Summarization** — Usually straightforward

+
+
+
+ +## CoT Limitations + +While powerful, Chain of Thought isn't a silver bullet. Understanding its limitations helps you apply it appropriately. + +1. **Increased token usage** — More output means higher costs +2. **Not always needed** — Simple tasks don't benefit +3. **Can be verbose** — May need to ask for conciseness +4. **Reasoning can be flawed** — CoT doesn't guarantee correctness + +## Summary + + +CoT dramatically improves complex reasoning by making implicit steps explicit. Use it for math, logic, analysis, and debugging. Trade-off: better accuracy for more tokens. + + + + +In the next chapter, we'll explore few-shot learning—teaching the model through examples. diff --git a/src/content/book/ar/07-few-shot-learning.mdx b/src/content/book/ar/07-few-shot-learning.mdx new file mode 100644 index 00000000..24e98f1d --- /dev/null +++ b/src/content/book/ar/07-few-shot-learning.mdx @@ -0,0 +1,478 @@ +Few-shot learning is one of the most powerful prompting techniques. By providing examples of what you want, you can teach the model complex tasks without any fine-tuning. + + +Just like humans learn by seeing examples, AI models can learn patterns from the examples you provide in your prompt. + + +## What is Few-Shot Learning? + +Few-shot learning shows the model examples of input-output pairs before asking it to perform the same task. The model learns the pattern from your examples and applies it to new inputs. + + + +
+
+
0
+
Zero-shot
+
+
+
1
+
One-shot
+
+
+
2-5
+
Few-shot
+
+
+
5+
+
Many-shot
+
+
+ +## Why Examples Work + + + +Examples communicate: +- **Format**: How output should be structured +- **Style**: Tone, length, vocabulary +- **Logic**: The reasoning pattern to follow +- **Edge cases**: How to handle special situations + +## Basic Few-Shot Pattern + +The fundamental structure of few-shot prompting follows a simple pattern: show examples, then ask for the new task. Consistency in formatting between examples is crucial. The model learns from the pattern you establish. + +``` +[Example 1] +Input: [input 1] +Output: [output 1] + +[Example 2] +Input: [input 2] +Output: [output 2] + +[Example 3] +Input: [input 3] +Output: [output 3] + +Now do this one: +Input: [new input] +Output: +``` + +## Few-Shot for Classification + +Classification is one of the strongest use cases for few-shot learning. By showing examples of each category, you define the boundaries between classes more precisely than instructions alone could achieve. + +### Sentiment Analysis + + +Sentiment analysis classifies text by emotional tone: positive, negative, neutral, or mixed. It's widely used for customer feedback, social media monitoring, and brand perception tracking. + + +Sentiment classification benefits from showing examples of each sentiment type, especially edge cases like "mixed" sentiment that might be ambiguous. + + + +### Topic Classification + +For multi-class categorization, include at least one example per category. This helps the model understand your specific taxonomy, which may differ from its default understanding. + + + +## Few-Shot for Transformation + +Transformation tasks convert input from one form to another while preserving meaning. Examples are essential here because they define exactly what "transformation" means for your use case. + +### Text Rewriting + +Style transformation requires examples that show the exact tone shift you want. Abstract instructions like "make it professional" are interpreted differently. Examples make it concrete. + + + +### Format Conversion + +Format conversion tasks benefit from examples showing edge cases and ambiguous inputs. The model learns your specific conventions for handling tricky cases. + + + +## Few-Shot for Generation + +Generation tasks create new content following a learned pattern. Examples establish length, structure, tone, and what details to highlight. These are hard to specify in instructions alone. + +### Product Descriptions + +Marketing copy benefits enormously from examples because they capture brand voice, feature emphasis, and persuasive techniques that are difficult to describe abstractly. + + + +### Code Documentation + + +Good documentation explains what code does, its parameters, return values, and usage examples. Consistent docstrings enable auto-generated API docs and help IDEs provide better code completion. + + +Documentation style varies widely between projects. Examples teach your specific format, what to include (args, returns, examples), and the level of detail expected. + +>> calculate_bmi(70, 1.75) + 22.86 +""" + +Now document: +Function: +def is_palindrome(text): + cleaned = ''.join(c.lower() for c in text if c.isalnum()) + return cleaned == cleaned[::-1] + +Documentation:`} /> + +## Few-Shot for Extraction + +Extraction tasks pull structured information from unstructured text. Examples define which entities matter, how to format output, and how to handle cases where information is missing or ambiguous. + +### Entity Extraction + + +Named Entity Recognition (NER) identifies and classifies named entities in text into categories like persons, organizations, locations, dates, and products. It's fundamental for information retrieval and knowledge graphs. + + +NER benefits from examples showing your specific entity types and how to handle entities that could fit multiple categories. + + + +### Structured Data Extraction + +Extracting structured data from natural language requires examples showing how to handle missing fields, implicit information, and varying input formats. + + + +## Advanced Few-Shot Techniques + +Beyond basic few-shot, several techniques can improve results for complex tasks. + +### Diverse Examples + +Diversity in examples is more valuable than quantity. Cover different scenarios, edge cases, and potential ambiguities rather than showing similar examples repeatedly. + + + +### Negative Examples + + +Showing "good" vs "bad" examples is called contrastive learning. It helps the model understand not just what you want, but what to avoid. This is especially useful for style and quality judgments. + + +Sometimes showing what *not* to do is as valuable as showing correct examples. Negative examples help the model understand boundaries and avoid common mistakes. + + + +### Edge Case Examples + +Edge cases often determine whether a solution works in production. Including unusual inputs in your examples prevents the model from failing on real-world data that doesn't fit the "happy path." + + + +## How Many Examples? + +
+
+ Simple classification + 2-3 + One per category minimum +
+
+ Complex formatting + 3-5 + Show variations +
+
+ Nuanced style + 4-6 + Capture full range +
+
+ Edge cases + 1-2 + Alongside normal examples +
+
+ +## Example Quality Matters + + + +## Combining Few-Shot with Other Techniques + +Few-shot learning combines powerfully with other prompting techniques. The examples provide the "what" while other techniques can add context, reasoning, or structure. + +### Few-Shot + Role + +Adding a role gives the model context for *why* it's doing the task, which can improve quality and consistency. + +``` +You are a legal contract reviewer. + +[examples of contract clause analysis] + +Now analyze: [new clause] +``` + +### Few-Shot + CoT + +Combining few-shot with Chain of Thought shows not just *what* answer to give, but *how* to reason through to that answer. This is powerful for tasks requiring judgment. + +``` +Classify and explain reasoning. + +Review: "Great features but overpriced" +Thinking: The review mentions positive aspects ("great features") +but also a significant negative ("overpriced"). The negative seems +to outweigh the positive based on the "but" conjunction. +Classification: Mixed-Negative + +[more examples with reasoning] + +Now classify with reasoning: +Review: "Exactly what I needed, arrived faster than expected" +``` + +## Summary + + +Few-shot learning teaches through demonstration and is often more effective than instructions alone. Use 2-5 diverse, correct examples and combine with other techniques for best results. + + + + +In the next chapter, we'll explore iterative refinement: the art of improving prompts through successive attempts. diff --git a/src/content/book/ar/08-iterative-refinement.mdx b/src/content/book/ar/08-iterative-refinement.mdx new file mode 100644 index 00000000..769f879a --- /dev/null +++ b/src/content/book/ar/08-iterative-refinement.mdx @@ -0,0 +1,387 @@ +Prompt engineering is rarely a one-shot process. The best prompts emerge through iteration—testing, observing, and refining until you achieve the desired results. + + +Think of your first prompt as a rough draft. Even experienced prompt engineers rarely nail it on the first try. + + +## The Iteration Cycle + +Effective prompt refinement follows a predictable cycle: write, test, analyze, and improve. Each iteration brings you closer to a prompt that reliably produces the results you need. + + + +## Common Refinement Patterns + +Most prompt failures fall into a handful of categories. Learning to recognize these patterns lets you quickly diagnose and fix issues without starting from scratch. + +### Problem: Output Too Long + +One of the most common issues. Without explicit constraints, models tend to be thorough rather than concise. + + + +### Problem: Output Too Vague + +Vague prompts produce vague outputs. The model can't read your mind about what "better" means or which aspects matter most to you. + + + +### Problem: Wrong Tone + +Tone is subjective and varies by context. What sounds "professional" to the model might not match your organization's voice or the relationship with your recipient. + + + +### Problem: Missing Key Information + +Open-ended requests get open-ended responses. If you need specific types of feedback, you must ask for them explicitly. + + + +### Problem: Inconsistent Format + +Without a template, the model will structure each response differently, making comparison difficult and automation impossible. + + + +## Systematic Refinement Approach + +Random changes waste time. A systematic approach helps you identify problems quickly and fix them efficiently. + +### Step 1: Diagnose the Issue + +Before changing anything, identify what's actually wrong. Use this diagnostic table to map symptoms to solutions: + +
+
+ Symptom + Likely Cause + Solution +
+
+ Too long + No length constraint + Add word/sentence limits +
+
+ Too short + Lacks detail request + Ask for elaboration +
+
+ Off-topic + Vague instructions + Be more specific +
+
+ Wrong format + Format not specified + Define exact structure +
+
+ Wrong tone + Audience not clear + Specify audience/style +
+
+ Inconsistent + No examples provided + Add few-shot examples +
+
+ +### Step 2: Make Targeted Changes + +Resist the urge to rewrite everything. Changing multiple variables at once makes it impossible to know what helped and what hurt. Make one change, test it, then proceed: + +``` +Iteration 1: Add length constraint +Iteration 2: Specify format +Iteration 3: Add example +Iteration 4: Refine tone instructions +``` + +### Step 3: Document What Works + +Prompt engineering knowledge is easily lost. Keep a log of what you tried and why. This saves time when you revisit the prompt later or face similar challenges: + +```markdown +## Prompt: Customer Email Response + +### Version 1 (too formal) +"Write a response to this customer complaint." + +### Version 2 (better tone, still missing structure) +"Write a friendly but professional response to this complaint. +Show empathy first." + +### Version 3 (final - good results) +"Write a response to this customer complaint. Structure: +1. Acknowledge their frustration (1 sentence) +2. Apologize specifically (1 sentence) +3. Explain solution (2-3 sentences) +4. Offer additional help (1 sentence) + +Tone: Friendly, professional, empathetic but not groveling." +``` + +## Real-World Iteration Example + +Let's walk through a complete iteration cycle to see how each refinement builds on the last. Notice how each version addresses specific shortcomings of the previous one. + +### Task: Generate Product Names + + + +## Refinement Strategies by Task Type + +Different tasks fail in predictable ways. Knowing the common failure modes helps you diagnose and fix issues faster. + +### For Content Generation + +Content generation often produces generic, off-target, or poorly formatted output. The fix usually involves being more specific about constraints, providing concrete examples, or defining your brand voice explicitly. + + + +### For Code Generation + +Code output can fail technically (syntax errors, wrong language features) or architecturally (poor patterns, missing cases). Technical issues need version/environment specifics; architectural issues need design guidance. + + + +### For Analysis + +Analysis tasks often produce surface-level or unstructured results. Guide the model with specific frameworks (SWOT, Porter's Five Forces), request multiple viewpoints, or provide a template for the output structure. + + + +### For Q&A + +Question-answering can be too terse or too verbose, and may lack confidence indicators or sources. Specify the detail level you need and whether you want citations or uncertainty expressed. + + + +## The Feedback Loop Technique + +Here's a meta-technique: use the model itself to help improve your prompts. Share what you tried, what you got, and what you wanted. The model can often suggest improvements you hadn't considered. + +``` +I used this prompt: +"[your prompt]" + +And got this output: +"[model output]" + +I wanted something more [describe gap]. How should I modify +my prompt to get better results? +``` + +## A/B Testing Prompts + +For prompts that will be used repeatedly or at scale, don't just pick the first one that works. Test variations to find the most reliable and highest-quality approach. + +``` +Prompt A: "Summarize this article in 3 bullet points." +Prompt B: "Extract the 3 most important insights from this article." +Prompt C: "What are the key takeaways from this article? List 3." +``` + +Run each multiple times, compare: +- Consistency of output +- Quality of information +- Relevance to your needs + +## When to Stop Iterating + +Perfection is the enemy of good enough. Know when your prompt is ready for use and when you're just polishing for diminishing returns. + +
+
+

Ready to Ship

+
+

Output consistently meets requirements

+

Edge cases are handled appropriately

+

Format is reliable and parseable

+

Further improvements show diminishing returns

+
+
+
+

Keep Iterating

+
+

Output is inconsistent across runs

+

Edge cases cause failures

+

Critical requirements are missed

+

You haven't tested enough variations

+
+
+
+ +## Version Control for Prompts + +Prompts are code. For any prompt used in production, treat it with the same rigor: version control, changelogs, and the ability to roll back if something breaks. + + +prompts.chat includes automatic version history for your prompts. Every edit is saved, so you can compare versions and restore previous iterations with one click. + + +For self-managed prompts, use a folder structure: + +``` +prompts/ +├── customer-response/ +│ ├── v1.0.txt # Initial version +│ ├── v1.1.txt # Fixed tone issue +│ ├── v2.0.txt # Major restructure +│ └── current.txt # Symlink to active version +└── changelog.md # Document changes +``` + +## Summary + + +Start simple, observe carefully, change one thing at a time, document what works, and know when to stop. The best prompts aren't written—they're discovered through systematic iteration. + + + + +## Practice: Improve This Prompt + +Try improving this weak prompt yourself. Edit it, then use AI to compare your version with the original: + + + +In the next chapter, we'll explore JSON and YAML prompting for structured data applications. diff --git a/src/content/book/ar/09-json-yaml-prompting.mdx b/src/content/book/ar/09-json-yaml-prompting.mdx new file mode 100644 index 00000000..318619da --- /dev/null +++ b/src/content/book/ar/09-json-yaml-prompting.mdx @@ -0,0 +1,586 @@ +Structured data formats like JSON and YAML are essential for building applications that consume AI outputs programmatically. This chapter covers techniques for reliable structured output generation. + + +JSON and YAML transform AI outputs from freeform text into structured, type-safe data that code can consume directly. + + +## Why Structured Formats? + + + +## JSON Prompting Basics + +JSON (JavaScript Object Notation) is the most common format for programmatic AI outputs. Its strict syntax makes it easy to parse, but also means small errors can break your entire pipeline. + +### Do's and Don'ts: Requesting JSON + + + +### Simple JSON Output + +Start with a schema showing the expected structure. The model will fill in values based on the input text. + +``` +Extract the following information as JSON: + +{ + "name": "string", + "age": number, + "email": "string" +} + +Text: "Contact John Smith, 34 years old, at john@example.com" +``` + +Output: +```json +{ + "name": "John Smith", + "age": 34, + "email": "john@example.com" +} +``` + +### Nested JSON Structures + +Real-world data often has nested relationships. Define each level of your schema clearly, especially for arrays of objects. + +``` +Parse this order into JSON: + +{ + "order_id": "string", + "customer": { + "name": "string", + "email": "string" + }, + "items": [ + { + "product": "string", + "quantity": number, + "price": number + } + ], + "total": number +} + +Order: "Order #12345 for Jane Doe (jane@email.com): 2x Widget ($10 each), +1x Gadget ($25). Total: $45" +``` + +### Ensuring Valid JSON + + +Models often wrap JSON in markdown code blocks or add explanatory text. Be explicit about wanting raw JSON only. + + +Add explicit instructions: + +``` +CRITICAL: Return ONLY valid JSON. No markdown, no explanation, +no additional text before or after the JSON object. + +If a field cannot be determined, use null. +Ensure all strings are properly quoted and escaped. +Numbers should not be quoted. +``` + +## YAML Prompting Basics + +YAML is more human-readable than JSON and supports comments. It's the standard for configuration files, especially in DevOps (Docker, Kubernetes, GitHub Actions). + +### Simple YAML Output + +YAML uses indentation instead of braces. Provide a template showing the expected structure. + +``` +Generate a configuration file in YAML format: + +server: + host: string + port: number + ssl: boolean +database: + type: string + connection_string: string + +Requirements: Production server on port 443 with SSL, PostgreSQL database +``` + +Output: +```yaml +server: + host: "0.0.0.0" + port: 443 + ssl: true +database: + type: "postgresql" + connection_string: "postgresql://user:pass@localhost:5432/prod" +``` + +### Complex YAML Structures + +For complex configurations, be specific about requirements. The model knows common patterns for tools like GitHub Actions, Docker Compose, and Kubernetes. + +``` +Generate a GitHub Actions workflow in YAML: + +Requirements: +- Trigger on push to main and pull requests +- Run on Ubuntu latest +- Steps: checkout, setup Node 18, install dependencies, run tests +- Cache npm dependencies +``` + +## Type Definitions in Prompts + +Type definitions give the model a precise contract for output structure. They're more explicit than examples and easier to validate programmatically. + +### Using TypeScript-like Types + +TypeScript interfaces are familiar to developers and precisely describe optional fields, union types, and arrays. The prompts.chat platform uses this approach for structured prompts. + + + +### JSON Schema Definition + + +JSON Schema is a formal specification for describing JSON structure. It's supported by many validation libraries and API tools. + + +JSON Schema provides constraints like min/max values, required fields, and regex patterns: + +``` +Extract data according to this JSON Schema: + +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "type": "object", + "required": ["title", "author", "year"], + "properties": { + "title": { "type": "string" }, + "author": { "type": "string" }, + "year": { "type": "integer", "minimum": 1000, "maximum": 2100 }, + "genres": { + "type": "array", + "items": { "type": "string" } + }, + "rating": { + "type": "number", + "minimum": 0, + "maximum": 5 + } + } +} + +Book: "1984 by George Orwell (1949) - A dystopian masterpiece. +Genres: Science Fiction, Political Fiction. Rated 4.8/5" +``` + +## Handling Arrays + +Arrays require special attention. Specify whether you need a fixed number of items or a variable-length list, and how to handle empty cases. + +### Fixed-Length Arrays + +When you need exactly N items, state it explicitly. The model will ensure the array has the right length. + +``` +Extract exactly 3 key points as JSON: + +{ + "key_points": [ + "string (first point)", + "string (second point)", + "string (third point)" + ] +} + +Article: [article text] +``` + +### Variable-Length Arrays + +For variable-length arrays, specify what to do when there are zero items. Including a count field helps verify extraction completeness. + +``` +Extract all mentioned people as JSON: + +{ + "people": [ + { + "name": "string", + "role": "string or null if not mentioned" + } + ], + "count": number +} + +If no people are mentioned, return empty array. + +Text: [text] +``` + +## Enum Values and Constraints + +Enums restrict values to a predefined set. This is crucial for classification tasks and anywhere you need consistent, predictable outputs. + +### Do's and Don'ts: Enum Values + + + +### String Enums + +List allowed values explicitly. Use "MUST be one of" language to enforce strict matching. + +``` +Classify this text. The category MUST be one of these exact values: +- "technical" +- "business" +- "creative" +- "personal" + +Return JSON: +{ + "text": "original text (truncated to 50 chars)", + "category": "one of the enum values above", + "confidence": number between 0 and 1 +} + +Text: [text to classify] +``` + +### Validated Numbers + +Numeric constraints prevent out-of-range values. Specify the type (integer vs float) and valid range. + +``` +Rate these aspects. Each score MUST be an integer from 1 to 5. + +{ + "quality": 1-5, + "value": 1-5, + "service": 1-5, + "overall": 1-5 +} + +Review: [review text] +``` + +## Handling Missing Data + +Real-world text often lacks some information. Define how the model should handle missing data to avoid hallucinated values. + +### Do's and Don'ts: Missing Information + + + +### Null Values + +Explicitly allow null and instruct the model not to invent information. This is safer than having the model guess. + +``` +Extract information. Use null for any field that cannot be +determined from the text. Do NOT invent information. + +{ + "company": "string or null", + "revenue": "number or null", + "employees": "number or null", + "founded": "number (year) or null", + "headquarters": "string or null" +} + +Text: "Apple, headquartered in Cupertino, was founded in 1976." +``` + +Output: +```json +{ + "company": "Apple", + "revenue": null, + "employees": null, + "founded": 1976, + "headquarters": "Cupertino" +} +``` + +### Default Values + +When defaults make sense, specify them in the schema. This is common for configuration extraction. + +``` +Extract settings with these defaults if not specified: + +{ + "theme": "light" (default) | "dark", + "language": "en" (default) | other ISO code, + "notifications": true (default) | false, + "fontSize": 14 (default) | number +} + +User preferences: "I want dark mode and larger text (18px)" +``` + +## Multi-Object Responses + +Often you need to extract multiple items from a single input. Define the array structure and any sorting/grouping requirements. + +### Array of Objects + +For lists of similar items, define the object schema once and specify it's an array. + +``` +Parse this list into JSON array: + +[ + { + "task": "string", + "priority": "high" | "medium" | "low", + "due": "ISO date string or null" + } +] + +Todo list: +- Finish report (urgent, due tomorrow) +- Call dentist (low priority) +- Review PR #123 (medium, due Friday) +``` + +### Grouped Objects + +Grouping tasks require categorization logic. The model will sort items into the categories you define. + +``` +Categorize these items into JSON: + +{ + "fruits": ["string array"], + "vegetables": ["string array"], + "other": ["string array"] +} + +Items: apple, carrot, bread, banana, broccoli, milk, orange, spinach +``` + +## YAML for Configuration Generation + +YAML shines for DevOps configurations. The model knows standard patterns for common tools and can generate production-ready configs. + +### Do's and Don'ts: YAML Configs + + + +### Docker Compose + +Specify the services you need and any special requirements. The model will handle the YAML syntax and best practices. + +``` +Generate a docker-compose.yml for: +- Node.js app on port 3000 +- PostgreSQL database +- Redis cache +- Nginx reverse proxy + +Include: +- Health checks +- Volume persistence +- Environment variables from .env file +- Network isolation +``` + +### Kubernetes Manifests + +Kubernetes manifests are verbose but follow predictable patterns. Provide the key parameters and the model will generate compliant YAML. + +``` +Generate Kubernetes deployment YAML: + +Deployment: +- Name: api-server +- Image: myapp:v1.2.3 +- Replicas: 3 +- Resources: 256Mi memory, 250m CPU (requests) +- Health checks: /health endpoint +- Environment from ConfigMap: api-config + +Also generate matching Service (ClusterIP, port 8080) +``` + +## Validation and Error Handling + +For production systems, build validation into your prompts. This catches errors before they propagate through your pipeline. + +### Self-Validation Prompt + +Ask the model to validate its own output against rules you specify. This catches format errors and invalid values. + +``` +Extract data as JSON, then validate your output. + +Schema: +{ + "email": "valid email format", + "phone": "E.164 format (+1234567890)", + "date": "ISO 8601 format (YYYY-MM-DD)" +} + +After generating JSON, check: +1. Email contains @ and valid domain +2. Phone starts with + and contains only digits +3. Date is valid and parseable + +If validation fails, fix the issues before responding. + +Text: [contact information] +``` + +### Error Response Format + +Define separate success and error formats. This makes programmatic handling much easier. + +``` +Attempt to extract data. If extraction fails, return error format: + +Success format: +{ + "success": true, + "data": { ... extracted data ... } +} + +Error format: +{ + "success": false, + "error": "description of what went wrong", + "partial_data": { ... any data that could be extracted ... } +} +``` + +## JSON vs YAML: When to Use Which + +
+
+
Use JSON When
+
+

Programmatic parsing needed

+

API responses

+

Strict type requirements

+

JavaScript/Web integration

+

Compact representation

+
+
+
+
Use YAML When
+
+

Human readability matters

+

Configuration files

+

Comments are needed

+

DevOps/Infrastructure

+

Deep nested structures

+
+
+
+ +## Prompts.chat Structured Prompts + +On prompts.chat, you can create prompts with structured output formats: + +``` +When creating a prompt on prompts.chat, you can specify: + +Type: STRUCTURED +Format: JSON or YAML + +The platform will: +- Validate outputs against your schema +- Provide syntax highlighting +- Enable easy copying of structured output +- Support template variables in your schema +``` + +## Common Pitfalls + + +These three issues cause most JSON parsing failures. Check for them when your code can't parse AI output. + + +### 1. Markdown Code Blocks + +**Problem:** Model wraps JSON in ```json blocks + +**Solution:** +``` +Return ONLY the JSON object. Do not wrap in markdown code blocks. +Do not include ```json or ``` markers. +``` + +### 2. Trailing Commas + +**Problem:** Invalid JSON due to trailing commas + +**Solution:** +``` +Ensure valid JSON syntax. No trailing commas after the last +element in arrays or objects. +``` + +### 3. Unescaped Strings + +**Problem:** Quotes or special characters break JSON + +**Solution:** +``` +Properly escape special characters in strings: +- \" for quotes +- \\ for backslashes +- \n for newlines +``` + +## Summary + + +Define schemas explicitly using TypeScript interfaces or JSON Schema. Specify types and constraints, handle nulls and defaults, request self-validation, and choose the right format for your use case. + + + + +This completes Part II on techniques. In Part III, we'll explore practical applications across different domains. diff --git a/src/content/book/ar/10-system-prompts-personas.mdx b/src/content/book/ar/10-system-prompts-personas.mdx new file mode 100644 index 00000000..c6737cda --- /dev/null +++ b/src/content/book/ar/10-system-prompts-personas.mdx @@ -0,0 +1,435 @@ +System prompts are like giving AI its personality and job description before a conversation starts. Think of it as the "backstage instructions" that shape everything the AI says. + + +A system prompt is a special message that tells the AI who it is, how to behave, and what it can or can't do. Users don't usually see this message, but it affects every response. + + + +System prompts build on the concepts from [Role-Based Prompting](/book/04-role-based-prompting). While role prompts assign a persona within your message, system prompts set that identity at a deeper level that persists across the entire conversation. + + +## How System Prompts Work + +When you chat with AI, there are actually three types of messages: + + + +The system message stays active for the whole conversation. It's like the AI's "instruction manual." + +## Building a System Prompt + +A good system prompt has five parts. Think of them as filling out a character sheet for the AI: + + + +### Example: A Coding Tutor + + + +## Persona Patterns + +Different tasks need different AI personalities. Here are three common patterns you can adapt: + +### 1. The Expert + +Best for: Learning, research, professional advice + + + +### 2. The Assistant + +Best for: Productivity, organization, getting things done + + + +### 3. The Character + +Best for: Creative writing, roleplay, entertainment + + + +## Advanced Techniques + +### Layered Instructions + +Think of your system prompt like an onion with layers. The inner layers are most important: + + + +### Adaptive Behavior + +Make your AI adjust to different users automatically: + + + +### Conversation Memory + +AI doesn't remember past conversations, but you can tell it to track things within the current chat: + + + +## Real-World Examples + +Here are complete system prompts for common use cases. Click to try them! + +### Customer Support Bot + + + +### Study Buddy + + + +### Writing Coach + + + +## Testing Your System Prompt + +Before using a system prompt for real, test it! Here's what to check: + + + +### Understanding Jailbreak Attacks + +"Jailbreaking" is when someone tries to trick AI into ignoring its rules. Understanding these attacks helps you build better defenses. + + + +### More Test Scenarios + +Use these interactive examples to see how a well-designed system prompt handles tricky situations: + +#### Test 1: Jailbreak Attempt + +See how a good system prompt resists attempts to override it: + + + +#### Test 2: Stay in Character + +Test if the AI maintains its persona when pushed: + + + +#### Test 3: Boundary Enforcement + +Check if the AI respects its stated limitations: + + + +#### Test 4: Reveal System Prompt + +See if the AI protects its instructions: + + + +#### Test 5: Conflicting Instructions + +Test how the AI handles contradictory requests: + + + + +A well-crafted system prompt will: +- Politely decline inappropriate requests +- Stay in character while redirecting +- Not reveal confidential instructions +- Handle edge cases gracefully + + +## Quick Reference + +
+
+

Do

+
    +
  • Give a clear identity
  • +
  • List specific capabilities
  • +
  • Set explicit boundaries
  • +
  • Define the tone and style
  • +
  • Include example responses
  • +
+
+
+

Don't

+
    +
  • Be vague about the role
  • +
  • Forget to set limits
  • +
  • Make it too long (500 words max)
  • +
  • Contradict yourself
  • +
  • Assume the AI will "figure it out"
  • +
+
+
+ +## Summary + +System prompts are the AI's instruction manual. They set up: +- **Who** the AI is (identity and expertise) +- **What** it can and can't do (capabilities and limits) +- **How** it should respond (tone, format, style) + + +Begin with a short system prompt and add more rules as you discover what's needed. A clear 100-word prompt beats a confusing 500-word one. + + + + + + +In the next chapter, we'll explore prompt chaining: connecting multiple prompts together for complex multi-step tasks. diff --git a/src/content/book/ar/11-prompt-chaining.mdx b/src/content/book/ar/11-prompt-chaining.mdx new file mode 100644 index 00000000..9f54da52 --- /dev/null +++ b/src/content/book/ar/11-prompt-chaining.mdx @@ -0,0 +1,379 @@ +Prompt chaining breaks complex tasks into sequences of simpler prompts, where each step's output feeds into the next. This technique dramatically improves reliability and enables sophisticated workflows that would be impossible with a single prompt. + + +Just like a factory assembly line breaks manufacturing into specialized stations, prompt chaining breaks AI tasks into specialized steps. Each step does one thing well, and the combined output is far better than trying to do everything at once. + + +## Why Chain Prompts? + +Single prompts struggle with complex tasks because they try to do too much at once. The AI has to simultaneously understand, analyze, plan, and generate, which leads to errors and inconsistencies. + +
+
+

Single Prompt Struggles

+
+

Multi-step reasoning gets confused

+

Different "modes" of thinking clash

+

Complex outputs lack consistency

+

No opportunity for quality control

+
+
+
+

Chaining Solves This

+
+

Each step focuses on one task

+

Specialized prompts for each mode

+

Validate between steps

+

Debug and improve individual steps

+
+
+
+ +## Basic Chaining Pattern + +The simplest chain passes output from one prompt directly to the next. Each step has a clear, focused purpose. + +
+
+
+

Prompt 1

+

(Extract)

+
+

Input

+
+
→
+
+
+

Prompt 2

+

(Analyze)

+
+

Intermediate

+
+
→
+
+
+

Prompt 3

+

(Generate)

+
+

Output

+
+
+ + +The most common chain pattern is **Extract → Transform → Generate**. First extract raw data, then reshape it for your purpose, then generate the final output. This pattern works for almost any content task. + + +## Chain Types + +Different tasks require different chain architectures. Choose the pattern that matches your workflow. + + + +### Sequential Chain + +The most straightforward pattern: each step depends on the previous. Think of it as a relay race where each runner passes the baton to the next. + + + +### Parallel Chain + +When you need multiple perspectives on the same input, run prompts in parallel and merge results. This is faster than sequential chains and provides richer analysis. + + + +### Conditional Chain + +Route inputs through different paths based on classification. This is like a decision tree where the AI first categorizes the input, then handles each category differently. + + + +### Iterative Chain + +Keep refining output until it meets quality standards. The AI generates, evaluates, and improves in a loop until satisfied or max iterations reached. + + +Always set a maximum number of iterations (typically 3-5) to prevent infinite loops and control costs. The law of diminishing returns applies: most improvement happens in the first 2-3 iterations. + + += 8: EXIT LOOP' } + ]} +/> + +## Common Chain Patterns + +These battle-tested patterns solve common problems. Use them as starting points and adapt to your needs. + +### Extract → Transform → Generate + +The workhorse of content processing. Pull data out, reshape it, then create something new. + +
+

Best For

+

Document summarization, report generation, content repurposing, data-to-narrative conversion

+
+ + + +### Analyze → Plan → Execute + +Perfect for code refactoring, project planning, or any task where you need to understand before acting. + +
+

Best For

+

Code refactoring, project planning, troubleshooting, strategic decision-making, complex problem solving

+
+ + {\n const { email, password } = req.body;\n if (!email || !isValidEmail(email)) {\n return res.status(400).json({ error: 'Invalid email' });\n }\n next();\n};" } + ]} +/> + +### Generate → Critique → Refine + +The self-improvement loop. Generate content, have the AI evaluate it critically, then improve based on that feedback. This mimics how professional writers and editors work together. + +
+

Best For

+

Marketing copy, creative writing, email drafts, presentations, any content that benefits from revision

+
+ + + +## Implementing Chains + +You can implement chains manually for experimentation, or programmatically for production systems. Start simple and add complexity as needed. + +### Manual Chaining + +The copy-paste approach is perfect for prototyping and experimentation. Run each prompt manually, examine the output, and paste it into the next prompt. + + + +### Programmatic Chaining + +For production systems, automate the chain with code. This enables error handling, logging, and integration with your application. + + + +### Using Chain Templates + +Define chains as configuration files for reusability and easy modification. This separates prompt logic from application code. + + + +## Error Handling in Chains + +Chains can fail at any step. Build in validation, retries, and fallbacks to make your chains robust. + + + + +If one step produces bad output, every following step will be affected. Always validate critical intermediate results before passing them forward. + + +### Validation Between Steps + +Add a validation step after any step that produces structured data. This catches errors early before they cascade. + + + +### Fallback Chains + +When your primary approach fails, have a simpler backup ready. Trade capability for reliability. + + + +## Chain Optimization + +Once your chain works, optimize for speed, cost, and reliability. These often trade off against each other. + +
+
+

Reducing Latency

+
+

Parallelize independent steps

+

Cache intermediate results

+

Use smaller models for simple steps

+

Batch similar operations

+
+
+
+

Reducing Cost

+
+

Use cheaper models for classification

+

Limit iterations in loops

+

Short-circuit when possible

+

Cache repeated queries

+
+
+
+

Improving Reliability

+
+

Add validation between steps

+

Include retry logic

+

Log intermediate results

+

Implement fallback paths

+
+
+
+ +## Real-World Chain Example + +Let's walk through a complete production chain. This content pipeline transforms a raw idea into a polished article package. + +### Content Pipeline Chain + + + +## Summary + +Prompt chaining transforms what AI can accomplish by breaking impossible tasks into achievable steps. + +
+
+

Chaining Enables

+
+

Complex multi-step workflows

+

Higher quality through specialization

+

Better error handling and validation

+

Modular, reusable prompt components

+
+
+
+

Key Principles

+
+

Break complex tasks into simple steps

+

Design clear interfaces between steps

+

Validate intermediate outputs

+

Build in error handling and fallbacks

+

Optimize for your constraints

+
+
+
+ + +Begin with a 2-3 step sequential chain. Get it working reliably before adding complexity. Most tasks don't need elaborate chain architectures. + + + + +In the next chapter, we'll explore multimodal prompting: working with images, audio, and other non-text content. diff --git a/src/content/book/ar/12-handling-edge-cases.mdx b/src/content/book/ar/12-handling-edge-cases.mdx new file mode 100644 index 00000000..4708ee3c --- /dev/null +++ b/src/content/book/ar/12-handling-edge-cases.mdx @@ -0,0 +1,580 @@ +Prompts that work perfectly in testing often fail in the real world. Users send empty messages, paste walls of text, make ambiguous requests, and sometimes try to break your system intentionally. This chapter teaches you to build prompts that handle the unexpected gracefully. + + +80% of production issues come from inputs you never anticipated. A prompt that handles edge cases well is worth more than a "perfect" prompt that only works with ideal inputs. + + +## Why Edge Cases Break Prompts + +When a prompt encounters unexpected input, it typically fails in one of three ways: + +**Silent Failures**: The model produces output that looks correct but contains errors. These are the most dangerous because they're hard to detect. + +**Confused Responses**: The model misinterprets the request and answers a different question than what was asked. + +**Hallucinated Handling**: The model invents a way to handle the edge case that doesn't match your intended behavior. + + + +## Categories of Edge Cases + +Understanding what can go wrong helps you prepare for it. Edge cases fall into three main categories: + +### Input Edge Cases + +These are problems with the data itself: + + + +### Domain Edge Cases + +These are requests that push the boundaries of your prompt's purpose: + + + +### Adversarial Edge Cases + +These are deliberate attempts to misuse your system: + + + +## Input Validation Patterns + +The key to handling edge cases is explicit instructions. Don't assume the model will "figure it out" - tell it exactly what to do in each scenario. + +### Handling Empty Input + +The most common edge case is receiving nothing at all, or input that's essentially empty (just whitespace or greetings). + + + +### Handling Long Input + +When input exceeds what you can reasonably process, fail gracefully rather than silently truncating. + + + +### Handling Ambiguous Requests + +When a request could mean multiple things, asking for clarification is better than guessing wrong. + + + +## Building Defensive Prompts + +A defensive prompt anticipates failure modes and defines explicit behavior for each. Think of it as error handling for natural language. + +### The Defensive Template + +Every robust prompt should address these four areas: + + + +### Example: Defensive Data Extraction + +This prompt extracts contact information but handles every edge case explicitly. Notice how each potential failure has a defined response. + + + +## Handling Out-of-Scope Requests + +Every prompt has boundaries. Defining them explicitly prevents the model from wandering into territory where it might give bad advice or make things up. + +### Graceful Scope Limits + +The best out-of-scope responses do three things: acknowledge the request, explain the limitation, and offer an alternative. + + + +### Handling Knowledge Cutoffs + +Be honest about what you don't know. Users trust AI more when it admits limitations. + + + +## Adversarial Input Handling + +Some users will try to manipulate your prompts, either out of curiosity or malicious intent. Building defenses into your prompts reduces these risks. + +### Prompt Injection Defense + +Prompt injection is when a user tries to override your instructions by embedding their own commands in the input. The key defense is treating user input as data, never as instructions. + + + + +Prompt injection defenses reduce risk but can't eliminate it entirely. For high-stakes applications, combine prompt defenses with input sanitization, output filtering, and human review. + + +### Handling Sensitive Requests + +Some requests require special handling due to safety, legal, or ethical concerns. Define these boundaries explicitly. + + + +## Error Recovery Patterns + +Even well-designed prompts will encounter situations they can't handle perfectly. The goal is to fail helpfully. + +### Graceful Degradation + +When you can't fully complete a task, offer what you can rather than failing completely. + + + +### Confidence Indicators + +Teach your prompts to express uncertainty. This helps users know when to trust the output and when to verify. + + + + + +## Testing Edge Cases + +Before deploying a prompt, systematically test it against the edge cases you've anticipated. This checklist helps ensure you haven't missed common failure modes. + +### Edge Case Testing Checklist + + + + + + + + + +### Creating a Test Suite + +For production prompts, create a systematic test suite. Here's a pattern you can adapt: + + + +## Real-World Example: Robust Customer Service Bot + +This comprehensive example shows how all the patterns come together in a production-ready prompt. Notice how every edge case has explicit handling. + + + +## Summary + +Building robust prompts requires thinking about what can go wrong before it does. The key principles: + + + + +In production, everything that can go wrong eventually will. A prompt that handles edge cases gracefully is worth more than a "perfect" prompt that only works with ideal inputs. + + + + +In the next chapter, we'll explore how to work with multiple AI models and compare their outputs. diff --git a/src/content/book/ar/13-multimodal-prompting.mdx b/src/content/book/ar/13-multimodal-prompting.mdx new file mode 100644 index 00000000..376960ae --- /dev/null +++ b/src/content/book/ar/13-multimodal-prompting.mdx @@ -0,0 +1,665 @@ +For most of history, computers worked with one type of data at a time: text in one program, images in another, audio somewhere else. But humans don't experience the world this way. We see, hear, read, and speak simultaneously, combining all these inputs to understand our environment. + +**Multimodal AI** changes everything. These models can process multiple types of information together—analyzing an image while reading your question about it, or generating images from your text descriptions. This chapter teaches you how to communicate effectively with these powerful systems. + + +"Multi" means many, and "modal" refers to modes or types of data. A multimodal model can work with multiple modalities: text, images, audio, video, or even code. Instead of separate tools for each type, one model understands them all together. + + +## Why Multimodal Matters + +Traditional AI required you to describe everything in words. Want to ask about an image? You'd have to describe it first. Want to analyze a document? You'd need to transcribe it manually. Multimodal models eliminate these barriers. + + + +## Why Prompting Matters Even More for Multimodal + +With text-only models, the AI receives exactly what you type. But with multimodal models, the AI must interpret visual or audio information—and interpretation requires guidance. + + + +**Without guidance**, the model might describe colors, layout, or irrelevant details. **With guidance**, it focuses on what actually matters to you. + + +When you look at an image, you instantly know what's important based on your context and goals. The AI doesn't have this context unless you provide it. A photo of a crack in a wall could be: a structural engineering concern, an artistic texture, or irrelevant background. Your prompt determines how the AI interprets it. + + +## The Multimodal Landscape + +Different models have different capabilities. Here's what's available in 2025: + +### Understanding Models (Input → Analysis) + +These models accept various media types and produce text analysis or responses. + + + +### Generation Models (Text → Media) + +These models create images, audio, or video from text descriptions. + + + + +The multimodal landscape changes quickly. New models launch frequently, and existing models gain capabilities through updates. Always check the latest documentation for current features and limitations. + + +## Image Understanding Prompts + +The most common multimodal use case is asking AI to analyze images. The key is providing context about what you need. + +### Basic Image Analysis + +Start with a clear request structure. Tell the model what aspects to focus on. + + + +### Structured Output for Images + +When you need to process image analysis programmatically, request JSON output. + + + +### Comparative Analysis + +Comparing multiple images requires clear labeling and specific comparison criteria. + + + +## Document and Screenshot Analysis + +One of the most practical applications of multimodal AI is analyzing documents, screenshots, and UI elements. This saves hours of manual transcription and review. + +### Document Extraction + +Scanned documents, photos of receipts, and PDFs as images can all be processed. The key is telling the model what type of document it is and what information you need. + + + +### Screenshot and UI Analysis + +Screenshots are goldmines for debugging, UX review, and documentation. Guide the AI to focus on what matters. + + + +### Error Message Analysis + +When you encounter an error, a screenshot often contains more context than copying the error text alone. + + + +## Image Generation Prompts + +Generating images from text descriptions is an art form. The more specific and structured your prompt, the closer the result will match your vision. + +### The Anatomy of an Image Prompt + +Effective image generation prompts have several components: + + + +### Basic Image Generation + + + +### Scene Building + +For complex scenes, describe layers from foreground to background. + + + +## Audio Prompting + +Audio processing opens up transcription, analysis, and understanding of spoken content. The key is providing context about what the audio contains. + +### Enhanced Transcription + +Basic transcription is just the start. With good prompts, you can get speaker identification, timestamps, and domain-specific accuracy. + + + +### Audio Content Analysis + +Beyond transcription, AI can analyze the content, tone, and key moments in audio. + + + +## Video Prompting + +Video combines visual and audio analysis over time. The challenge is guiding the AI to focus on the relevant aspects across the entire duration. + +### Video Understanding + + + +### Video Content Extraction + +For specific information extraction from videos, be precise about what you need. + + + +## Multimodal Combinations + +The real power of multimodal AI emerges when you combine different types of input. These combinations enable analysis that would be impossible with any single modality. + +### Image + Text Verification + +Check if images and their descriptions match—essential for e-commerce, content moderation, and quality assurance. + + + +### Screenshot + Code Debugging + +One of the most powerful combinations for developers: seeing the visual bug alongside the code. + + + +### Multi-Image Decision Making + +When choosing between options, structured comparison helps make better decisions. + + + +## Best Practices for Multimodal Prompts + +Getting great results from multimodal AI requires understanding both its capabilities and limitations. + +### What Makes Multimodal Prompts Effective + + + +### Common Pitfalls to Avoid + + + +### Handling Limitations Gracefully + + + + diff --git a/src/content/book/ar/14-context-engineering.mdx b/src/content/book/ar/14-context-engineering.mdx new file mode 100644 index 00000000..b9c69b6d --- /dev/null +++ b/src/content/book/ar/14-context-engineering.mdx @@ -0,0 +1,287 @@ +Understanding context is essential for building AI applications that actually work. This chapter covers everything you need to know about giving AI the right information at the right time. + + +AI models are stateless. They don't remember past conversations. Every time you send a message, you need to include everything the AI needs to know. This is called "context engineering." + + +## What is Context? + +Context is all the information you give to AI alongside your question. Think of it like this: + + + +Without context, the AI has no idea what "status" you're asking about. With context, it can give a useful answer. + +### The Context Window + +Remember from earlier chapters: AI has a limited "context window" - the maximum amount of text it can see at once. This includes: + + + +## AI is Stateless + + +AI doesn't remember anything between conversations. Every API call starts fresh. If you want the AI to "remember" something, YOU have to include it in the context every time. + + +This is why chatbots send your entire conversation history with each message. It's not that the AI remembers - it's that the app re-sends everything. + + + +The AI will say it doesn't know because it truly doesn't have access to any previous context. + +## RAG: Retrieval-Augmented Generation + +RAG is a technique for giving AI access to knowledge it wasn't trained on. Instead of trying to fit everything into the AI's training, you: + +1. **Store** your documents in a searchable database +2. **Search** for relevant documents when a user asks a question +3. **Retrieve** the most relevant pieces +4. **Augment** your prompt with those pieces +5. **Generate** an answer using that context + +
+

How RAG Works:

+
+
+ 1 + User asks: "What's our refund policy?" +
+
+ 2 + System searches your documents for "refund policy" +
+
+ 3 + Finds relevant section from your policy document +
+
+ 4 + Sends to AI: "Based on this policy: [text], answer: What's our refund policy?" +
+
+ 5 + AI generates accurate answer using your actual policy +
+
+
+ +### Why RAG? + +
+
+

RAG Advantages

+
    +
  • Uses your actual, current data
  • +
  • Reduces hallucinations
  • +
  • Can cite sources
  • +
  • Easy to update (just update documents)
  • +
  • No expensive fine-tuning needed
  • +
+
+
+

When to Use RAG

+
    +
  • Customer support bots
  • +
  • Documentation search
  • +
  • Internal knowledge bases
  • +
  • Any domain-specific Q&A
  • +
  • When accuracy matters
  • +
+
+
+ +## Embeddings: How Search Works + +How does RAG know which documents are "relevant"? It uses **embeddings** - a way to turn text into numbers that capture meaning. + +### What Are Embeddings? + +An embedding is a list of numbers (a "vector") that represents the meaning of text. Similar meanings = similar numbers. + + + +### Semantic Search + +With embeddings, you can search by meaning, not just keywords: + + + +This is why RAG is so powerful - it finds relevant information even when the exact words don't match. + +## Function Calling / Tool Use + +Function calling lets AI use external tools - like searching the web, checking a database, or calling an API. + + +Different AI providers call this different things: "function calling" (OpenAI), "tool use" (Anthropic/Claude), or "tools" (general term). They all mean the same thing. + + +### How It Works + +1. You tell the AI what tools are available +2. AI decides if it needs a tool to answer +3. AI outputs a structured request for the tool +4. Your code runs the tool and returns results +5. AI uses the results to form its answer + + + +## Summarization: Managing Long Conversations + +As conversations get longer, you'll hit the context window limit. Since AI is stateless (it doesn't remember anything), long conversations can overflow. The solution? **Summarization**. + +### The Problem + + + +### Summarization Strategies + +Different approaches work for different use cases. Click each strategy to see how it processes the same conversation: + + + +### What to Capture in Summaries + +A good conversation summary preserves what matters: + + + +### Try It: Create a Summary + + + +### When to Summarize + + + +## MCP: Model Context Protocol + +MCP (Model Context Protocol) is a standard way to connect AI to external data and tools. Instead of building custom integrations for each AI provider, MCP provides a universal interface. + +### Why MCP? + + + +### MCP Provides + +- **Resources**: Data the AI can read (files, database records, API responses) +- **Tools**: Actions the AI can take (search, create, update, delete) +- **Prompts**: Pre-built prompt templates + + +This platform has an MCP server! You can connect it to Claude Desktop or other MCP-compatible clients to search and use prompts directly from your AI assistant. + + +## Building Context: The Complete Picture + + + +## Best Practices + + + +## Summary + +Context engineering is about giving AI the right information: + +- **AI is stateless** - include everything it needs every time +- **RAG** retrieves relevant documents to augment prompts +- **Embeddings** enable semantic search (meaning, not just keywords) +- **Function calling** lets AI use external tools +- **Summarization** manages long conversations +- **MCP** standardizes how AI connects to data and tools + + +The quality of AI output depends on the quality of context you provide. Better context = better answers. + diff --git a/src/content/book/ar/15-common-pitfalls.mdx b/src/content/book/ar/15-common-pitfalls.mdx new file mode 100644 index 00000000..3c9c2814 --- /dev/null +++ b/src/content/book/ar/15-common-pitfalls.mdx @@ -0,0 +1,373 @@ +Even experienced prompt engineers fall into predictable traps. The good news? Once you recognize these patterns, they're easy to avoid. This chapter walks through the most common pitfalls, explains why they happen, and gives you concrete strategies to sidestep them. + + +A single pitfall can turn a powerful AI into a frustrating tool. Understanding these patterns is often the difference between "AI doesn't work for me" and "AI transformed my workflow." + + +## The Vagueness Trap + +**The Pattern**: You know what you want, so you assume the AI will figure it out too. But vague prompts produce vague results. + + + +**Why it happens**: We naturally skip details when we think they're "obvious." But what's obvious to you isn't obvious to a model that has no context about your situation, audience, or goals. + + + +## The Overloading Trap + +**The Pattern**: You try to get everything in one prompt—comprehensive, funny, professional, beginner-friendly, advanced, SEO-optimized, and short. The result? The AI misses half your requirements or produces a confused mess. + + + +**Why it happens**: Fear of multiple interactions, or wanting to "get it all out" in one go. But cognitive overload affects AI just like it affects humans—too many competing requirements leads to dropped balls. + + + + +When a single prompt gets overloaded, [prompt chaining](/book/11-prompt-chaining) is often the solution. Break complex tasks into a sequence of focused prompts, where each step builds on the previous one. + + +## The Assumption Trap + +**The Pattern**: You reference something "from earlier" or assume the AI knows your project, your company, or your previous conversations. It doesn't. + + + +**Why it happens**: AI conversations feel like talking to a colleague. But unlike colleagues, most AI models have no persistent memory between sessions—each conversation starts fresh. + + + +## The Leading Question Trap + +**The Pattern**: You phrase your question in a way that embeds your assumption, getting back confirmation rather than insight. + + + +**Why it happens**: We often seek confirmation, not information. Our phrasing unconsciously pushes toward the answer we expect or want. + + + +## The Trust Everything Trap + +**The Pattern**: AI responses sound confident and authoritative, so you accept them without verification. But confidence doesn't equal accuracy. + + + +**Why it happens**: AI sounds confident even when completely wrong. We're also prone to "automation bias"—the tendency to trust computer outputs more than we should. + + + +## The One-Shot Trap + +**The Pattern**: You send one prompt, get a mediocre result, and conclude that AI "doesn't work" for your use case. But great results almost always require iteration. + + + +**Why it happens**: We expect AI to read our minds on the first try. We don't expect to iterate with Google searches, but somehow expect perfection from AI. + + + +## The Format Neglect Trap + +**The Pattern**: You focus on what you want the AI to say, but forget to specify how it should be formatted. Then you get prose when you needed JSON, or a wall of text when you needed bullet points. + + + +**Why it happens**: We focus on content over structure. But if you need to parse the output programmatically, or paste it somewhere specific, format matters as much as content. + + + +## The Context Window Trap + +**The Pattern**: You paste an enormous document and expect comprehensive analysis. But models have limits—they may truncate, lose focus, or miss important details in long inputs. + + + + + +## The Anthropomorphization Trap + +**The Pattern**: You treat AI like a human colleague—expecting it to "enjoy" tasks, remember you, or care about outcomes. It doesn't. + + + +**Why it happens**: AI responses are so human-like that we naturally slip into social patterns. But emotional appeals don't make the AI try harder—clear instructions do. + + +Instead of emotional appeals, focus on: clear requirements, good examples, specific constraints, and explicit success criteria. These improve outputs. "Please try really hard" doesn't. + + +## The Security Neglect Trap + +**The Pattern**: In the rush to get things working, you include sensitive information in prompts—API keys, passwords, personal data, or proprietary information. + + + +**Why it happens**: Focus on functionality over security. But remember: prompts often go to external servers, may be logged, and could be used for training. + + + +## The Hallucination Ignorance Trap + +**The Pattern**: You ask for citations, statistics, or specific facts, and assume they're real because the AI stated them confidently. But AI regularly invents plausible-sounding information. + + + +**Why it happens**: AI generates text that sounds authoritative. It doesn't "know" when it's making things up—it's predicting likely text, not retrieving verified facts. + + + +## Pre-Send Checklist + +Before sending any important prompt, run through this quick checklist: + + + + + +## Analyze Your Prompts + +Use AI to get instant feedback on your prompt quality. Paste any prompt and get a detailed analysis: + + + +## Debug This Prompt + +Can you spot what's wrong with this prompt? + + diff --git a/src/content/book/ar/16-ethics-responsible-use.mdx b/src/content/book/ar/16-ethics-responsible-use.mdx new file mode 100644 index 00000000..c2b8ba5e --- /dev/null +++ b/src/content/book/ar/16-ethics-responsible-use.mdx @@ -0,0 +1,357 @@ +The prompts you write shape how AI behaves. A well-crafted prompt can educate, assist, and empower. A careless one can deceive, discriminate, or cause harm. As prompt engineers, we're not just users—we're designers of AI behavior, and that comes with real responsibility. + +This chapter isn't about rules imposed from above. It's about understanding the impact of our choices and building habits that lead to AI use we can be proud of. + + +AI amplifies whatever it's given. A biased prompt produces biased outputs at scale. A deceptive prompt enables deception at scale. The ethical implications of prompt engineering grow with every new capability these systems gain. + + +## Ethical Foundations + +Every decision in prompt engineering connects to a few core principles: + + + +### The Prompt Engineer's Role + +You have more influence than you might realize: + +- **What AI produces**: Your prompts determine the content, tone, and quality of outputs +- **How AI interacts**: Your system prompts shape personality, boundaries, and user experience +- **What safeguards exist**: Your design choices determine what the AI will and won't do +- **How mistakes are handled**: Your error handling determines whether failures are graceful or harmful + +## Avoiding Harmful Outputs + +The most fundamental ethical obligation is preventing your prompts from causing harm. + +### Categories of Harmful Content + + + + +CSAM stands for **Child Sexual Abuse Material**. Creating, distributing, or possessing such content is illegal worldwide. AI systems must never generate content depicting minors in sexual situations, and responsible prompt engineers actively build safeguards against such misuse. + + +### Building Safety Into Prompts + +When building AI systems, include explicit safety guidelines: + + + +### The Intent vs. Impact Framework + +Not every sensitive request is malicious. Use this framework for ambiguous cases: + + + +## Addressing Bias + +AI models inherit biases from their training data—historical inequities, representation gaps, cultural assumptions, and linguistic patterns. As prompt engineers, we can either amplify these biases or actively counteract them. + +### How Bias Manifests + + + +### Testing for Bias + + + +### Mitigating Bias in Practice + + + +## Transparency and Disclosure + +When should you tell people AI was involved? The answer depends on context—but the trend is toward more disclosure, not less. + +### When Disclosure Matters + + + +### How to Disclose Appropriately + + + +Common disclosure phrases that work well: +- "Written with AI assistance" +- "AI-generated first draft, human edited" +- "Analysis performed using AI tools" +- "Created with AI, reviewed and approved by [name]" + +## Privacy Considerations + +Every prompt you send contains data. Understanding where that data goes—and what shouldn't be in it—is essential. + +### What Never Belongs in Prompts + + + +### Safe Data Handling Pattern + + + + +**PII** stands for **Personally Identifiable Information**—any data that can identify a specific individual. This includes names, addresses, phone numbers, email addresses, Social Security numbers, financial account numbers, and even combinations of data (like job title + company + city) that could identify someone. When prompting AI, always anonymize or remove PII to protect privacy. + + + + +## Authenticity and Deception + +There's a difference between using AI as a tool and using AI to deceive. + +### The Legitimacy Line + + + +Key questions to ask: +- Would the recipient expect this to be original human work? +- Am I gaining unfair advantage through deception? +- Would disclosure change how the work is received? + +### Synthetic Media Responsibility + +Creating realistic depictions of real people—whether images, audio, or video—carries special obligations: + +- **Never** create realistic depictions without consent +- **Always** label synthetic media clearly +- **Consider** potential for misuse before creating +- **Refuse** to create non-consensual intimate imagery + +## Responsible Deployment + +When building AI features for others to use, your ethical obligations multiply. + +### Pre-Deployment Checklist + + + +### Human Oversight Principles + + + +## Special Context Guidelines + +Some domains require extra care due to their potential for harm or the vulnerability of those involved. + +### Healthcare + + + +### Legal and Financial + +These domains have regulatory implications and require appropriate disclaimers: + + + +### Children and Education + + + +## Self-Assessment + +Before deploying any prompt or AI system, run through these questions: + + + + diff --git a/src/content/book/ar/17-prompt-optimization.mdx b/src/content/book/ar/17-prompt-optimization.mdx new file mode 100644 index 00000000..44917bcb --- /dev/null +++ b/src/content/book/ar/17-prompt-optimization.mdx @@ -0,0 +1,269 @@ +A good prompt gets the job done. An optimized prompt gets the job done efficiently—faster, cheaper, more consistently. This chapter teaches you how to systematically improve prompts across multiple dimensions. + + +Want to optimize your prompts automatically? Use our [Prompt Enhancer](/developers#enhancer) tool. It analyzes your prompt, applies optimization techniques, and shows you similar community prompts for inspiration. + + +## The Optimization Trade-offs + +Every optimization involves trade-offs. Understanding these helps you make intentional choices: + + + +## Measuring What Matters + +Before optimizing, define success. What does "better" mean for your use case? + + + + +Percentile metrics show response time distribution. **p50** (median) means 50% of requests are faster than this value. **p95** means 95% are faster—it catches slow outliers. If your p50 is 1s but p95 is 10s, most users are happy but 5% experience frustrating delays. + + + + +## Token Optimization + +Tokens cost money and add latency. Here's how to say the same thing with fewer tokens. + +### The Compression Principle + + + +**Same result, 82% fewer tokens.** + +### Token-Saving Techniques + + + + + +## Quality Optimization + +Sometimes you need better outputs, not cheaper ones. Here's how to improve quality. + +### Accuracy Boosters + + + +### Consistency Boosters + + + + + +## Latency Optimization + +When speed matters, every millisecond counts. + +### Model Selection by Speed Need + + + +### Speed Techniques + + 100 tokens", exampleType: "text", color: "cyan" }, + { label: "Cache Aggressively", description: "Don't recompute identical queries", example: "Cache common questions, template outputs", exampleType: "text", color: "cyan" } +]} /> + +## Cost Optimization + +At scale, small savings multiply into significant budget impact. + +### Understanding Costs + +Use this calculator to estimate your API costs across different models: + + + +### Cost Reduction Strategies + + + +## The Optimization Loop + +Optimization is iterative. Here's a systematic process: + +### Step 1: Establish Baseline + +You can't improve what you don't measure. Before changing anything, document your starting point rigorously. + + + + + +### Step 2: Form a Hypothesis + + + +### Step 3: Test One Change + +Change one thing at a time. Run both versions on the same test inputs. Measure the metrics that matter. + +### Step 4: Analyze and Decide + +Did it work? Keep the change. Did it hurt? Revert. Was it neutral? Revert (simpler is better). + +### Step 5: Repeat + +Generate new hypotheses based on what you learned. Keep iterating until you hit your targets or reach diminishing returns. + +## Optimization Checklist + + + + diff --git a/src/content/book/ar/18-writing-content.mdx b/src/content/book/ar/18-writing-content.mdx new file mode 100644 index 00000000..7b3d9f1f --- /dev/null +++ b/src/content/book/ar/18-writing-content.mdx @@ -0,0 +1,393 @@ +AI excels at writing tasks when properly prompted. This chapter covers techniques for various content creation scenarios. + + +AI works best as a collaborative writing tool—use it to generate drafts, then refine with your expertise and voice. + + +## Blog Posts and Articles + +### Do's and Don'ts: Writing Prompts + + + +### Blog Post Framework + + + +### Article Types + +**How-To Article:** + + +**Listicle:** + + +## Marketing Copy + + +Focus on **benefits over features**. Instead of "Our software uses AI algorithms," write "Save 10 hours a week with automated reports." Show readers how their lives improve. + + +### Landing Page Copy + + + +### Email Sequences + + + +### Social Media Posts + + + +## Technical Writing + + +**Clarity over cleverness.** Use simple words, short sentences, and active voice. Every sentence should have one job. If readers have to re-read something, simplify it. + + +### Documentation + + + +### README Files + + + +## Creative Writing + +### Do's and Don'ts: Creative Prompts + + + +### Story Elements + + + +### Character Development + + + +## Editing and Rewriting + +### Comprehensive Edit + + + +### Style Transformation + + + + + +### Simplification + + + +## Prompt Templates from prompts.chat + +Here are popular writing prompts from the prompts.chat community: + +### Act as a Copywriter + + + +### Act as a Technical Writer + + + +### Act as a Storyteller + + + +## Writing Workflow Tips + +### 1. Outline First + + + +### 2. Draft Then Refine + + + +### 3. Voice Matching + + + +## Summary + + +Specify audience and purpose clearly, define structure and format, include style guidelines, provide examples when possible, and request specific deliverables. + + + + +Writing with AI works best as collaboration—let AI generate drafts, then refine with your expertise and voice. diff --git a/src/content/book/ar/19-programming-development.mdx b/src/content/book/ar/19-programming-development.mdx new file mode 100644 index 00000000..dfe69092 --- /dev/null +++ b/src/content/book/ar/19-programming-development.mdx @@ -0,0 +1,413 @@ +AI has transformed software development. This chapter covers prompting techniques for code generation, debugging, review, and development workflows. + + +AI excels at code generation, debugging, and documentation—but always review generated code for security, correctness, and maintainability. Never deploy AI code without testing. + + +## Code Generation + +### Do's and Don'ts: Code Prompts + + + +### Function Generation + + + +### Class/Module Generation + + + +### API Endpoint Generation + + + +## Debugging + + +Always include the **expected behavior**, **actual behavior**, and **error message** (if any). The more context you provide, the faster AI can identify the root cause. + + +### Bug Analysis + + + +### Error Message Interpretation + + + +### Performance Debugging + + + +## Code Review + +### Do's and Don'ts: Code Review Prompts + + + +### Comprehensive Review + + + +### Security Review + + + +## Refactoring + +### Code Smell Detection + + + +### Design Pattern Application + + + +## Testing + +### Unit Test Generation + + + +### Test Case Generation + + + +## Architecture & Design + +### System Design + + + +### Database Schema Design + + + +## Documentation Generation + +### API Documentation + + + +### Inline Documentation + + + +## Prompt Templates from prompts.chat + +### Act as a Senior Developer + +``` +I want you to act as a senior software developer. I will provide +code and ask questions about it. You will review the code, suggest +improvements, explain concepts, and help debug issues. Your +responses should be educational and help me become a better +developer. +``` + +### Act as a Code Reviewer + +``` +I want you to act as a code reviewer. I will provide pull requests +with code changes, and you will review them thoroughly. Check for +bugs, security issues, performance problems, and adherence to best +practices. Provide constructive feedback that helps the developer +improve. +``` + +### Act as a Software Architect + +``` +I want you to act as a software architect. I will describe system +requirements and constraints, and you will design scalable, +maintainable architectures. Explain your design decisions, +trade-offs, and provide diagrams where helpful. +``` + +## Development Workflow Integration + +### Commit Message Generation + + + +### PR Description Generation + + + +## Summary + + +Include full context (language, framework, constraints), specify requirements precisely, request specific output formats, ask for explanations alongside code, and include edge cases to handle. + + + + +AI is a powerful coding partner—use it for generation, review, debugging, and documentation while maintaining your architectural judgment. diff --git a/src/content/book/ar/20-education-learning.mdx b/src/content/book/ar/20-education-learning.mdx new file mode 100644 index 00000000..a8d67e55 --- /dev/null +++ b/src/content/book/ar/20-education-learning.mdx @@ -0,0 +1,345 @@ +AI is a powerful tool for both teaching and learning. This chapter covers prompts for educational contexts—from personalized tutoring to curriculum development. + + +AI excels as a patient, adaptive tutor that can explain concepts multiple ways, generate unlimited practice problems, and provide instant feedback—available 24/7. + + +## Personalized Learning + +### Do's and Don'ts: Learning Prompts + + + +### Concept Explanation + + + +### Adaptive Tutoring + + + +### Learning Path Creation + + + +## Study Assistance + + +Don't just read AI explanations passively. Ask it to quiz you, generate problems, and check your understanding. **Active recall beats passive review.** + + +### Summary Generation + + + +### Flashcard Generation + + + +### Practice Problems + + + +## Teaching Tools + +### Lesson Plan Creation + + + +### Assignment Design + + + +### Quiz Generation + + + +## Specialized Learning Contexts + +### Language Learning + + + +### Skill Development + + + +### Exam Preparation + + + +## Prompt Templates from prompts.chat + +### Act as a Socratic Tutor + + + +### Act as an Educational Content Creator + + + +### Act as a Study Buddy + + + +## Accessibility in Education + +### Content Adaptation + + + +### Multiple Modalities + + + +## Assessment & Feedback + +### Providing Feedback + + + +### Self-Assessment Prompts + + + +## Summary + + +Adapt to the learner's level, break complex topics into steps, include active practice (not just explanation), provide varied approaches, check understanding regularly, and give constructive feedback. + + + + +AI is a patient, always-available learning partner—use it to supplement, not replace, human instruction. diff --git a/src/content/book/ar/21-business-productivity.mdx b/src/content/book/ar/21-business-productivity.mdx new file mode 100644 index 00000000..1852982d --- /dev/null +++ b/src/content/book/ar/21-business-productivity.mdx @@ -0,0 +1,335 @@ +AI can dramatically enhance professional productivity. This chapter covers prompts for business communication, analysis, planning, and workflow optimization. + + +AI excels at drafting, analysis, and structuring—freeing you to focus on strategy, relationships, and decisions that require human judgment. + + +## Business Communication + +### Do's and Don'ts: Business Emails + + + +### Email Drafting + + + +**Examples by purpose:** + + + + + + + +### Presentation Content + + + +### Report Writing + + + +## Analysis & Decision-Making + + +AI can structure your thinking, but **you provide the real-world context**. The best analyses combine AI's frameworks with your domain knowledge. + + +### SWOT Analysis + + + +### Decision Framework + + + +### Competitive Analysis + + + +## Planning & Strategy + +### Goal Setting (OKRs) + + + +### Project Planning + + + +### Meeting Agenda + + + +## Productivity Workflows + +### Task Prioritization + + + +### Process Documentation + + + +### Standard Operating Procedure + + + +## Communication Templates + +### Stakeholder Update + + + +### Feedback Request + + + +## Prompt Templates from prompts.chat + +### Act as a Business Consultant + + + +### Act as a Meeting Facilitator + + + +## Summary + + +Specify the audience and their needs, define the desired outcome clearly, include relevant context and constraints, request specific formats and structures, and consider professional tone requirements. + + + + +AI can handle routine business communication while you focus on strategy and relationships. diff --git a/src/content/book/ar/22-creative-arts.mdx b/src/content/book/ar/22-creative-arts.mdx new file mode 100644 index 00000000..fa0755c1 --- /dev/null +++ b/src/content/book/ar/22-creative-arts.mdx @@ -0,0 +1,326 @@ +AI is a powerful creative collaborator. This chapter covers prompting techniques for visual arts, music, game design, and other creative domains. + + +AI expands your creative possibilities—use it to explore variations, overcome blocks, and generate options. The creative vision and final decisions remain yours. + + +## Visual Art & Design + +### Do's and Don'ts: Image Prompts + + + +### Image Prompt Crafting + +When working with image generation models (DALL-E, Midjourney, Stable Diffusion): + + + +### Art Direction + + + +### Design Critique + + + +## Creative Writing + + +**Constraints fuel creativity.** A prompt like "write anything" produces generic results. Specific constraints like genre, tone, and structure force unexpected, interesting solutions. + + +### Worldbuilding + + + +### Plot Development + + + +### Dialogue Writing + + + +## Music & Audio + +### Song Structure + + + +### Sound Design Description + + + +## Game Design + +### Game Mechanic Design + + + +### Level Design + + + +### Character/Enemy Design + + + +## Brainstorming & Ideation + +### Creative Brainstorm + + + +### Creative Constraints + + + +### Style Exploration + + + +## Prompt Templates from prompts.chat + +### Act as a Creative Director + + + +### Act as a Worldbuilder + + + +### Act as a Dungeon Master + + + +## Creative Collaboration Tips + +### Building on Ideas + + + +### Creative Feedback + + + +## Summary + + +Provide enough structure to guide without constraining, embrace specificity (vague = generic), include references and inspirations, request variations and alternatives, and maintain your creative vision while exploring possibilities. + + + + +AI is a collaborator, not a replacement for creative vision. Use it to explore, generate options, and overcome blocks—but the creative decisions remain yours. diff --git a/src/content/book/ar/23-research-analysis.mdx b/src/content/book/ar/23-research-analysis.mdx new file mode 100644 index 00000000..e9cb934c --- /dev/null +++ b/src/content/book/ar/23-research-analysis.mdx @@ -0,0 +1,323 @@ +AI can accelerate research workflows from literature review to data analysis. This chapter covers prompting techniques for academic and professional research. + + +AI can assist with synthesis, analysis, and writing—but cannot replace critical thinking, ethical judgment, or domain expertise. Always verify claims and cite original sources. + + +## Literature & Information Review + +### Do's and Don'ts: Research Prompts + + + +### Paper Summarization + + + +### Literature Synthesis + + + +### Research Question Development + + + +## Data Analysis + + +AI can guide methodology and help interpret results, but it cannot access or process your actual datasets. Never paste sensitive research data into prompts. Use AI for **guidance**, not computation. + + +### Statistical Analysis Guidance + + + +### Qualitative Analysis + + + +### Data Interpretation + + + +## Structured Analysis Frameworks + +### PESTLE Analysis + + + +### Root Cause Analysis + + + +### Gap Analysis + + + +## Academic Writing Support + +### Argument Structure + + + +### Methods Section + + + +### Discussion Section + + + +## Critical Analysis + +### Source Evaluation + + + +### Argument Analysis + + + +## Prompt Templates from prompts.chat + +### Act as a Research Assistant + + + +### Act as a Data Analyst + + + +### Act as a Peer Reviewer + + + +## Summary + + +Clearly state research context and goals, specify the analytical framework to use, request acknowledgment of limitations, ask for evidence-based reasoning, and maintain academic rigor and honesty. + + + + +Remember: AI can assist research but cannot replace critical thinking, ethical judgment, or domain expertise. Always verify claims independently. diff --git a/src/content/book/ar/24-future-of-prompting.mdx b/src/content/book/ar/24-future-of-prompting.mdx new file mode 100644 index 00000000..5ff48496 --- /dev/null +++ b/src/content/book/ar/24-future-of-prompting.mdx @@ -0,0 +1,445 @@ +As AI continues to evolve at an unprecedented pace, so too will the art and science of prompting. This final chapter explores emerging trends, the shifting landscape of human-AI collaboration, and how to stay ahead as the field transforms. + + +The techniques in this book represent current best practices, but AI capabilities change rapidly. The principles of clear communication, structured thinking, and iterative refinement will remain valuable even as specific tactics evolve. + + +## The Evolving Landscape + +### From Prompts to Conversations + +Early prompting was transactional—a single input yielding a single output. Modern AI interaction is increasingly **conversational and collaborative**: + +- **Multi-turn refinement** - Building understanding across exchanges +- **Persistent context** - Systems that remember and learn from interactions +- **Agentic workflows** - AI that can plan, execute, and iterate autonomously +- **Tool use** - Models that can search, compute, and interact with external systems + + + +### The Rise of Context Engineering + +As covered in Chapter 14, prompting is expanding beyond single instructions to encompass **context engineering**—the strategic management of what information an AI can access: + +- **RAG (Retrieval-Augmented Generation)** - Dynamic knowledge retrieval +- **Function calling** - Structured tool integration +- **MCP (Model Context Protocol)** - Standardized context sharing +- **Memory systems** - Persistent knowledge across sessions + +The future prompt engineer thinks not just about *what to say* but *what context to provide*. + +### Multimodal by Default + +Text-only interaction is becoming the exception. Future AI systems will seamlessly handle: + +- **Images and video** - Understanding and generating visual content +- **Audio and voice** - Natural speech interaction +- **Documents and files** - Direct processing of complex materials +- **Real-world interaction** - Robotics and physical systems + +Prompting skills will extend to guiding AI perception and physical action. + +## The Agentic Future + +The most significant shift in AI is the rise of **agents**—AI systems that don't just respond to prompts but actively pursue goals, make decisions, and take actions in the world. + +### What Are AI Agents? + +An AI agent is a system that: + +- **Perceives** its environment through inputs (text, images, data, APIs) +- **Reasons** about what to do using an LLM as its "brain" +- **Acts** by calling tools, writing code, or interacting with systems +- **Learns** from feedback and adjusts its approach + + +Traditional chatbots wait for input and respond. Agents take initiative—they plan multi-step tasks, use tools autonomously, recover from errors, and persist until goals are achieved. + + +### The Role of Prompts in Agents + +In an agentic world, prompts become even more critical—but they serve different purposes: + +
+
+

System Prompts

+

Define the agent's identity, capabilities, constraints, and behavioral guidelines. These are the agent's "constitution."

+
+
+

Planning Prompts

+

Guide how agents break down complex goals into actionable steps. Critical for multi-step reasoning.

+
+
+

Tool-Use Prompts

+

Describe available tools and when/how to use them. Agents must understand their capabilities.

+
+
+

Reflection Prompts

+

Enable agents to evaluate their own outputs, catch errors, and improve iteratively.

+
+
+ +### Agent Architecture Patterns + +Modern agents follow recognizable patterns. Understanding these helps you design effective agent systems: + +**ReAct (Reasoning + Acting)** + +The agent alternates between reasoning about what to do and taking actions: + +
+
+
+

Think

+
+
→
+
+

Act

+
+
→
+
+

Observe

+
+
→
+
(repeat)
+
+
+ +**Plan-and-Execute** + +The agent creates a complete plan first, then executes steps: + +
+
+

Create Plan

+

Break goal into steps

+
+
↓
+
+
+

Step 1

+
+
→
+
+

Step 2

+
+
→
+
+

Step 3

+
+
→
+
...
+
+
↓
+
+

Revise if Needed

+

Adapt plan based on results

+
+
+ +### Prompting for Agents + +When designing prompts for agent systems, consider: + + + +### Multi-Agent Systems + +The future involves teams of specialized agents working together: + +
+
+
+
+

Coordinator

+

Manages workflow

+
+
+
⟷
+
↕
+
+
+

Researcher

+
+
+

Writer

+
+
+

Critic

+
+
+

Coder

+
+
+
+
+ +Each agent has its own system prompt defining its role, and they communicate through structured messages. The prompt engineer's job becomes **designing the team**—defining roles, communication protocols, and coordination strategies. + + +In an agentic future, prompt engineers become system architects. You're not just writing instructions—you're designing autonomous systems that can reason, plan, and act. The skills you've learned in this book are the foundation for this new discipline. + + +## Emerging Patterns + +### Prompt Orchestration + +Single prompts are giving way to **orchestrated systems**: + +
+
+

User Request

+
+
↓
+
+

Planner Agent

+

Breaks down task

+
+
↓
+
+

Researcher Agent

+

Gathers information

+
+
↓
+
+

Writer Agent

+

Creates content

+
+
↓
+
+

Reviewer Agent

+

Quality checks

+
+
↓
+
+

Final Output

+
+
+ +Future practitioners will design prompt *systems* rather than individual prompts. + +### Self-Improving Prompts + +AI systems are beginning to: + +- **Optimize their own prompts** - Meta-learning for better instructions +- **Learn from feedback** - Adapting based on outcomes +- **Generate training data** - Creating examples for fine-tuning +- **Evaluate themselves** - Building in quality assessment + + + +### Natural Language Programming + +The line between prompting and programming is blurring: + +- **Prompts as code** - Version-controlled, tested, deployed +- **LLMs as interpreters** - Natural language as executable instructions +- **Hybrid systems** - Combining traditional code with AI reasoning +- **AI-assisted development** - Models that write and debug code + +Understanding prompting increasingly means understanding software development. + +## Skills for the Future + +### What Will Remain Valuable + +Certain skills will remain essential regardless of how AI evolves: + +1. **Clear thinking** - Knowing what you actually want +2. **Domain expertise** - Understanding the problem space +3. **Critical evaluation** - Assessing AI output quality +4. **Ethical judgment** - Knowing what *should* be done +5. **Iterative refinement** - Continuous improvement mindset + +### What Will Change + +Other aspects will shift significantly: + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
TodayTomorrow
Writing detailed promptsDesigning agent systems
Manual prompt optimizationAutomated prompt tuning
Single-model expertiseMulti-model orchestration
Text-focused interactionMultimodal fluency
Individual productivityTeam-AI collaboration
+
+ +### Staying Current + +To keep your skills relevant: + +- **Experiment continuously** - Try new models and features as they release +- **Follow research** - Stay aware of academic developments +- **Join communities** - Learn from other practitioners +- **Build projects** - Apply skills to real problems +- **Teach others** - Solidify understanding by explaining + +## The Human Element + +### AI as Amplifier + +At its best, AI amplifies human capability rather than replacing it: + +- **Experts become more expert** - AI handles routine work, humans focus on insight +- **Creativity expands** - More ideas explored, more possibilities tested +- **Access democratizes** - Capabilities once requiring specialists become available to all +- **Collaboration deepens** - Human-AI teams exceed either alone + +### The Irreplaceable Human + +Certain qualities remain distinctly human: + +- **Original experience** - Living in the world, having emotions and relationships +- **Values and ethics** - Deciding what matters and what's right +- **Accountability** - Taking responsibility for outcomes +- **Meaning-making** - Understanding *why* something matters +- **Genuine creativity** - True novelty born from unique perspective + + +As AI handles more routine cognitive tasks, your unique value lies in judgment, creativity, domain expertise, and the human connections AI cannot replicate. Invest in what makes you irreplaceable. + + +## Final Reflections + +### What We've Learned + +Throughout this book, we've explored: + +- **Foundations** - How AI models work and what makes prompts effective +- **Techniques** - Role-based prompting, chain-of-thought, few-shot learning, and more +- **Advanced strategies** - System prompts, prompt chaining, multimodal interaction +- **Best practices** - Avoiding pitfalls, ethical considerations, optimization +- **Applications** - Writing, programming, education, business, creativity, research + +These techniques share common threads: + +1. **Be clear and specific** - Know what you want and communicate it precisely +2. **Provide context** - Give AI the information it needs +3. **Structure your requests** - Organization improves outputs +4. **Iterate and refine** - First attempts are starting points, not endpoints +5. **Evaluate critically** - AI output requires human judgment + +### The Art and Science + +Prompting is both **art and science**: + +- **Science**: Testable hypotheses, measurable outcomes, reproducible techniques +- **Art**: Intuition, creativity, knowing when to break the rules + +The best practitioners combine rigorous methodology with creative experimentation. They test systematically but also trust their instincts. They follow best practices but know when to deviate. + +### A Call to Create + +This book has given you tools. What you build with them is up to you. + +- **Solve problems** that matter to you and others +- **Create things** that didn't exist before +- **Help people** do things they couldn't do alone +- **Push boundaries** of what's possible +- **Stay curious** as the field evolves + +The age of AI is just beginning. The most important applications haven't been invented yet. The most powerful techniques haven't been discovered. The future is being written now—by people like you, one prompt at a time. + +## Looking Ahead + + + + +Visit [prompts.chat](https://prompts.chat) for community prompts, new techniques, and to share your own discoveries. The best learning happens in community. + + +## Summary + + +AI will continue evolving rapidly, but core skills of clear communication, critical thinking, and iterative refinement remain valuable. Focus on what makes you irreplaceable: judgment, creativity, ethics, and genuine human connection. The future of prompting is collaborative, multimodal, and integrated into larger systems. Stay curious, keep experimenting, and build things that matter. + + + + +Thank you for reading *The Interactive Book of Prompting*. Now go create something amazing. diff --git a/src/content/book/ar/25-agents-and-skills.mdx b/src/content/book/ar/25-agents-and-skills.mdx new file mode 100644 index 00000000..ba355859 --- /dev/null +++ b/src/content/book/ar/25-agents-and-skills.mdx @@ -0,0 +1,551 @@ +As AI systems evolve from simple question-answering to autonomous task execution, understanding **agents** and **skills** becomes essential. This chapter explores how prompts serve as the fundamental building blocks for AI agents, and how skills package expertise into reusable, comprehensive instruction sets. + +
+
+
+
+ +
+

Agent

+

Autonomous AI system

+
+
+ powered by + ↓ +
+
+
+
+ +
+

Skill

+

Reusable expertise

+
+
+
+ +
+

Skill

+

Reusable expertise

+
+
+
+ +
+

Skill

+

Reusable expertise

+
+
+
+ composed of + ↓ +
+
+
+ + Prompt +
+
+ + Prompt +
+
+ + Prompt +
+
+ + Prompt +
+
+ + Prompt +
+
+

Prompts are atoms → Skills are molecules → Agents are complete structures

+
+
+ +## What Are AI Agents? + +An **AI agent** is an AI system that can autonomously plan, execute, and iterate on tasks. Unlike simple prompt-response interactions, agents can: + +- **Plan** - Break down complex goals into actionable steps +- **Execute** - Use tools and take actions in the real world +- **Observe** - Process feedback from their actions +- **Adapt** - Adjust their approach based on results +- **Persist** - Maintain context and memory across interactions + +
+
+
+
+

Goal

+
+
→
+
+
+
+

Plan

+
+
→
+
+

Execute

+
+
→
+
+

Observe

+
+
→
+
+

Adapt

+
+
+
+ ↺ Loop until complete +
+
+
→
+
+

Done

+
+
+
+
+ +## Prompts as Building Blocks + +Every agent, no matter how sophisticated, is built from prompts. Just as atoms combine to form molecules, and molecules combine to form complex structures, prompts combine to create intelligent agent behavior. + +
+
+

System Prompts

+

Identity & Role

+
+
+

Planning Prompts

+

How to Think

+
+
+

Tool Prompts

+

How to Act

+
+
+

Recovery Prompts

+

How to Recover

+
+
+ +These prompt types stack together to form complete agent behavior: + +### System Prompts (The Agent's Identity) + +The foundational prompt that establishes who the agent is and how it behaves: + +```markdown +You are a code review assistant. Your role is to: +- Analyze code for bugs, security issues, and performance problems +- Suggest improvements following best practices +- Explain your reasoning clearly +- Be constructive and educational in feedback + +You have access to tools for reading files, searching code, and running tests. +``` + +### Planning Prompts (How to Think) + +Instructions that guide the agent's reasoning and planning process: + +```markdown +Before taking action, always: +1. Understand the complete request +2. Break it into smaller, verifiable steps +3. Identify which tools you'll need +4. Consider edge cases and potential issues +5. Execute step by step, validating as you go +``` + +### Tool-Use Prompts (How to Act) + +Guidance on when and how to use available tools: + +```markdown +When you need to understand a codebase: +- Use grep_search for finding specific patterns +- Use read_file to examine file contents +- Use list_dir to explore directory structure +- Always verify your understanding before making changes +``` + +### Recovery Prompts (How to Handle Failure) + +Instructions for when things go wrong: + +```markdown +If an action fails: +1. Analyze the error message carefully +2. Consider alternative approaches +3. Ask for clarification if the task is ambiguous +4. Never repeat the same failed action without changes +``` + + +An agent's behavior emerges from layers of prompts working together. The system prompt sets the foundation, planning prompts guide reasoning, tool prompts enable action, and recovery prompts handle failures. Together, they create coherent, capable behavior. + + +## What Are Skills? + +If prompts are the atoms, **skills are the molecules**—reusable building blocks that give agents specific capabilities. + +A **skill** is a comprehensive, portable package of instructions that gives an AI agent expertise in a specific domain or task. Skills are the reusable blocks of agents: you build them once, and any agent can use them. + + +Write a skill for code review once. Now every coding agent—whether it's for Python, JavaScript, or Rust—can instantly become an expert code reviewer by loading that skill. Skills let you build agent capabilities like LEGO blocks. + + +### Anatomy of a Skill + +A well-designed skill typically includes: + +
+
+

📄 SKILL.md (Required)

+

The main instruction file. Contains the core expertise, guidelines, and behaviors that define the skill.

+
+
+

📚 Reference Docs

+

Supporting documentation, examples, and context the agent can reference while working.

+
+
+

🔧 Scripts & Tools

+

Helper scripts, templates, or tool configurations that support the skill's functionality.

+
+
+

⚙️ Configuration

+

Settings, parameters, and customization options for adapting the skill to different contexts.

+
+
+ +### Example: Code Review Skill + +Here's what a code review skill might look like: + +
+
+ 📁 + code-review-skill/ +
+
+
+ 📄 + SKILL.md + Core review guidelines +
+
+ 📄 + security-checklist.md + Security patterns +
+
+ 📄 + performance-tips.md + Optimization guide +
+
+
+ 📁 + language-specific/ +
+
+
+ 📄 + python.md + Python best practices +
+
+ 📄 + javascript.md + JavaScript patterns +
+
+ 📄 + rust.md + Rust guidelines +
+
+
+
+
+ +The `SKILL.md` file defines the overall approach: + +```markdown +--- +name: code-review +description: Comprehensive code review with security, performance, and style analysis +--- + +# Code Review Skill + +You are an expert code reviewer. When reviewing code: + +## Process +1. **Understand Context** - What does this code do? What problem does it solve? +2. **Check Correctness** - Does it work? Are there logic errors? +3. **Security Scan** - Reference security-checklist.md for common vulnerabilities +4. **Performance Review** - Check performance-tips.md for optimization opportunities +5. **Style & Maintainability** - Is the code readable and maintainable? + +## Output Format +Provide feedback in categories: +- 🔴 **Critical** - Must fix before merge +- 🟡 **Suggested** - Recommended improvements +- 🟢 **Nice to have** - Optional enhancements + +Always explain *why* something is an issue, not just *what* is wrong. +``` + +## Skills vs. Simple Prompts + +
+
+

Simple Prompt

+
+

Single instruction

+

One-off use

+

Limited context

+

Generic approach

+

No supporting materials

+
+
+
+

Skill

+
+

Comprehensive instruction set

+

Reusable across projects

+

Rich context with references

+

Domain-specific expertise

+

Supporting docs, scripts, configs

+
+
+
+ +## Building Effective Skills + +### 1. Define the Expertise Clearly + +Start with a clear description of what the skill enables: + +```markdown +--- +name: api-design +description: Design RESTful APIs following industry best practices, + including versioning, error handling, and documentation standards +--- +``` + +### 2. Structure Knowledge Hierarchically + +Organize information from general to specific: + +```markdown +# API Design Skill + +## Core Principles +- Resources should be nouns, not verbs +- Use HTTP methods semantically +- Version your APIs from day one + +## Detailed Guidelines +[More specific rules...] + +## Reference Materials +- See `rest-conventions.md` for naming conventions +- See `error-codes.md` for standard error responses +``` + +### 3. Include Concrete Examples + +Abstract rules become clear with examples: + +```markdown +## Endpoint Naming + +✅ Good: +- GET /users/{id} +- POST /orders +- DELETE /products/{id}/reviews/{reviewId} + +❌ Avoid: +- GET /getUser +- POST /createNewOrder +- DELETE /removeProductReview +``` + +### 4. Provide Decision Frameworks + +Help the agent make choices in ambiguous situations: + +```markdown +## When to Use Pagination + +Use pagination when: +- Collection could exceed 100 items +- Response size impacts performance +- Client may not need all items + +Use full response when: +- Collection is always small (<20 items) +- Client typically needs everything +- Real-time consistency is critical +``` + +### 5. Add Recovery Patterns + +Anticipate what can go wrong: + +```markdown +## Common Issues + +**Problem**: Client needs fields not in standard response +**Solution**: Implement field selection: GET /users?fields=id,name,email + +**Problem**: Breaking changes needed +**Solution**: Create new version, deprecate old with timeline +``` + +## Composing Skills + +Agents become powerful when multiple skills work together. Consider how skills can complement each other: + +
+
+ Code Review +
+
+
+
+ Security Audit +
+
+
+
+ Documentation +
+
=
+
+ Complete Code Quality Agent +
+
+ +When composing skills, ensure they don't conflict. Skills should be: + +- **Modular** - Each skill handles one domain well +- **Compatible** - Skills shouldn't give contradictory instructions +- **Prioritized** - When skills overlap, define which takes precedence + +## Sharing and Discovering Skills + +Skills are most valuable when shared. Platforms like [prompts.chat](https://prompts.chat/skills) allow you to: + +- **Discover** community-created skills for common tasks +- **Download** skills directly to your projects +- **Share** your own expertise as reusable skills +- **Iterate** on skills based on real-world usage + + +Before building a skill from scratch, check if someone has already solved your problem. Community skills are battle-tested and often better than starting from zero. + + +## The Agent-Skill Ecosystem + +The relationship between agents and skills creates a powerful ecosystem: + +
+
+ AI Agent +
+
+
+

Code Review

+

Skill 1

+
+
+

API Design

+

Skill 2

+
+
+

Test Writing

+

Skill 3

+
+
+
+
↓
+
+
+
+

Core Prompts

+

Planning • Tools • Recovery • Memory

+
+
+
+ +The agent provides the execution framework—planning, tool use, and memory—while skills provide domain expertise. This separation means: + +- **Skills are portable** - The same skill works with different agents +- **Agents are extensible** - Add new capabilities by adding skills +- **Expertise is shareable** - Domain experts can contribute skills without building full agents + +## Best Practices + +### For Building Skills + +1. **Start specific, then generalize** - Build a skill for your exact use case first, then abstract +2. **Include failure cases** - Document what the skill can't do and how to handle it +3. **Version your skills** - Track changes so agents can depend on stable versions +4. **Test with real tasks** - Validate skills against actual work, not just theory + +### For Using Skills with Agents + +1. **Read the skill first** - Understand what a skill does before deploying it +2. **Customize thoughtfully** - Override skill defaults only when necessary +3. **Monitor performance** - Track how well skills perform in your context +4. **Contribute improvements** - When you improve a skill, consider sharing back + + +As AI agents become more capable, the ability to compose, share, and customize skills will become a core competency. The prompt engineers of tomorrow won't just write prompts—they'll architect skill ecosystems that make AI agents genuinely expert in specific domains. + + + + + + + diff --git a/src/content/book/de/00a-preface.mdx b/src/content/book/de/00a-preface.mdx new file mode 100644 index 00000000..89605baf --- /dev/null +++ b/src/content/book/de/00a-preface.mdx @@ -0,0 +1,82 @@ +
+ Fatih Kadir Akın +
+ Fatih Kadir Akın + Schöpfer von Awesome ChatGPT Prompts (auch bekannt als prompts.chat) + + Softwareentwickler aus Istanbul, leitet Developer Relations bei Teknasyon. Autor von Büchern über JavaScript und Prompt Engineering. Open-Source-Befürworter mit Spezialisierung auf Webtechnologien und KI-gestützte Entwicklung. + + +
+
+ +Ich erinnere mich noch genau an die Nacht, in der sich alles veränderte. + +Es war der **30. November 2022**. Ich saß an meinem Schreibtisch und scrollte durch Twitter, als ich sah, dass Leute über etwas namens „ChatGPT" sprachen. Ich klickte auf den Link, aber ehrlich gesagt? Ich erwartete nicht viel. Ich hatte diese alten „Wortvervollständigungs"-KI-Tools schon ausprobiert, die nach ein paar Sätzen nur noch Unsinn produzierten. Ich dachte, das hier würde genauso sein. + +Ich tippte eine einfache Frage ein und drückte Enter. + +Dann erstarrte ich. + +Die Antwort war nicht nur zusammenhängend. Sie war *gut*. Sie verstand, was ich meinte. Sie konnte argumentieren. Es fühlte sich völlig anders an als alles, was ich zuvor gesehen hatte. Ich versuchte einen weiteren Prompt. Und noch einen. Jede Antwort erstaunte mich mehr als die vorherige. + +Ich konnte in dieser Nacht nicht schlafen. Zum ersten Mal hatte ich das Gefühl, wirklich mit einer Maschine zu *sprechen*, und sie antwortete auf eine Weise, die tatsächlich Sinn ergab. + +## Ein Repository, das aus Staunen entstand + +In diesen frühen Tagen war ich mit meiner Begeisterung nicht allein. Überall, wo ich hinschaute, entdeckten Menschen kreative Wege, ChatGPT zu nutzen. Lehrer verwendeten es, um komplexe Konzepte zu erklären. Schriftsteller arbeiteten mit ihm an Geschichten. Entwickler debuggten Code mit seiner Hilfe. + +Ich begann, die besten Prompts zu sammeln, die ich fand. Die, die wie Magie funktionierten. Die, die einfache Fragen in brillante Antworten verwandelten. Und ich dachte: *Warum sollte ich das für mich behalten?* + +Also erstellte ich ein einfaches GitHub-Repository namens [Awesome ChatGPT Prompts](https://github.com/f/prompts.chat). Ich erwartete, dass vielleicht ein paar hundert Leute es nützlich finden würden. + +Ich lag falsch. + +Innerhalb weniger Wochen hob das Repository ab. Tausende von Stars. Dann Zehntausende. Menschen aus der ganzen Welt begannen, ihre eigenen Prompts hinzuzufügen, zu teilen, was sie gelernt hatten, und sich gegenseitig zu helfen. Was als meine persönliche Sammlung begann, wurde zu etwas viel Größerem: einer weltweiten Gemeinschaft neugieriger Menschen, die sich gegenseitig helfen. + +Heute hat dieses Repository über **140.000 GitHub-Stars** und Beiträge von Hunderten von Menschen, die ich nie getroffen habe, denen ich aber zutiefst dankbar bin. + +## Warum ich dieses Buch geschrieben habe + +Die Originalversion dieses Buches wurde **Anfang 2023** auf [Gumroad](https://gumroad.com/l/the-art-of-chatgpt-prompting) veröffentlicht, nur Monate nach dem Start von ChatGPT. Es war eines der ersten Bücher überhaupt, das über Prompt Engineering geschrieben wurde – ein Versuch, alles festzuhalten, was ich über das Erstellen effektiver Prompts gelernt hatte, als das Feld noch brandneu war. Zu meinem Erstaunen haben über **100.000 Menschen** es heruntergeladen. + +Aber seitdem sind drei Jahre vergangen. KI hat sich stark verändert. Neue Modelle sind erschienen. Und wir alle haben so viel mehr darüber gelernt, wie man mit KI kommuniziert. + +Diese neue Ausgabe ist mein Geschenk an die Community, die mir so viel gegeben hat. Sie enthält alles, was ich mir gewünscht hätte zu wissen, als ich anfing: **was funktioniert**, **was man vermeiden sollte** und **Ideen, die wahr bleiben**, egal welche KI man verwendet. + +## Was dieses Buch für mich bedeutet + +Ich werde nicht so tun, als wäre dies nur eine Bedienungsanleitung. Es bedeutet mir mehr als das. + +Dieses Buch fängt einen Moment ein, in dem sich die Welt veränderte und Menschen zusammenkamen, um es herauszufinden. Es repräsentiert späte Nächte des Ausprobierens, die Freude der Entdeckung und die Freundlichkeit von Fremden, die teilten, was sie gelernt hatten. + +Vor allem repräsentiert es meinen Glauben, dass **der beste Weg, etwas zu lernen, ist, es mit anderen zu teilen**. + +## Für dich + +Ob du gerade erst mit KI anfängst oder sie schon seit Jahren verwendest, ich habe dieses Buch für dich geschrieben. + +Ich hoffe, es spart dir Zeit. Ich hoffe, es entfacht Ideen. Ich hoffe, es hilft dir, Dinge zu erreichen, die du nie für möglich gehalten hast. + +Und wenn du etwas Erstaunliches entdeckst, hoffe ich, dass du es mit anderen teilst, so wie so viele Menschen mit mir geteilt haben. + +**So werden wir alle zusammen besser.** + +Danke, dass du hier bist. Danke, dass du Teil dieser Community bist. + +Jetzt lass uns beginnen. + +--- + +*Mit Dankbarkeit,* + +**Fatih Kadir Akın** +*Istanbul, Januar 2025* diff --git a/src/content/book/de/00b-history.mdx b/src/content/book/de/00b-history.mdx new file mode 100644 index 00000000..e8cd4ff1 --- /dev/null +++ b/src/content/book/de/00b-history.mdx @@ -0,0 +1,159 @@ +# Die Geschichte von Awesome ChatGPT Prompts + +## Der Anfang: November 2022 + +Als ChatGPT im November 2022 gestartet wurde, veränderte sich die Welt der KI über Nacht. Was einst die Domäne von Forschern und Entwicklern war, wurde plötzlich für alle zugänglich. Unter denen, die von dieser neuen Technologie fasziniert waren, war Fatih Kadir Akın, ein Entwickler, der etwas Bemerkenswertes in den Fähigkeiten von ChatGPT sah. + +> „Als ChatGPT zum ersten Mal gestartet wurde, war ich sofort von seinen Fähigkeiten fasziniert. Ich experimentierte auf vielfältige Weise mit dem Tool und war immer wieder erstaunt über die Ergebnisse." + +Diese frühen Tage waren voller Experimentieren und Entdeckungen. Nutzer auf der ganzen Welt fanden kreative Wege, mit ChatGPT zu interagieren, teilten ihre Erkenntnisse und lernten voneinander. In dieser Atmosphäre der Begeisterung und Erkundung wurde die Idee für „Awesome ChatGPT Prompts" geboren. + +## Das Repository, das alles begann + +Im Dezember 2022, nur wenige Wochen nach dem Start von ChatGPT, wurde das Repository [Awesome ChatGPT Prompts](https://github.com/f/prompts.chat) auf GitHub erstellt. Das Konzept war einfach, aber wirkungsvoll: eine kuratierte Sammlung effektiver Prompts, die jeder nutzen und zu der jeder beitragen konnte. + +Das Repository gewann schnell an Zugkraft und wurde zu einer bevorzugten Ressource für ChatGPT-Nutzer weltweit. Was als persönliche Sammlung nützlicher Prompts begann, entwickelte sich zu einem von der Community getriebenen Projekt mit Beiträgen von Entwicklern, Schriftstellern, Pädagogen und Enthusiasten aus allen Ecken der Welt. + +### Erfolge + +**Presse & Medien** +- Vorgestellt in [Forbes](https://www.forbes.com/sites/bernardmarr/2023/05/17/the-best-prompts-for-chatgpt-a-complete-guide/) als eine der besten ChatGPT-Prompt-Ressourcen + +**Akademische Anerkennung** +- Referenziert von der [Harvard University](https://www.huit.harvard.edu/news/ai-prompts) in ihren KI-Richtlinien +- Referenziert von der [Columbia University](https://etc.cuit.columbia.edu/news/columbia-prompt-library-effective-academic-ai-use) Prompt Library +- Verwendet vom [Olympic College](https://libguides.olympic.edu/UsingAI/Prompts) in ihren KI-Ressourcen +- Zitiert in [wissenschaftlichen Arbeiten auf arXiv](https://arxiv.org/pdf/2502.04484) +- [40+ akademische Zitierungen](https://scholar.google.com/citations?user=AZ0Dg8YAAAAJ&hl=en) auf Google Scholar + +**Community & GitHub** +- [142.000+ GitHub-Stars](https://github.com/f/prompts.chat) — eines der meist gesternten KI-Repositories +- Ausgewählt als [GitHub Staff Pick](https://spotlights-feed.github.com/spotlights/prompts-chat/) +- Beliebtester Datensatz veröffentlicht auf [Hugging Face](https://huggingface.co/datasets/fka/prompts.chat) +- Verwendet von Tausenden von Entwicklern weltweit + +## Das erste Buch: „The Art of ChatGPT Prompting" + +Der Erfolg des Repositories führte zur Erstellung von „The Art of ChatGPT Prompting: A Guide to Crafting Clear and Effective Prompts" – einem umfassenden Leitfaden, der Anfang 2023 auf Gumroad veröffentlicht wurde. + +Das Buch erfasste die frühe Weisheit des Prompt Engineering und behandelte: + +- Verstehen, wie ChatGPT funktioniert +- Prinzipien klarer Kommunikation mit KI +- Die berühmte „Act As"-Technik +- Schritt-für-Schritt-Erstellung effektiver Prompts +- Häufige Fehler und wie man sie vermeidet +- Tipps zur Fehlerbehebung + +**Das Buch wurde zu einem Phänomen** und erreichte über **100.000 Downloads** auf Gumroad. Es wurde in sozialen Medien geteilt, in wissenschaftlichen Arbeiten referenziert und von Community-Mitgliedern in mehrere Sprachen übersetzt. Hochkarätige Empfehlungen kamen von unerwarteten Stellen – sogar [Greg Brockman](https://x.com/gdb/status/1602072566671110144), Mitgründer und Präsident von OpenAI, würdigte das Projekt. + +## Frühe Erkenntnisse, die das Feld prägten + +In diesen prägenden Monaten entstanden mehrere Schlüsselerkenntnisse, die grundlegend für das Prompt Engineering werden sollten: + +### 1. Spezifität ist wichtig + +> „Ich lernte die Wichtigkeit, spezifische und relevante Sprache zu verwenden, um sicherzustellen, dass ChatGPT meine Prompts versteht und in der Lage ist, angemessene Antworten zu generieren." + +Frühe Experimentatoren entdeckten, dass vage Prompts zu vagen Antworten führten. Je spezifischer und detaillierter der Prompt, desto nützlicher die Ausgabe. + +### 2. Zweck und Fokus + +> „Ich entdeckte den Wert, einen klaren Zweck und Fokus für das Gespräch zu definieren, anstatt offene oder zu breite Prompts zu verwenden." + +Diese Erkenntnis wurde zur Grundlage für strukturierte Prompting-Techniken, die sich in den folgenden Jahren entwickeln sollten. + +### 3. Die „Act As"-Revolution + +Eine der einflussreichsten Techniken, die aus der Community hervorgingen, war das „Act As"-Muster. Indem man ChatGPT anweist, eine bestimmte Rolle oder Persona anzunehmen, konnten Nutzer die Qualität und Relevanz der Antworten dramatisch verbessern. + +``` +I want you to act as a javascript console. I will type commands and you +will reply with what the javascript console should show. I want you to +only reply with the terminal output inside one unique code block, and +nothing else. +``` + +Diese einfache Technik eröffnete unzählige Möglichkeiten und bleibt bis heute eine der am weitesten verbreiteten Prompting-Strategien. + +## Die Evolution von prompts.chat + +### 2022: Der Anfang + +Das Projekt begann als einfaches GitHub-Repository mit einer README-Datei, die als HTML auf GitHub Pages gerendert wurde. Es war minimalistisch, aber funktional – ein Beweis für das Prinzip, dass großartige Ideen keine aufwendigen Implementierungen brauchen. + +**Tech Stack**: HTML, CSS, GitHub Pages + +### 2024: UI-Erneuerung + +Als die Community wuchs, wuchs auch der Bedarf an einer besseren Benutzererfahrung. Die Website erhielt ein bedeutendes UI-Update, das mit Hilfe von KI-Coding-Assistenten wie Cursor und Claude Sonnet 3.5 erstellt wurde. + +### 2025: Die aktuelle Plattform + +Heute hat sich prompts.chat zu einer vollwertigen Plattform entwickelt, die mit folgenden Technologien erstellt wurde: + +- **Next.js** für das Web-Framework +- **Vercel** für das Hosting +- **KI-gestützte Entwicklung** mit Windsurf und Claude + +Die Plattform bietet jetzt Benutzerkonten, Sammlungen, Suche, Kategorien, Tags und eine blühende Community von Prompt-Ingenieuren. + +### Native Apps + +Das Projekt expandierte über das Web hinaus mit einer nativen iOS-App, die mit SwiftUI erstellt wurde und die Prompt-Bibliothek auf mobile Nutzer brachte. + +## Community-Wirkung + +Das Awesome ChatGPT Prompts-Projekt hatte einen tiefgreifenden Einfluss darauf, wie Menschen mit KI interagieren: + +### Akademische Anerkennung + +Universitäten auf der ganzen Welt haben das Projekt in ihren KI-Orientierungsmaterialien referenziert, darunter: + +- Harvard University +- Columbia University +- Olympic College +- Zahlreiche wissenschaftliche Arbeiten auf arXiv + +### Entwickler-Adoption + +Das Projekt wurde in unzählige Entwickler-Workflows integriert. Der Hugging Face-Datensatz wird von Forschern und Entwicklern zum Trainieren und Feinabstimmen von Sprachmodellen verwendet. + +### Globale Community + +Mit Beiträgen von Hunderten von Community-Mitgliedern aus Dutzenden von Ländern repräsentiert das Projekt eine wirklich globale Anstrengung, KI für alle zugänglicher und nützlicher zu machen. + +## Die Philosophie: Offen und frei + +Von Anfang an hat sich das Projekt der Offenheit verschrieben. Lizenziert unter CC0 1.0 Universal (Public Domain Dedication), sind alle Prompts und Inhalte frei verwendbar, modifizierbar und ohne Einschränkungen teilbar. + +Diese Philosophie hat ermöglicht: + +- Übersetzungen in mehrere Sprachen +- Integration in andere Tools und Plattformen +- Akademische Nutzung und Forschung +- Kommerzielle Anwendungen + +Das Ziel war schon immer, den Zugang zu effektiven KI-Kommunikationstechniken zu demokratisieren – um sicherzustellen, dass jeder, unabhängig vom technischen Hintergrund, von diesen Tools profitieren kann. + +## Drei Jahre später + +Drei Jahre nach dem Start von ChatGPT hat sich das Feld des Prompt Engineering erheblich weiterentwickelt. Was als informelles Experimentieren begann, hat sich zu einer anerkannten Disziplin mit etablierten Mustern, Best Practices und einer aktiven Forschungsgemeinschaft entwickelt. + +Das Awesome ChatGPT Prompts-Projekt ist gemeinsam mit diesem Feld gewachsen und hat sich von einer einfachen Liste von Prompts zu einer umfassenden Plattform zum Entdecken, Teilen und Lernen über KI-Prompts entwickelt. + +Dieses Buch repräsentiert die nächste Evolution – eine Destillation von drei Jahren Community-Weisheit, aktualisiert für die KI-Landschaft von heute und morgen. + +## Blick nach vorn + +Die Reise von diesem ersten Repository zu diesem umfassenden Leitfaden spiegelt die rasante Evolution der KI und unser Verständnis davon wider, wie man effektiv mit ihr arbeitet. Mit fortschreitenden KI-Fähigkeiten werden sich auch die Techniken zur Kommunikation mit diesen Systemen weiterentwickeln. + +Die in jenen frühen Tagen entdeckten Prinzipien – Klarheit, Spezifität, Zweck und die Kraft des Rollenspiels – bleiben so relevant wie eh und je. Aber neue Techniken entstehen weiterhin: Chain-of-Thought-Prompting, Few-Shot-Learning, multimodale Interaktionen und mehr. + +Die Geschichte von Awesome ChatGPT Prompts ist letztendlich eine Geschichte über Community – über Tausende von Menschen auf der ganzen Welt, die ihre Entdeckungen teilen, einander beim Lernen helfen und gemeinsam unser Verständnis davon vorantreiben, wie man mit KI arbeitet. + +Dieser Geist der offenen Zusammenarbeit und des gemeinsamen Lernens ist das, was dieses Buch fortsetzen möchte. + +--- + +*Das Awesome ChatGPT Prompts-Projekt wird gepflegt von [@f](https://github.com/f) und einer erstaunlichen Community von Mitwirkenden. Besuche [prompts.chat](https://prompts.chat), um die Plattform zu erkunden, und mach mit auf [GitHub](https://github.com/f/prompts.chat).* diff --git a/src/content/book/de/00c-introduction.mdx b/src/content/book/de/00c-introduction.mdx new file mode 100644 index 00000000..bd3678aa --- /dev/null +++ b/src/content/book/de/00c-introduction.mdx @@ -0,0 +1,130 @@ +Willkommen zum **Interaktiven Buch des Promptings**, deinem Leitfaden für effektive Kommunikation mit KI. + + +Am Ende dieses Buches wirst du verstehen, wie KI funktioniert, wie man bessere Prompts schreibt und wie man diese Fähigkeiten für Schreiben, Programmieren, Recherche und kreative Projekte nutzt. + + + +Anders als traditionelle Bücher ist dieser Leitfaden vollständig interaktiv. Du findest Live-Demos, anklickbare Beispiele und „Probier es aus"-Buttons, mit denen du Prompts sofort testen kannst. Lernen durch Tun macht komplexe Konzepte viel leichter verständlich. + + +## Was ist Prompt Engineering? + +Prompt Engineering ist die Fähigkeit, gute Anweisungen für KI zu schreiben. Wenn du etwas an ChatGPT, Claude, Gemini oder andere KI-Tools schreibst, nennt man das einen „Prompt". Je besser dein Prompt, desto besser die Antwort, die du bekommst. + +Stell es dir so vor: KI ist ein leistungsstarker Helfer, der deine Worte sehr wörtlich nimmt. Sie wird genau das tun, was du fragst. Der Trick ist zu lernen, wie man genau das fragt, was man will. + + + +Der Unterschied in der Ausgabequalität zwischen diesen beiden Prompts kann dramatisch sein. + + + +## Wie sich Prompt Engineering entwickelt hat + +In nur drei Jahren seit dem Start von ChatGPT hat sich Prompt Engineering dramatisch zusammen mit der Technologie selbst entwickelt. Was als einfaches „bessere Fragen stellen" begann, ist zu etwas viel Breiterem gewachsen. + +Heute verstehen wir, dass dein Prompt nur **ein Teil eines größeren Kontexts** ist. Moderne KI-Systeme arbeiten gleichzeitig mit mehreren Datentypen: + +- **System-Prompts**, die das Verhalten der KI definieren +- **Gesprächsverlauf** aus vorherigen Nachrichten +- **Abgerufene Dokumente** aus Datenbanken (RAG) +- **Tool-Definitionen**, die der KI ermöglichen, Aktionen auszuführen +- **Benutzereinstellungen** und Präferenzen +- **Dein eigentlicher Prompt** - die Frage, die du gerade stellst + +Dieser Wandel von „Prompt Engineering" zu „Context Engineering" spiegelt wider, wie wir jetzt über KI-Interaktionen denken. Dein Prompt ist wichtig, aber auch alles andere, was die KI sieht. Die besten Ergebnisse entstehen durch sorgfältiges Management all dieser Teile zusammen. + +Wir werden diese Konzepte im gesamten Buch ausführlich erkunden, besonders im Kapitel [Context Engineering](/book/20-context-engineering). + +## Warum ist Prompt Engineering wichtig? + +### 1. Bessere Antworten bekommen + +KI-Tools sind unglaublich leistungsfähig, aber sie brauchen klare Anweisungen, um ihr volles Potenzial zu entfalten. Dieselbe KI, die auf eine vage Frage eine mittelmäßige Antwort gibt, kann brillante Arbeit leisten, wenn sie richtig angeleitet wird. + + + +### 2. Zeit und Geld sparen + +Ein gut formulierter Prompt liefert Ergebnisse beim ersten Versuch statt nach mehrfachem Hin und Her. Das ist noch wichtiger, wenn du pro Token bezahlst oder mit Rate-Limits arbeitest. Eine 5-minütige Investition in einen guten Prompt kann Stunden an Iteration sparen. + +### 3. Konsistente, reproduzierbare Ergebnisse + +Gute Prompts produzieren vorhersagbare Ausgaben. Das ist entscheidend für: +- **Geschäftsabläufe**, bei denen du jedes Mal die gleiche Qualität brauchst +- **Automatisierung**, bei der Prompts ohne menschliche Überprüfung laufen +- **Teams**, bei denen mehrere Personen ähnliche Ergebnisse brauchen + +### 4. Fortgeschrittene Funktionen freischalten + +Viele leistungsstarke KI-Funktionen funktionieren nur, wenn du weißt, wie man fragt: +- **Chain-of-Thought-Reasoning** für komplexe Probleme +- **Strukturierte Ausgabe** für Datenextraktion +- **Rollenspiel** für spezialisiertes Fachwissen +- **Few-Shot-Learning** für benutzerdefinierte Aufgaben + +Ohne Prompt-Engineering-Wissen nutzt du nur einen Bruchteil dessen, was KI kann. + +### 5. Sicher bleiben und Fallstricke vermeiden + +Gutes Prompting hilft dir: +- Halluzinationen zu vermeiden, indem du nach Quellen und Verifizierung fragst +- Ausgewogene Perspektiven statt einseitiger Antworten zu bekommen +- Die KI davon abzuhalten, Annahmen zu treffen, die du nicht beabsichtigt hast +- Sensible Informationen aus deinen Prompts herauszuhalten + +### 6. Deine Fähigkeiten zukunftssicher machen + +Da KI immer stärker in Arbeit und Leben integriert wird, wird Prompt Engineering zu einer grundlegenden Kompetenz. Die Prinzipien, die du hier lernst, gelten für alle KI-Tools – ChatGPT, Claude, Gemini, Bildgeneratoren und zukünftige Modelle, die wir noch nicht kennen. + +## Für wen ist dieses Buch? + +Dieses Buch ist für alle: + +- **Anfänger**, die lernen wollen, KI-Tools besser zu nutzen +- **Schüler und Studenten**, die an Hausaufgaben, Recherche oder kreativen Projekten arbeiten +- **Autoren und Kreative**, die KI für ihre Arbeit nutzen +- **Entwickler**, die Apps mit KI bauen +- **Geschäftsleute**, die KI bei der Arbeit nutzen wollen +- **Alle Neugierigen**, die mehr aus KI-Assistenten herausholen wollen + +## Wie dieses Buch aufgebaut ist + + + +Plus ein **Anhang** mit Vorlagen, Hilfe zur Fehlerbehebung, Glossar und zusätzlichen Ressourcen. + +## Hinweis zu KI-Modellen + +Dieses Buch verwendet hauptsächlich Beispiele von ChatGPT (da es am beliebtesten ist), aber die Ideen funktionieren mit jedem KI-Tool wie Claude, Gemini oder anderen. Wir erwähnen es, wenn etwas nur mit bestimmten KI-Modellen funktioniert. + +KI entwickelt sich schnell. Was heute funktioniert, könnte morgen durch etwas Besseres ersetzt werden. Deshalb konzentriert sich dieses Buch auf Kernideen, die nützlich bleiben, egal welche KI du verwendest. + +## Lass uns anfangen + +Gute Prompts zu schreiben ist eine Fähigkeit, die mit Übung besser wird. Während du dieses Buch liest: + +1. **Probiere Dinge aus** - Teste die Beispiele, ändere sie, schau was passiert +2. **Bleib dran** - Erwarte keine perfekten Ergebnisse beim ersten Versuch +3. **Mach Notizen** - Schreibe auf, was funktioniert und was nicht +4. **Teile** - Füge deine Entdeckungen zu [prompts.chat](https://prompts.chat) hinzu + + +Der beste Weg zu lernen ist durch Tun. Jedes Kapitel hat Beispiele, die du sofort ausprobieren kannst. Lies nicht nur. Probiere es selbst aus! + + +Bereit, deine Arbeit mit KI zu transformieren? Blättere um und lass uns loslegen. + +--- + +*Dieses Buch ist Teil des [Awesome ChatGPT Prompts](https://github.com/f/prompts.chat) Projekts und ist unter CC0 1.0 Universal (Public Domain) lizenziert.* diff --git a/src/content/book/de/01-understanding-ai-models.mdx b/src/content/book/de/01-understanding-ai-models.mdx new file mode 100644 index 00000000..7ea50ea2 --- /dev/null +++ b/src/content/book/de/01-understanding-ai-models.mdx @@ -0,0 +1,302 @@ +Bevor du Prompt-Techniken lernst, hilft es zu verstehen, wie KI-Sprachmodelle tatsächlich funktionieren. Dieses Wissen wird dich besser im Schreiben von Prompts machen. + + +Zu verstehen, wie KI funktioniert, ist nicht nur für Experten. Es hilft dir direkt, bessere Prompts zu schreiben. Sobald du weißt, dass KI vorhersagt, was als nächstes kommt, wirst du natürlich klarere Anweisungen geben. + + +## Was sind große Sprachmodelle? + +Große Sprachmodelle (Large Language Models, LLMs) sind KI-Systeme, die aus dem Lesen riesiger Textmengen gelernt haben. Sie können schreiben, Fragen beantworten und Gespräche führen, die menschlich klingen. Sie werden „groß" genannt, weil sie Milliarden winziger Einstellungen (genannt Parameter) haben, die während des Trainings angepasst wurden. + +### Wie LLMs funktionieren (vereinfacht) + +Im Kern sind LLMs Vorhersagemaschinen. Du gibst ihnen Text, und sie sagen vorher, was als nächstes kommen sollte. + + + +Wenn du tippst „Die Hauptstadt von Deutschland ist...", sagt die KI „Berlin" voraus, weil das normalerweise als nächstes in Texten über Deutschland kommt. Diese einfache Idee, milliardenfach mit riesigen Datenmengen wiederholt, erzeugt überraschend intelligentes Verhalten. + + + +### Schlüsselkonzepte + +**Tokens**: KI liest nicht Buchstabe für Buchstabe. Sie zerlegt Text in Stücke, die „Tokens" genannt werden. Ein Token kann ein ganzes Wort wie „hallo" sein oder ein Teil eines Wortes wie „ung". Das Verstehen von Tokens hilft zu erklären, warum KI manchmal Rechtschreibfehler macht oder mit bestimmten Wörtern kämpft. + + +Ein Token ist die kleinste Texteinheit, die ein KI-Modell verarbeitet. Es ist nicht immer ein vollständiges Wort – es könnte ein Wortfragment, Satzzeichen oder Leerraum sein. Zum Beispiel könnte „unglaublich" zu 3 Tokens werden: „un" + „glaub" + „lich". Im Durchschnitt gilt: **1 Token ≈ 4 Zeichen** oder **100 Tokens ≈ 75 Wörter**. API-Kosten und Kontextlimits werden in Tokens gemessen. + + + + +**Kontextfenster**: Das ist, wie viel Text die KI in einem Gespräch „erinnern" kann. Stell es dir wie das Kurzzeitgedächtnis der KI vor. Es umfasst alles: deine Frage UND die Antwort der KI. + + + +Kontextfenster variieren je nach Modell und erweitern sich schnell: + +
+
+ GPT-4o + 128K tokens +
+
+ GPT-5 + 400K tokens +
+
+ Claude Sonnet 4 + 1M tokens +
+
+ Gemini 2.5 + 1M tokens +
+
+ Llama 4 + 1M-10M tokens +
+
+ DeepSeek R1 + 128K tokens +
+
+ +**Temperatur**: Dies steuert, wie kreativ oder vorhersagbar die KI ist. Niedrige Temperatur (0.0-0.3) gibt dir fokussierte, konsistente Antworten. Hohe Temperatur (0.7-1.0) gibt dir kreativere, überraschendere Antworten. + + + +**System-Prompt**: Spezielle Anweisungen, die der KI sagen, wie sie sich für ein ganzes Gespräch verhalten soll. Zum Beispiel: „Du bist ein freundlicher Lehrer, der Dinge einfach erklärt." Nicht alle KI-Tools erlauben dir, dies einzustellen, aber es ist sehr mächtig, wenn verfügbar. + +## Arten von KI-Modellen + +### Textmodelle (LLMs) +Der häufigste Typ, diese erzeugen Textantworten auf Texteingaben. Sie betreiben Chatbots, Schreibassistenten und Code-Generatoren. Beispiele: GPT-4, Claude, Llama, Mistral. + +### Multimodale Modelle +Diese können mehr als nur Text verstehen. Sie können Bilder betrachten, Audio hören und Videos ansehen. Beispiele: GPT-4V, Gemini, Claude 3. + +### Text-zu-Bild-Modelle + + +Während sich dieses Buch hauptsächlich auf das Prompting für große Sprachmodelle (textbasierte KI) konzentriert, gelten die Prinzipien des klaren, spezifischen Promptings auch für die Bilderzeugung. Das Beherrschen von Prompts für diese Modelle ist ebenso wichtig, um großartige Ergebnisse zu erzielen. + + +Text-zu-Bild-Modelle wie DALL-E, Midjourney, Nano Banana und Stable Diffusion erstellen Bilder aus Textbeschreibungen. Sie funktionieren anders als Textmodelle: + +**Wie sie funktionieren:** +1. **Training**: Das Modell lernt aus Millionen von Bild-Text-Paaren und versteht, welche Wörter welchen visuellen Konzepten entsprechen +2. **Diffusionsprozess**: Ausgehend von zufälligem Rauschen verfeinert das Modell das Bild schrittweise, geleitet von deinem Text-Prompt +3. **CLIP-Anleitung**: Ein separates Modell (CLIP) hilft, deine Wörter mit visuellen Konzepten zu verbinden und stellt sicher, dass das Bild zu deiner Beschreibung passt + + + +**Prompting für Bilder ist anders:** +Anders als bei Text-Prompts, wo du Sätze schreibst, funktionieren Bild-Prompts oft besser als beschreibende Phrasen, getrennt durch Kommas: + + + +### Text-zu-Video-Modelle + +Text-zu-Video ist die neueste Grenze. Modelle wie Sora 2, Runway und Veo erstellen bewegte Bilder aus Textbeschreibungen. Wie bei Bildmodellen bestimmt die Qualität deines Prompts direkt die Qualität deiner Ausgabe – Prompt Engineering ist hier genauso entscheidend. + +**Wie sie funktionieren:** +1. **Zeitliches Verständnis**: Über Einzelbilder hinaus verstehen diese Modelle, wie sich Dinge im Laufe der Zeit bewegen und verändern +2. **Physiksimulation**: Sie lernen grundlegende Physik – wie Objekte fallen, wie Wasser fließt, wie Menschen gehen +3. **Frame-Konsistenz**: Sie halten Subjekte und Szenen über viele Frames hinweg konsistent +4. **Diffusion in der Zeit**: Ähnlich wie Bildmodelle, aber mit Erzeugung kohärenter Sequenzen statt einzelner Frames + + + + +Video-Prompts müssen Aktion über Zeit beschreiben, nicht nur eine statische Szene. Füge Verben und Bewegung hinzu: + + + + +### Spezialisierte Modelle +Feinabgestimmt für spezifische Aufgaben wie Code-Generierung (Codex, CodeLlama), Musikgenerierung (Suno, Udio) oder domänenspezifische Anwendungen wie medizinische Diagnose oder juristische Dokumentenanalyse. + +## Modellfähigkeiten und -grenzen + +Erkunde, was LLMs können und was nicht. Klicke auf jede Fähigkeit, um Beispiel-Prompts zu sehen: + + + +### Halluzinationen verstehen + + +Manchmal schreibt KI Dinge, die wahr klingen, aber nicht sind. Das nennt man „Halluzination". Es ist kein Fehler. Es ist einfach, wie Vorhersage funktioniert. Überprüfe wichtige Fakten immer doppelt. + + +Warum erfindet KI Dinge? + +1. Sie versucht, Text zu schreiben, der gut klingt, nicht Text, der immer wahr ist +2. Das Internet (wo sie gelernt hat) hat auch Fehler +3. Sie kann nicht wirklich prüfen, ob etwas real ist + + + +- **Frag nach Quellen**: Dann prüfe, ob diese Quellen real sind +- **Frag nach Schritt-für-Schritt-Denken**: So kannst du jeden Schritt prüfen +- **Überprüfe wichtige Fakten doppelt**: Nutze Google oder vertrauenswürdige Websites +- **Frag „Bist du sicher?"**: Die KI gibt möglicherweise Unsicherheit zu + + + + + +## Wie KI lernt: Die drei Schritte + +KI weiß nicht einfach magisch Dinge. Sie durchläuft drei Lernschritte, wie in der Schule: + +### Schritt 1: Vortraining (Lesen lernen) + +Stell dir vor, du liest jedes Buch, jede Website und jeden Artikel im Internet. Das passiert beim Vortraining. Die KI liest Milliarden von Wörtern und lernt Muster: + +- Wie Sätze aufgebaut sind +- Welche Wörter normalerweise zusammengehören +- Fakten über die Welt +- Verschiedene Schreibstile + +Das dauert Monate und kostet Millionen von Dollar. Nach diesem Schritt weiß die KI viel, aber sie ist noch nicht sehr hilfreich. Sie könnte einfach fortsetzen, was du schreibst, auch wenn das nicht das ist, was du wolltest. + + + +### Schritt 2: Feinabstimmung (Helfen lernen) + +Jetzt lernt die KI, ein guter Assistent zu sein. Trainer zeigen ihr Beispiele hilfreicher Gespräche: + +- „Wenn jemand eine Frage stellt, gib eine klare Antwort" +- „Wenn du gebeten wirst, etwas Schädliches zu tun, lehne höflich ab" +- „Sei ehrlich über das, was du nicht weißt" + +Stell es dir wie das Lehren guter Manieren vor. Die KI lernt den Unterschied zwischen bloßem Textvorhersagen und tatsächlich hilfreich sein. + + + +Probiere den obigen Prompt. Beachte, wie die KI ablehnt? Das ist die Feinabstimmung bei der Arbeit. + +### Schritt 3: RLHF (Lernen, was Menschen mögen) + +RLHF steht für „Reinforcement Learning from Human Feedback" (Verstärkungslernen aus menschlichem Feedback). Es ist eine schicke Art zu sagen: Menschen bewerten die Antworten der KI, und die KI lernt, bessere zu geben. + +So funktioniert es: +1. Die KI schreibt zwei verschiedene Antworten auf dieselbe Frage +2. Ein Mensch wählt, welche Antwort besser ist +3. Die KI lernt: „Okay, ich sollte mehr wie Antwort A schreiben" +4. Das passiert millionenfach + +Deshalb ist KI: +- Höflich und freundlich +- Gibt zu, wenn sie etwas nicht weiß +- Versucht, verschiedene Seiten eines Themas zu sehen +- Vermeidet kontroverse Aussagen + + +Diese drei Schritte zu kennen, hilft dir, das Verhalten der KI zu verstehen. Wenn KI eine Anfrage ablehnt, ist das Feinabstimmung. Wenn KI extra höflich ist, ist das RLHF. Wenn KI zufällige Fakten weiß, ist das Vortraining. + + +## Was das für deine Prompts bedeutet + +Jetzt, da du verstehst, wie KI funktioniert, hier, wie du dieses Wissen nutzen kannst: + +### 1. Sei klar und spezifisch + +KI sagt vorher, was als nächstes kommt, basierend auf deinen Worten. Vage Prompts führen zu vagen Antworten. Spezifische Prompts bekommen spezifische Ergebnisse. + + + + + +### 2. Gib Kontext + +KI weiß nichts über dich, es sei denn, du sagst es ihr. Jedes Gespräch beginnt neu. Füge die Hintergrundinformationen hinzu, die KI braucht. + + + + + +### 3. Arbeite mit der KI, nicht gegen sie + +Denk daran: KI wurde trainiert, hilfreich zu sein. Frag nach Dingen so, wie du einen hilfreichen Freund fragen würdest. + + + +### 4. Überprüfe wichtige Dinge immer doppelt + +KI klingt selbstbewusst, auch wenn sie falsch liegt. Bei allem Wichtigen verifiziere die Informationen selbst. + + + +### 5. Setze wichtige Dinge an den Anfang + +Wenn dein Prompt sehr lang ist, setze die wichtigsten Anweisungen an den Anfang. KI achtet mehr auf das, was zuerst kommt. + +## Die richtige KI auswählen + +Verschiedene KI-Modelle sind gut in verschiedenen Dingen: + +
+
+ Schnelle Fragen + Schnellere Modelle wie GPT-4o oder Claude 3.5 Sonnet +
+
+ Schwierige Probleme + Intelligentere Modelle wie GPT-5.2 oder Claude 4.5 Opus +
+
+ Code schreiben + Code-fokussierte Modelle oder die intelligentesten allgemeinen Modelle +
+
+ Lange Dokumente + Modelle mit großen Kontextfenstern (Claude, Gemini) +
+
+ Aktuelle Ereignisse + Modelle mit Internetzugang +
+
+ +## Zusammenfassung + +KI-Sprachmodelle sind Vorhersagemaschinen, die auf Text trainiert wurden. Sie sind erstaunlich in vielen Dingen, aber sie haben echte Grenzen. Der beste Weg, KI zu nutzen, ist zu verstehen, wie sie funktioniert, und Prompts zu schreiben, die ihre Stärken ausspielen. + + + + + +Im nächsten Kapitel lernen wir, was einen guten Prompt ausmacht und wie man Prompts schreibt, die großartige Ergebnisse liefern. diff --git a/src/content/book/de/02-anatomy-of-effective-prompt.mdx b/src/content/book/de/02-anatomy-of-effective-prompt.mdx new file mode 100644 index 00000000..41790fce --- /dev/null +++ b/src/content/book/de/02-anatomy-of-effective-prompt.mdx @@ -0,0 +1,343 @@ +Jeder großartige Prompt teilt gemeinsame strukturelle Elemente. Das Verstehen dieser Komponenten ermöglicht es dir, Prompts systematisch zu konstruieren, anstatt durch Versuch und Irrtum. + + +Denke an diese Komponenten wie LEGO-Steine. Du brauchst nicht alle für jeden Prompt, aber zu wissen, was verfügbar ist, hilft dir, genau das zu bauen, was du brauchst. + + +## Die Kernkomponenten + +Ein effektiver Prompt enthält typischerweise einige oder alle dieser Elemente: + + + +Lass uns jede Komponente im Detail untersuchen. + +## 1. Rolle / Persona + +Das Setzen einer Rolle fokussiert die Antworten des Modells durch die Linse einer spezifischen Expertise oder Perspektive. + + + +Die Rolle bereitet das Modell darauf vor: +- Angemessenes Vokabular zu verwenden +- Relevante Expertise anzuwenden +- Eine konsistente Perspektive beizubehalten +- Das Publikum angemessen zu berücksichtigen + +### Effektive Rollenmuster + +``` +"Du bist ein [Beruf] mit [X Jahren] Erfahrung in [Spezialgebiet]" +"Handle als ein [Rolle], der [Eigenschaft] ist" +"Du bist ein Experte für [Bereich], der einem [Publikumstyp] hilft" +``` + +## 2. Kontext / Hintergrund + +Kontext liefert die Informationen, die das Modell braucht, um deine Situation zu verstehen. Denk daran: Das Modell weiß nichts über dich, dein Projekt oder deine Ziele, es sei denn, du sagst es ihm. + + + +### Was in den Kontext gehört + +- **Projektdetails** — Technologie-Stack, Architektur, Einschränkungen +- **Aktueller Stand** — Was du versucht hast, was funktioniert, was nicht +- **Ziele** — Was du letztendlich erreichen willst +- **Einschränkungen** — Zeitlimits, technische Anforderungen, Stilrichtlinien + +## 3. Aufgabe / Anweisung + +Die Aufgabe ist das Herzstück deines Prompts – was du willst, dass das Modell tut. Sei spezifisch und eindeutig. + +### Das Spezifitätsspektrum + + + +### Handlungsverben, die gut funktionieren + +
+
+ Erstellung + Schreibe, Erstelle, Generiere, Verfasse, Entwirf +
+
+ Analyse + Analysiere, Bewerte, Vergleiche, Beurteile, Überprüfe +
+
+ Transformation + Konvertiere, Übersetze, Formatiere um, Fasse zusammen, Erweitere +
+
+ Erklärung + Erkläre, Beschreibe, Kläre, Definiere, Veranschauliche +
+
+ Problemlösung + Löse, Debugge, Behebe, Optimiere, Verbessere +
+
+ +## 4. Einschränkungen / Regeln + +Einschränkungen begrenzen die Ausgabe des Modells. Sie verhindern häufige Probleme und stellen Relevanz sicher. + +### Arten von Einschränkungen + +**Längeneinschränkungen:** +``` +"Halte deine Antwort unter 200 Wörtern" +"Gib genau 5 Vorschläge" +"Schreibe 3-4 Absätze" +``` + +**Inhaltseinschränkungen:** +``` +"Füge keine Code-Beispiele hinzu" +"Konzentriere dich nur auf die technischen Aspekte" +"Vermeide Marketingsprache" +``` + +**Stileinschränkungen:** +``` +"Verwende einen formellen, akademischen Ton" +"Schreibe, als würdest du mit einem 10-Jährigen sprechen" +"Sei direkt und vermeide ausweichende Sprache" +``` + +**Bereichseinschränkungen:** +``` +"Berücksichtige nur Optionen, die in Python 3.10+ verfügbar sind" +"Beschränke Vorschläge auf kostenlose Tools" +"Konzentriere dich auf Lösungen, die keine zusätzlichen Abhängigkeiten erfordern" +``` + +## 5. Ausgabeformat + +Das Spezifizieren des Ausgabeformats stellt sicher, dass du Antworten in einer nutzbaren Struktur erhältst. + +### Gängige Formate + +**Listen:** +``` +"Gib als Aufzählungsliste zurück" +"Liefere eine nummerierte Liste von Schritten" +``` + +**Strukturierte Daten:** +``` +"Gib als JSON mit Schlüsseln zurück: title, description, priority" +"Formatiere als Markdown-Tabelle mit Spalten: Feature, Vorteile, Nachteile" +``` + +**Spezifische Strukturen:** +``` +"Strukturiere deine Antwort als: + ## Zusammenfassung + ## Kernpunkte + ## Empfehlungen" +``` + +### JSON-Ausgabebeispiel + +``` +Analysiere diese Kundenbewertung und gib JSON zurück: +{ + "sentiment": "positive" | "negative" | "neutral", + "topics": ["Array der Hauptthemen"], + "rating_prediction": 1-5, + "key_phrases": ["bemerkenswerte Phrasen"] +} + +Bewertung: "Das Produkt kam schnell an und funktioniert super, aber +die Anleitung war verwirrend." +``` + +## 6. Beispiele (Few-Shot-Learning) + +Beispiele sind der mächtigste Weg, dem Modell genau zu zeigen, was du willst. + +### One-Shot-Beispiel + +``` +Wandle diese Sätze in die Vergangenheitsform um. + +Beispiel: +Eingabe: "Sie geht zum Laden" +Ausgabe: "Sie ging zum Laden" + +Jetzt umwandeln: +Eingabe: "Sie laufen jeden Morgen" +``` + +### Few-Shot-Beispiel + +``` +Klassifiziere diese Support-Tickets nach Dringlichkeit. + +Beispiele: +"Mein Konto wurde gehackt" → Kritisch +"Wie ändere ich mein Passwort?" → Niedrig +"Zahlung fehlgeschlagen, aber ich wurde belastet" → Hoch + +Klassifiziere: "Die App stürzt ab, wenn ich die Einstellungen öffne" +``` + +## Alles zusammenfügen + +Hier ist ein vollständiger Prompt mit allen Komponenten: + + + +## Der minimal effektive Prompt + +Nicht jeder Prompt braucht alle Komponenten. Für einfache Aufgaben kann eine klare Anweisung ausreichen: + +``` +Übersetze "Hallo, wie geht es dir?" ins Englische. +``` + +Verwende zusätzliche Komponenten, wenn: +- Die Aufgabe komplex oder mehrdeutig ist +- Du spezifische Formatierung brauchst +- Ergebnisse nicht den Erwartungen entsprechen +- Konsistenz über mehrere Abfragen hinweg wichtig ist + +## Häufige Prompt-Muster + +Diese Frameworks geben dir eine einfache Checkliste, der du beim Schreiben von Prompts folgen kannst. Klicke auf jeden Schritt, um ein Beispiel zu sehen. + + + + + +## Zusammenfassung + +Effektive Prompts werden konstruiert, nicht entdeckt. Durch das Verstehen und Anwenden dieser strukturellen Komponenten kannst du: + +- Beim ersten Versuch bessere Ergebnisse erzielen +- Prompts debuggen, die nicht funktionieren +- Wiederverwendbare Prompt-Vorlagen erstellen +- Deine Absichten klar kommunizieren + + + + + +## Baue deinen eigenen Prompt + +Jetzt bist du dran! Verwende diesen interaktiven Prompt-Builder, um deinen eigenen Prompt mit den Komponenten zu konstruieren, die du gelernt hast: + + + + + +Im nächsten Kapitel werden wir die Kernprinzipien erkunden, die Prompt-Konstruktionsentscheidungen leiten. diff --git a/src/content/book/de/03-core-prompting-principles.mdx b/src/content/book/de/03-core-prompting-principles.mdx new file mode 100644 index 00000000..e7a2313f --- /dev/null +++ b/src/content/book/de/03-core-prompting-principles.mdx @@ -0,0 +1,373 @@ +Über die Struktur hinaus wird effektives Prompt Engineering von Prinzipien geleitet – grundlegenden Wahrheiten, die über Modelle, Aufgaben und Kontexte hinweg gelten. Beherrsche diese Prinzipien, und du wirst dich an jede Prompting-Herausforderung anpassen können. + + +Diese Prinzipien gelten für jedes KI-Modell und jede Aufgabe. Lerne sie einmal, nutze sie überall. + + +## Prinzip 1: Klarheit vor Cleverness + +Die besten Prompts sind klar, nicht clever. KI-Modelle sind wörtliche Interpreten – sie arbeiten mit genau dem, was du ihnen gibst. + +### Sei explizit + + + +### Vermeide Mehrdeutigkeit + +Wörter können mehrere Bedeutungen haben. Wähle präzise Sprache. + + + +### Nenne das Offensichtliche + +Was für dich offensichtlich ist, ist nicht offensichtlich für das Modell. Buchstabiere Annahmen aus. + +``` +Du hilfst mir, ein Anschreiben zu schreiben. + +Wichtiger Kontext: +- Ich bewerbe mich für eine Position als Software Engineer bei Google +- Ich habe 5 Jahre Erfahrung in Python und verteilten Systemen +- Die Rolle erfordert Führungserfahrung (ich habe ein Team von 4 Personen geleitet) +- Ich möchte meine Open-Source-Beiträge betonen +``` + +## Prinzip 2: Spezifität liefert Qualität + +Vage Eingaben produzieren vage Ausgaben. Spezifische Eingaben produzieren spezifische, nützliche Ausgaben. + +### Die Spezifitätsleiter + + + +Jede Stufe fügt Spezifität hinzu und verbessert die Ausgabequalität dramatisch. + +### Spezifiziere diese Elemente + +
+
+ Publikum + Wer wird das lesen/nutzen? +
+
+ Länge + Wie lang/kurz sollte es sein? +
+
+ Ton + Formell? Locker? Technisch? +
+
+ Format + Prosa? Liste? Tabelle? Code? +
+
+ Umfang + Was einschließen/ausschließen? +
+
+ Zweck + Was soll das erreichen? +
+
+ +## Prinzip 3: Kontext ist König + +Modelle haben kein Gedächtnis, keinen Zugriff auf deine Dateien und kein Wissen über deine Situation. Alles Relevante muss im Prompt sein. + +### Liefere ausreichend Kontext + + + +### Die Kontext-Checkliste + + +Frag dich: Würde ein kluger Fremder diese Anfrage verstehen? Wenn nicht, füge mehr Kontext hinzu. + + + + +## Prinzip 4: Leite an, frag nicht nur + +Frag nicht nur nach einer Antwort – leite das Modell zur gewünschten Antwort. + +### Verwende instruktive Rahmung + + + +### Liefere Denkgerüste + +Für komplexe Aufgaben, leite den Denkprozess: + + + +## Prinzip 5: Iterieren und Verfeinern + +Prompt Engineering ist ein iterativer Prozess. Dein erster Prompt ist selten dein bester. + +### Der Iterationszyklus + +``` +1. Schreibe initialen Prompt +2. Überprüfe Ausgabe +3. Identifiziere Lücken oder Probleme +4. Verfeinere Prompt +5. Wiederhole bis zufrieden +``` + +### Häufige Verfeinerungen + +
+
+ Zu ausführlich + Füge „Sei prägnant" oder Längenlimits hinzu +
+
+ Zu vage + Füge spezifische Beispiele oder Einschränkungen hinzu +
+
+ Falsches Format + Spezifiziere genaue Ausgabestruktur +
+
+ Fehlende Aspekte + Füge „Stelle sicher, dass du einschließt..." hinzu +
+
+ Falscher Ton + Spezifiziere Publikum und Stil +
+
+ Ungenau + Fordere Zitate oder Schritt-für-Schritt-Begründung an +
+
+ +### Führe ein Prompt-Tagebuch + +Dokumentiere, was funktioniert: +``` +Aufgabe: Code-Review +Version 1: „Überprüfe diesen Code" → Zu generisch +Version 2: Spezifische Review-Kriterien hinzugefügt → Besser +Version 3: Beispiel eines guten Reviews hinzugefügt → Ausgezeichnet +Final: [Erfolgreichen Prompt als Vorlage speichern] +``` + +## Prinzip 6: Nutze die Stärken des Modells + +Arbeite mit der Art, wie Modelle trainiert wurden, nicht dagegen. + +### Modelle wollen hilfreich sein + +Rahme Anfragen als Dinge, die ein hilfreicher Assistent natürlich tun würde: + + + +### Modelle sind gut in Mustern + +Wenn du konsistente Ausgabe brauchst, zeige das Muster: + + + +### Modelle können Rollen spielen + +Verwende Personas, um verschiedene „Modi" der Antwort zu aktivieren: + +``` +Als Advocatus Diaboli, argumentiere gegen meinen Vorschlag... +Als unterstützender Mentor, hilf mir zu verbessern... +Als skeptischer Investor, hinterfrage diesen Businessplan... +``` + +## Prinzip 7: Kontrolliere die Ausgabestruktur + +Strukturierte Ausgaben sind nützlicher als Freitext. + +### Fordere spezifische Formate an + +``` +Gib deine Analyse zurück als: + +ZUSAMMENFASSUNG: [1 Satz] + +SCHLÜSSELERKENNTNISSE: +• [Erkenntnis 1] +• [Erkenntnis 2] +• [Erkenntnis 3] + +EMPFEHLUNG: [1-2 Sätze] + +KONFIDENZ: [Niedrig/Mittel/Hoch] weil [Grund] +``` + +### Verwende Trennzeichen + +Trenne Abschnitte deines Prompts klar: + +``` +### KONTEXT ### +[Dein Kontext hier] + +### AUFGABE ### +[Deine Aufgabe hier] + +### FORMAT ### +[Gewünschtes Format hier] +``` + +### Fordere maschinenlesbare Ausgabe an + +Für programmatische Nutzung: + +``` +Gib nur gültiges JSON zurück, keine Erklärung: +{ + "decision": "approve" | "reject" | "review", + "confidence": 0.0-1.0, + "reasons": ["string array"] +} +``` + +## Prinzip 8: Verifizieren und Validieren + +Vertraue Modellausgaben nie blind, besonders bei wichtigen Aufgaben. + +### Frag nach Begründung + +``` +Löse dieses Problem und zeige deine Arbeit Schritt für Schritt. +Nach dem Lösen, verifiziere deine Antwort durch [Prüfmethode]. +``` + +### Fordere mehrere Perspektiven an + +``` +Gib mir drei verschiedene Ansätze, um dieses Problem zu lösen. +Erkläre für jeden die Kompromisse. +``` + +### Baue Selbstprüfung ein + +``` +Nach dem Generieren des Codes, überprüfe ihn auf: +- Syntaxfehler +- Randfälle +- Sicherheitslücken +Liste alle gefundenen Probleme auf. +``` + +## Zusammenfassung: Die Prinzipien auf einen Blick + + + + + +## Übung: Fülle die Lücken + +Teste dein Verständnis der Kernprinzipien, indem du diese Prompt-Vorlage vervollständigst: + + + + + +Diese Prinzipien bilden das Fundament für alles, was folgt. In Teil II werden wir sie auf spezifische Techniken anwenden, die die Prompt-Effektivität dramatisch verbessern. diff --git a/src/content/book/de/04-role-based-prompting.mdx b/src/content/book/de/04-role-based-prompting.mdx new file mode 100644 index 00000000..97ee705e --- /dev/null +++ b/src/content/book/de/04-role-based-prompting.mdx @@ -0,0 +1,328 @@ +Rollenbasiertes Prompting ist eine der mächtigsten und am weitesten verbreiteten Techniken im Prompt Engineering. Indem du der KI eine spezifische Rolle oder Persona zuweist, kannst du die Qualität, den Stil und die Relevanz der Antworten dramatisch beeinflussen. + + +Denke an Rollen als Filter für das umfangreiche Wissen der KI. Die richtige Rolle fokussiert Antworten wie eine Linse Licht fokussiert. + + +## Warum Rollen funktionieren + +Wenn du eine Rolle zuweist, sagst du dem Modell im Wesentlichen: „Filtere dein umfangreiches Wissen durch diese spezifische Linse." Das Modell passt an: + +- **Vokabular**: Verwendung von rollengerechter Terminologie +- **Perspektive**: Betrachtung von Problemen aus diesem Blickwinkel +- **Expertise-Tiefe**: Bereitstellung rollengerechter Detailstufen +- **Kommunikationsstil**: Anpassung an die Kommunikationsweise der Rolle + +### Die technische Erklärung + +LLMs funktionieren, indem sie das wahrscheinlichste nächste Token basierend auf dem gegebenen Kontext vorhersagen. Wenn du eine Rolle spezifizierst, änderst du grundlegend, was „wahrscheinlich" bedeutet. + +**Aktivierung relevanten Wissens**: Die Rolle aktiviert spezifische Bereiche der gelernten Assoziationen des Modells. „Du bist ein Arzt" zu sagen aktiviert medizinische Terminologie, diagnostische Denkmuster und klinische Kommunikationsstile aus den Trainingsdaten. + +**Statistische Konditionierung**: LLMs haben aus Millionen von Dokumenten gelernt, die von echten Experten geschrieben wurden. Wenn du eine Rolle zuweist, konditioniert das Modell seine Wahrscheinlichkeitsverteilungen, um Muster zu entsprechen, die es von diesem Autorentyp gesehen hat. + +**Reduzierung von Mehrdeutigkeit**: Ohne eine Rolle mittelt das Modell über alle möglichen Antwortenden. Mit einer Rolle verengt es sich auf eine spezifische Teilmenge, was Antworten fokussierter und konsistenter macht. + +**Kontext-Verankerung**: Die Rolle schafft einen dauerhaften Kontextanker während des gesamten Gesprächs. Jede nachfolgende Antwort wird von dieser initialen Rahmung beeinflusst. + +Stell es dir so vor: Wenn du fragst „Was soll ich wegen diesem Husten tun?", könnte das Modell als Arzt, Freund, Apotheker oder besorgter Elternteil antworten. Jeder würde unterschiedliche Ratschläge geben. Indem du die Rolle vorher spezifizierst, sagst du dem Modell, welche „Stimme" es aus seinen Trainingsdaten verwenden soll. + + +Das Modell spielt nicht Theater oder tut so. Es verzerrt seine Ausgaben statistisch in Richtung Muster, die es während des Trainings von echten Experten, Fachleuten und Spezialisten gelernt hat. Eine „Arzt"-Rolle aktiviert medizinische Wissenspfade; eine „Dichter"-Rolle aktiviert literarische Muster. + + +## Grundlegende Rollenmuster + +Diese grundlegenden Muster funktionieren für die meisten Anwendungsfälle. Beginne mit diesen Vorlagen und passe sie an deine Bedürfnisse an. + +### Das Experten-Muster + +Das vielseitigste Muster. Spezifiziere das Fachgebiet und die Jahre an Erfahrung, um autoritative, tiefgehende Antworten zu bekommen. Funktioniert gut für technische Fragen, Analysen und professionelle Beratung. + + + +### Das Berufs-Muster + +Verankere die Rolle in einem realen Kontext, indem du eine Berufsbezeichnung und Organisationstyp spezifizierst. Dies fügt institutionelles Wissen und professionelle Normen zur Antwort hinzu. + + + +### Das Lehrer-Muster + +Perfekt zum Lernen und Erklären. Die Spezifikation des Publikumsniveaus stellt sicher, dass die Antwort zum Hintergrund des Lernenden passt, von Anfängern bis zu fortgeschrittenen Praktikern. + + + +## Fortgeschrittene Rollenkonstruktionen + +### Kombinierte Rollen + +Kombiniere mehrere Identitäten, um Antworten zu bekommen, die verschiedene Perspektiven vermischen. Diese Kinderarzt-Eltern-Kombination produziert Ratschläge, die sowohl medizinisch fundiert als auch praktisch erprobt sind. + + + +### Situative Rollen + +Platziere die Rolle in einem spezifischen Szenario, um sowohl Inhalt als auch Ton zu formen. Hier macht der Code-Review-Kontext die KI konstruktiv und lehrreich statt nur kritisch. + + + +### Perspektiv-Rollen + +Hole Feedback aus der Sicht eines bestimmten Stakeholders. Eine VC-Perspektive bewertet Tragfähigkeit und Skalierbarkeit anders als ein Kunde oder Ingenieur. + + + +## Rollenkategorien und Beispiele + +Verschiedene Bereiche profitieren von verschiedenen Rollentypen. Hier sind bewährte Beispiele nach Kategorie organisiert, die du für deine Aufgaben anpassen kannst. + +### Technische Rollen + +**Software-Architekt**: Am besten für Systemdesign-Entscheidungen, Technologiewahl und architektonische Kompromisse. Der Fokus auf Wartbarkeit lenkt Antworten zu praktischen, langfristigen Lösungen. + + + +**Sicherheitsspezialist**: Die Angreifer-Denkweise ist hier der Schlüssel. Diese Rolle produziert bedrohungsfokussierte Analysen, die Schwachstellen identifizieren, die eine rein defensive Perspektive übersehen könnte. + + + +**DevOps-Engineer**: Ideal für Deployment-, Automatisierungs- und Infrastrukturfragen. Der Schwerpunkt auf Zuverlässigkeit stellt produktionsreife Empfehlungen sicher. + + + +### Kreative Rollen + +**Werbetexter**: Der „preisgekrönte" Qualifier und der Conversion-Fokus produzieren prägnante, überzeugende Texte statt generischem Marketingtext. + + + +**Drehbuchautor**: Aktiviert Wissen über dramatische Struktur, Pacing und Dialogkonventionen. Großartig für jedes narrative Schreiben, das Spannung und Charakterstimme braucht. + + + +**UX-Writer**: Eine spezialisierte Rolle für Interface-Texte. Der Fokus auf Kürze und Benutzerführung produziert prägnante, handlungsorientierte Texte. + + + +### Analytische Rollen + +**Business-Analyst**: Überbrückt die Lücke zwischen technischen und nicht-technischen Stakeholdern. Nützlich für Anforderungserfassung, Spezifikationsschreiben und Identifizierung von Lücken in Projektplänen. + + + +**Forschungswissenschaftler**: Der Schwerpunkt auf Evidenz und Unsicherheitsanerkennung produziert ausgewogene, gut belegte Antworten, die Fakten von Spekulationen unterscheiden. + + + +**Finanzanalyst**: Kombiniert quantitative Analyse mit Risikobewertung. Der doppelte Fokus auf Renditen und Risiko produziert ausgewogenere Investitionsperspektiven. + + + +### Pädagogische Rollen + +**Sokratischer Tutor**: Statt Antworten zu geben, stellt diese Rolle leitende Fragen. Ausgezeichnet für tieferes Lernen und um Schülern zu helfen, kritisches Denken zu entwickeln. + + + +**Instruktionsdesigner**: Strukturiert Lernen für maximale Behaltensleistung. Nutze diese Rolle, wenn du komplexe Themen in lehrbare Häppchen mit klarer Progression aufteilen musst. + + + +## Die Rollen-Stack-Technik + +Für komplexe Aufgaben kombiniere mehrere Rollenaspekte in einer einzigen, geschichteten Identität. Diese Technik stapelt Expertise, Publikumsbewusstsein und Stilrichtlinien, um hochspezialisierte Antworten zu erstellen. + +Dieses Beispiel schichtet drei Elemente: Domänenexpertise (API-Dokumentation), Publikum (Junior-Entwickler) und Stilrichtlinie (Googles Konventionen). Jede Schicht schränkt die Ausgabe weiter ein. + + + +## Rollen für verschiedene Aufgaben + +
+
+ Code-Review + Senior-Entwickler + Mentor +
+
+ Schreib-Feedback + Lektor + Zielgruppen-Mitglied +
+
+ Geschäftsstrategie + Berater + Branchenexperte +
+
+ Neues Thema lernen + Geduldiger Lehrer + Praktiker +
+
+ Kreatives Schreiben + Spezifischer Genre-Autor +
+
+ Technische Erklärung + Experte + Kommunikator +
+
+ Problemlösung + Domänenspezialist + Generalist +
+
+ +## Anti-Muster, die zu vermeiden sind + +### Zu generische Rollen + + + +### Widersprüchliche Rollen + + + +### Unrealistische Expertise + + + +## Praxisbeispiele + +### Technische Dokumentation + + + +### Kreatives Schreiben + + + +### Geschäftskommunikation + + + +## Rollen mit anderen Techniken kombinieren + +Rollen funktionieren noch besser, wenn sie mit anderen Prompting-Techniken kombiniert werden: + +### Rolle + Few-Shot + +Kombiniere eine Rolle mit einem Beispiel, um genau zu zeigen, wie die Rolle antworten soll. Das Beispiel lehrt Ton und Format, während die Rolle Kontext und Expertise liefert. + + + +### Rolle + Chain of Thought + +Die Detektiv-Rolle ermutigt natürlich zu schrittweisem Denken. Die Kombination von Rollen mit Chain-of-Thought produziert transparentere, überprüfbare Problemlösung. + + + +## Zusammenfassung + + +Rollenbasiertes Prompting ist mächtig, weil es das umfangreiche Wissen des Modells fokussiert, Erwartungen für Ton und Stil setzt, impliziten Kontext liefert und Ausgaben konsistenter macht. + + + + +Der Schlüssel ist **Spezifität**: Je detaillierter und realistischer die Rolle, desto besser die Ergebnisse. Im nächsten Kapitel werden wir erkunden, wie man konsistente, strukturierte Ausgaben aus seinen Prompts bekommt. diff --git a/src/content/book/de/05-structured-output.mdx b/src/content/book/de/05-structured-output.mdx new file mode 100644 index 00000000..0145276f --- /dev/null +++ b/src/content/book/de/05-structured-output.mdx @@ -0,0 +1,411 @@ +Konsistente, gut formatierte Ausgaben zu bekommen ist essenziell für Produktionsanwendungen und effiziente Workflows. Dieses Kapitel behandelt Techniken zur genauen Kontrolle, wie KI-Modelle ihre Antworten formatieren. + + +Strukturierte Ausgabe transformiert KI-Antworten von Freitext in handlungsfähige, parsierbare Daten. + + +## Warum Struktur wichtig ist + + + +## Grundlegende Formatierungstechniken + +### Listen + +Listen sind perfekt für Schritt-für-Schritt-Anleitungen, Ranglisten oder Sammlungen verwandter Punkte. Sie sind leicht zu scannen und zu parsen. Verwende **nummerierte Listen**, wenn die Reihenfolge wichtig ist (Schritte, Rankings), und **Aufzählungspunkte** für ungeordnete Sammlungen. + + + + +Spezifiziere die genaue Anzahl der gewünschten Elemente, ob Erklärungen enthalten sein sollen und ob Elemente fett oder mit einer bestimmten Struktur sein sollen. + + +### Tabellen + +Tabellen sind hervorragend zum Vergleichen mehrerer Elemente über dieselben Dimensionen. Sie sind ideal für Feature-Vergleiche, Datenzusammenfassungen und alle Informationen mit konsistenten Attributen. Definiere deine Spaltenüberschriften immer explizit. + + + + +Spezifiziere Spaltennamen, erwartete Datentypen (Text, Zahlen, Bewertungen) und wie viele Zeilen du brauchst. Für komplexe Vergleiche beschränke dich auf 4-6 Spalten für Lesbarkeit. + + +### Überschriften und Abschnitte + +Überschriften schaffen eine klare Dokumentstruktur, machen lange Antworten scannbar und organisiert. Verwende sie für Berichte, Analysen oder jede mehrteilige Antwort. Hierarchische Überschriften (##, ###) zeigen Beziehungen zwischen Abschnitten. + +``` +Analysiere diesen Geschäftsvorschlag. + +Strukturiere deine Antwort mit diesen Abschnitten: +## Zusammenfassung +## Stärken +## Schwächen +## Empfehlungen +## Risikobewertung +``` + + +Liste deine Abschnitte in der gewünschten Reihenfolge auf. Für Konsistenz spezifiziere, was jeder Abschnitt enthalten soll (z.B. „Zusammenfassung: nur 2-3 Sätze"). + + +### Betonung mit Großbuchstaben-Direktiven + +Großbuchstaben-Wörter wirken als starke Signale an das Modell und betonen kritische Einschränkungen oder Anforderungen. Verwende sie sparsam für maximale Wirkung – Übernutzung verwässert ihre Effektivität. + +**Häufige Großbuchstaben-Direktiven:** + + + +``` +Fasse diesen Artikel zusammen. + +WICHTIG: Halte die Zusammenfassung unter 100 Wörtern. +NIEMALS Informationen hinzufügen, die nicht im Original vorhanden sind. +IMMER den ursprünglichen Ton und die Perspektive beibehalten. +Eigene Meinungen oder Analysen NICHT einschließen. +``` + + +Wenn alles großgeschrieben oder als kritisch markiert ist, sticht nichts hervor. Reserviere diese Direktiven für wirklich wichtige Einschränkungen. + + +## JSON-Ausgabe + +JSON (JavaScript Object Notation) ist das beliebteste Format für strukturierte KI-Ausgaben. Es ist maschinenlesbar, von Programmiersprachen weit unterstützt und perfekt für APIs, Datenbanken und Automatisierungs-Workflows. Der Schlüssel zu zuverlässigem JSON ist die Bereitstellung eines klaren Schemas. + +### Grundlegende JSON-Anfrage + +Beginne mit einer Vorlage, die die genaue gewünschte Struktur zeigt. Füge Feldnamen, Datentypen und Beispielwerte hinzu. Dies fungiert als Vertrag, dem das Modell folgen wird. + + + +### Komplexe JSON-Strukturen + +Für verschachtelte Daten verwende hierarchisches JSON mit Objekten in Objekten, Arrays von Objekten und gemischten Typen. Definiere jede Ebene klar und verwende TypeScript-Stil-Annotationen (`"positive" | "negative"`), um Werte einzuschränken. + +``` +Analysiere diese Produktbewertung und gib JSON zurück: + +{ + "review_id": "string (generiere eindeutig)", + "sentiment": { + "overall": "positive" | "negative" | "mixed" | "neutral", + "score": 0.0-1.0 + }, + "aspects": [ + { + "aspect": "string (z.B. 'Preis', 'Qualität')", + "sentiment": "positive" | "negative" | "neutral", + "mentions": ["exakte Zitate aus der Bewertung"] + } + ], + "purchase_intent": { + "would_recommend": boolean, + "confidence": 0.0-1.0 + }, + "key_phrases": ["String-Array bemerkenswerter Phrasen"] +} + +Gib NUR gültiges JSON zurück, keinen zusätzlichen Text. + +Bewertung: "[Bewertungstext]" +``` + +### Gültiges JSON sicherstellen + +Modelle fügen manchmal erklärenden Text oder Markdown-Formatierung um JSON hinzu. Verhindere dies mit expliziten Anweisungen zum Ausgabeformat. Du kannst rohes JSON oder JSON in Code-Blöcken anfordern – wähle basierend auf deinen Parsing-Bedürfnissen. + +Füge explizite Anweisungen hinzu: + +``` +WICHTIG: +- Gib NUR das JSON-Objekt zurück, keine Markdown-Code-Blöcke +- Stelle sicher, dass alle Strings korrekt escaped sind +- Verwende null für fehlende Werte, nicht undefined +- Validiere, dass die Ausgabe parsebares JSON ist +``` + +Oder fordere Code-Blöcke an, indem du das Modell bittest, seine Ausgabe zu wrappen: + +```` +Gib das Ergebnis als JSON-Code-Block zurück: +```json +{ ... } +``` +```` + +## YAML-Ausgabe + +YAML ist menschenlesbarer als JSON und verwendet Einrückung statt Klammern. Es ist der Standard für Konfigurationsdateien (Docker, Kubernetes, GitHub Actions) und funktioniert gut, wenn die Ausgabe von Menschen gelesen oder in DevOps-Kontexten verwendet wird. YAML ist empfindlich bei Einrückung, also sei spezifisch über Formatierungsanforderungen. + + + +## XML-Ausgabe + +XML wird immer noch für viele Enterprise-Systeme, SOAP-APIs und Legacy-Integrationen benötigt. Es ist ausführlicher als JSON, bietet aber Features wie Attribute, Namespaces und CDATA-Abschnitte für komplexe Daten. Spezifiziere Elementnamen, Verschachtelungsstruktur und wo Attribute vs. Kindelemente verwendet werden sollen. + +``` +Konvertiere diese Daten ins XML-Format: + +Anforderungen: +- Wurzelelement: +- Jedes Element in -Element +- Füge Attribute ein, wo angemessen +- Verwende CDATA für Beschreibungstext + +Daten: [Buchdaten] +``` + +## Benutzerdefinierte Formate + +Manchmal passen Standardformate nicht zu deinen Bedürfnissen. Du kannst jedes benutzerdefinierte Format definieren, indem du eine klare Vorlage bereitstellst. Benutzerdefinierte Formate funktionieren gut für Berichte, Logs oder domänenspezifische Ausgaben, die von Menschen gelesen werden. + +### Strukturiertes Analyseformat + +Verwende Trennzeichen (===, ---, [ABSCHNITT]), um scannbare Dokumente mit klaren Grenzen zwischen Abschnitten zu erstellen. Dieses Format ist großartig für Code-Reviews, Audits und Analysen. + +``` +Analysiere diesen Code mit diesem exakten Format: + +=== CODE-ANALYSE === + +[ZUSAMMENFASSUNG] +Ein Absatz Überblick + +[PROBLEME] +• KRITISCH: [Problem] — [Datei:Zeile] +• WARNUNG: [Problem] — [Datei:Zeile] +• INFO: [Problem] — [Datei:Zeile] + +[METRIKEN] +Komplexität: [Niedrig/Mittel/Hoch] +Wartbarkeit: [Punktzahl]/10 +Testabdeckung: [geschätzt %] + +[EMPFEHLUNGEN] +1. [Priorität 1 Empfehlung] +2. [Priorität 2 Empfehlung] + +=== ENDE ANALYSE === +``` + +### Lückentext-Format + +Vorlagen mit Lücken (___) leiten das Modell an, spezifische Felder auszufüllen, während die exakte Formatierung beibehalten wird. Dieser Ansatz ist ausgezeichnet für Formulare, Briefs und standardisierte Dokumente, bei denen Konsistenz wichtig ist. + +``` +Vervollständige diese Vorlage für das gegebene Produkt: + +PRODUKT-BRIEF +───────────── +Name: _______________ +Slogan: _______________ +Zielnutzer: _______________ +Gelöstes Problem: _______________ +Schlüsselfeatures: + 1. _______________ + 2. _______________ + 3. _______________ +Differenzierungsmerkmal: _______________ + +Produkt: [Produktbeschreibung] +``` + +## Typisierte Antworten + +Typisierte Antworten definieren Kategorien oder Entitätstypen, die das Modell erkennen und beschriften soll. Diese Technik ist essenziell für Named Entity Recognition (NER), Klassifikationsaufgaben und jede Extraktion, bei der du Informationen konsistent kategorisieren musst. Definiere deine Typen klar mit Beispielen. + + + +## Mehrteilige strukturierte Antworten + +Wenn du umfassende Ausgaben brauchst, die mehrere Aspekte abdecken, definiere unterschiedliche Teile mit klaren Grenzen. Spezifiziere genau, was in jeden Teil gehört – Format, Länge und Inhaltstyp. Dies verhindert, dass das Modell Abschnitte vermischt oder weglässt. + +``` +Recherchiere dieses Thema und liefere: + +### TEIL 1: ZUSAMMENFASSUNG +[2-3 Sätze Überblick] + +### TEIL 2: SCHLÜSSELERKENNTNISSE +[Genau 5 Stichpunkte] + +### TEIL 3: DATENTABELLE +| Metrik | Wert | Quelle | +|--------|------|--------| +[Mindestens 5 Zeilen einschließen] + +### TEIL 4: EMPFEHLUNGEN +[Nummerierte Liste von 3 umsetzbaren Empfehlungen] + +### TEIL 5: WEITERFÜHRENDE LEKTÜRE +[3 vorgeschlagene Ressourcen mit kurzen Beschreibungen] +``` + +## Bedingte Formatierung + +Bedingte Formatierung ermöglicht dir, verschiedene Ausgabeformate basierend auf den Eigenschaften der Eingabe zu definieren. Dies ist mächtig für Klassifikation, Triage und Routing-Systeme, bei denen das Antwortformat je nach dem variieren sollte, was das Modell erkennt. Verwende klare wenn/dann-Logik mit expliziten Ausgabevorlagen für jeden Fall. + + + +## Arrays und Listen in JSON + +Das Extrahieren mehrerer Elemente in Arrays erfordert sorgfältige Schema-Definition. Spezifiziere die Array-Struktur, was jedes Element enthalten soll und wie Randfälle behandelt werden (leere Arrays, einzelne Elemente). Ein Zählfeld hilft, Vollständigkeit zu verifizieren. + +``` +Extrahiere alle Aktionspunkte aus diesem Meeting-Protokoll. + +Gib als JSON-Array zurück: +{ + "action_items": [ + { + "task": "String, der die Aufgabe beschreibt", + "assignee": "Personenname oder 'Nicht zugewiesen'", + "deadline": "Datum wenn erwähnt, sonst null", + "priority": "high" | "medium" | "low", + "context": "relevantes Zitat aus dem Protokoll" + } + ], + "total_count": number +} + +Protokoll: "[Meeting-Protokoll]" +``` + +## Validierungsanweisungen + +Selbstvalidierung fordert das Modell auf, seine eigene Ausgabe vor dem Antworten zu prüfen. Dies fängt häufige Probleme wie fehlende Abschnitte, Platzhaltertext oder Constraint-Verletzungen ab. Das Modell wird intern iterieren, um Probleme zu beheben, was die Ausgabequalität ohne zusätzliche API-Aufrufe verbessert. + +``` +Generiere den Bericht, dann: + +VALIDIERUNGS-CHECKLISTE: +□ Alle erforderlichen Abschnitte vorhanden +□ Kein Platzhaltertext verbleibend +□ Alle Statistiken enthalten Quellen +□ Wortanzahl innerhalb von 500-700 Wörtern +□ Fazit bezieht sich zurück auf Einleitung + +Wenn eine Prüfung fehlschlägt, vor dem Antworten beheben. +``` + +## Umgang mit optionalen Feldern + +Reale Daten haben oft fehlende Werte. Weise das Modell explizit an, wie optionale Felder behandelt werden sollen – die Verwendung von `null` ist sauberer als leere Strings und einfacher programmatisch zu verarbeiten. Verhindere auch „Halluzination" fehlender Daten, indem du betonst, dass das Modell niemals Informationen erfinden soll. + +``` +Extrahiere Kontaktinformationen. Verwende null für fehlende Felder. + +{ + "name": "string (erforderlich)", + "email": "string oder null", + "phone": "string oder null", + "company": "string oder null", + "role": "string oder null", + "linkedin": "URL-String oder null" +} + +WICHTIG: +- Niemals Informationen erfinden, die nicht in der Quelle sind +- Verwende null, nicht leere Strings, für fehlende Daten +- Telefonnummern im E.164-Format wenn möglich +``` + +## Zusammenfassung + + +Sei explizit über das Format, verwende Beispiele, spezifiziere Typen, behandle Randfälle mit null-Werten und bitte das Modell, seine eigene Ausgabe zu validieren. + + + + +Strukturierte Ausgaben sind essenziell für den Aufbau zuverlässiger KI-gestützter Anwendungen. Im nächsten Kapitel werden wir Chain-of-Thought-Prompting für komplexe Denkaufgaben erkunden. diff --git a/src/content/book/de/06-chain-of-thought.mdx b/src/content/book/de/06-chain-of-thought.mdx new file mode 100644 index 00000000..dc62aeba --- /dev/null +++ b/src/content/book/de/06-chain-of-thought.mdx @@ -0,0 +1,363 @@ +Chain of Thought (CoT) Prompting ist eine Technik, die die KI-Leistung bei komplexen Denkaufgaben dramatisch verbessert, indem das Modell gebeten wird, seine Arbeit Schritt für Schritt zu zeigen. + + +Genau wie ein Mathelehrer, der Schüler bittet, ihre Arbeit zu zeigen, bittet CoT-Prompting die KI, ihr Denken sichtbar zu machen. + + +## Das Problem, das CoT löst + +KI-Modelle können mit mehrstufigem Denken kämpfen, wenn sie gebeten werden, direkt zur Antwort zu springen. + + + +## Grundlegende CoT-Prompts + +### Einfache Auslösephrasen + +Füge eine davon zu deinen Prompts hinzu: + +
+
"Lass uns Schritt für Schritt denken."
+
"Denke das sorgfältig durch."
+
"Arbeite dieses Problem methodisch durch."
+
"Zeige deine Begründung bei jedem Schritt."
+
"Erkläre deinen Denkprozess."
+
+ +### Explizite Schrittanfrage + + + +## Zero-Shot vs Few-Shot CoT + +Es gibt zwei Hauptansätze für Chain of Thought Prompting, jeder mit unterschiedlichen Kompromissen zwischen Einfachheit und Kontrolle. + +### Zero-Shot CoT + +Der einfachste Ansatz – füge einfach eine Auslösephrase hinzu und lass das Modell herausfinden, wie es denken soll. Keine Beispiele nötig. Das funktioniert überraschend gut für viele Probleme, obwohl du weniger Kontrolle über das Denkformat hast. + + + +**Beispielausgabe:** +``` +Lass uns Schritt für Schritt denken. +- Hans beginnt mit 3 Äpfeln +- Die Hälfte von 3 ist 1,5, aber wir können Äpfel nicht teilen +- Wenn wir abrunden: Hans gibt 1 Apfel, behält 2 +- Nach dem Kauf von 4 weiteren: 2 + 4 = 6 Äpfel + +Antwort: 6 Äpfel +``` + +### Few-Shot CoT + +Für konsistentere Ergebnisse zeige dem Modell genau, wie du willst, dass es denkt, indem du durchgearbeitete Beispiele lieferst. Das gibt dir Kontrolle über den Denkstil, das Format und das Detailniveau. Das Modell wird dein demonstriertes Muster nachahmen. + + + +**Beispielausgabe:** +``` +A: Lass uns das durcharbeiten: +- Regulärer Preis: 3€, Menge: 12 +- Da 12 ≥ 10, gilt der 25% Rabatt +- Regulärer Gesamtpreis: 12 × 3€ = 36€ +- Rabatt: 25% von 36€ = 9€ +- Endpreis: 36€ - 9€ = 27€ +``` + +## Strukturierte CoT-Formate + +Für konsistentes, reproduzierbares Denken verwende strukturierte Formate mit benannten Schritten. Diese Frameworks stellen sicher, dass das Modell keine wichtigen Stufen überspringt und machen Ausgaben einfacher zu parsen und verifizieren. + +### Das BREAK-Format + +Ein einprägsames Akronym, das das Modell durch einen vollständigen Problemlösungszyklus führt, vom Verstehen bis zur Verifizierung. + + + +### Die Denkvorlage + +Eine formellere Struktur, die Eingaben, Ziele und Ausführung trennt. Ausgezeichnet für technische Probleme, bei denen du klare Dokumentation des Lösungsprozesses brauchst. + + + +**Beispielausgabe:** +``` +GEGEBEN: 8L/100km, Tank 45L, 1,50€/L, fahren 300km +ZIEL: Kraftstoffkosten berechnen +ANSATZ: Benötigter Kraftstoff × Kosten pro Liter +SCHRITTE: +1. Kraftstoff = (300 ÷ 100) × 8 = 24 Liter +2. Kosten = 24 × 1,50€ = 36€ +VERIFIZIERUNG: 24L < 45L Tank ✓ +ANTWORT: 36€ +``` + +## CoT für verschiedene Problemtypen + +Verschiedene Problemtypen profitieren von verschiedenen CoT-Ansätzen. Hier sind Muster, die für häufige Szenarien optimiert sind. + +### Mathematisches Denken + +Mathematische Probleme profitieren am meisten von CoT, weil jeder Schritt auf dem vorherigen aufbaut. Fehler potenzieren sich, also hilft das Zeigen der Arbeit, Fehler früh zu erkennen. Das Modell sollte jede Berechnung klar beschriften. + + + +**Beispielausgabe:** +``` +Q1: 1.200.000€ (gegeben) +Q2: 1.200.000€ × 1,15 = 1.380.000€ +Q3: 1.380.000€ × 0,90 = 1.242.000€ +Q4: 1.242.000€ × 1,25 = 1.552.500€ + +Gesamt: 5.374.500€ +``` + +### Logisches Denken + +Logikrätsel erfordern systematische Elimination und Hypothesentests. CoT hilft dem Modell, Einschränkungen zu verfolgen, Möglichkeiten zu testen und zu verifizieren, dass alle Bedingungen erfüllt sind. Der Schlüssel ist methodische Erkundung statt Raten. + + + +**Beispielausgabe:** +``` +Aus Hinweis 3: Ben = Lehrer +→ Anna und Clara sind Ingenieur/Arzt + +Wenn Clara = Ingenieur: +- Clara hat Hund (Hinweis 2) +- Anna = Arzt, hat Fisch (Hinweis 1) +- Ben hat Katze + +Verifizieren: Alle 4 Hinweise erfüllt ✓ +Antwort: Anna (Arzt, Fisch), Ben (Lehrer, Katze), Clara (Ingenieur, Hund) +``` + +### Code-Debugging + +Debugging profitiert von CoT, weil es das Modell zwingt, die Ausführung zu verfolgen, statt Bugs zu raten. Durch das Durchgehen des Codes mit konkreten Werten wird das tatsächliche Verhalten sichtbar und Diskrepanzen zum erwarteten Verhalten werden aufgedeckt. + + + +**Beispielausgabe:** +``` +Verfolge [2, 3, 4, 6]: +n=2: total += 1 → 1 (Moment, addiert 1 nicht n!) +n=3: übersprungen (ungerade) +n=4: total = 2 +n=6: total = 3 + +BUG: "total += 1" sollte "total += n" sein +Erwartet: 12, Bekommen: 3 +Fix: Ändere zu "total += n" +``` + +## Selbstkonsistenz mit CoT + +Für kritische Probleme verlasse dich nicht auf einen einzelnen Denkpfad. Generiere mehrere unabhängige Lösungen und vergleiche Ergebnisse. Wenn verschiedene Ansätze zur gleichen Antwort konvergieren, ist das Vertrauen hoch. Unstimmigkeit signalisiert die Notwendigkeit sorgfältiger Überprüfung. + + + +**Beispielausgabe:** +``` +Ansatz 1 (Algebra): h + k = 30, 2h + 4k = 74 → h=23, k=7 +Ansatz 2 (Raten): Versuche 23/7 → 46 + 28 = 74 ✓ +Ansatz 3 (Logik): 30 Hühner = 60 Beine, brauche 14 mehr → 7 Kühe + +Alle stimmen überein: 23 Hühner, 7 Kühe +``` + +## CoT für Entscheidungsfindung + +Entscheidungen beinhalten das Abwägen von Kompromissen über mehrere Dimensionen. CoT stellt sicher, dass alle relevanten Faktoren systematisch berücksichtigt werden, statt zu voreiligen Schlüssen zu springen. Dieser strukturierte Ansatz dokumentiert auch die Begründung für zukünftige Referenz. + + + +**Beispielausgabe:** +``` +FAKTOREN: +- Teamgröße (5): Zu klein für Microservices ❌ +- Skalierung (100 DAU): Kein Skalierungsbedarf ❌ +- Geschwindigkeit: Monolith = schnellere Iteration ❌ +- Zukünftiges Wachstum: Unsicherer Zeitrahmen ⚠️ + +GEWICHTUNG: 3 stark dagegen, 1 schwach dafür + +EMPFEHLUNG: Beim Monolith bleiben, klare Modul- +grenzen für einfachere zukünftige Transition nutzen. +``` + +## Wann CoT verwenden + +
+
+

CoT verwenden für

+
+

**Mathematische Probleme** — Reduziert Rechenfehler

+

**Logikrätsel** — Verhindert übersprungene Schritte

+

**Komplexe Analysen** — Organisiert das Denken

+

**Code-Debugging** — Verfolgt Ausführung

+

**Entscheidungsfindung** — Wägt Kompromisse ab

+
+
+
+

CoT überspringen für

+
+

**Einfache Fragen** — Unnötiger Overhead

+

**Kreatives Schreiben** — Kann Kreativität einschränken

+

**Faktennachschlagen** — Kein Denken nötig

+

**Übersetzung** — Direkte Aufgabe

+

**Zusammenfassung** — Normalerweise unkompliziert

+
+
+
+ +## CoT-Einschränkungen + +Obwohl mächtig, ist Chain of Thought kein Allheilmittel. Das Verstehen seiner Einschränkungen hilft dir, es angemessen anzuwenden. + +1. **Erhöhte Token-Nutzung** — Mehr Ausgabe bedeutet höhere Kosten +2. **Nicht immer nötig** — Einfache Aufgaben profitieren nicht +3. **Kann ausführlich sein** — Muss möglicherweise um Prägnanz bitten +4. **Denken kann fehlerhaft sein** — CoT garantiert keine Korrektheit + +## Zusammenfassung + + +CoT verbessert komplexes Denken dramatisch, indem es implizite Schritte explizit macht. Verwende es für Mathematik, Logik, Analyse und Debugging. Kompromiss: bessere Genauigkeit für mehr Tokens. + + + + +Im nächsten Kapitel werden wir Few-Shot-Learning erkunden – das Lehren des Modells durch Beispiele. diff --git a/src/content/book/de/07-few-shot-learning.mdx b/src/content/book/de/07-few-shot-learning.mdx new file mode 100644 index 00000000..ae322ea9 --- /dev/null +++ b/src/content/book/de/07-few-shot-learning.mdx @@ -0,0 +1,477 @@ +Few-Shot-Learning ist eine der mächtigsten Prompting-Techniken. Indem du Beispiele dessen lieferst, was du willst, kannst du dem Modell komplexe Aufgaben beibringen, ohne Feinabstimmung. + + +Genau wie Menschen durch Beispiele lernen, können KI-Modelle Muster aus den Beispielen lernen, die du in deinem Prompt lieferst. + + +## Was ist Few-Shot-Learning? + +Few-Shot-Learning zeigt dem Modell Beispiele von Eingabe-Ausgabe-Paaren, bevor du es bittest, dieselbe Aufgabe auszuführen. Das Modell lernt das Muster aus deinen Beispielen und wendet es auf neue Eingaben an. + + + +
+
+
0
+
Zero-Shot
+
+
+
1
+
One-Shot
+
+
+
2-5
+
Few-Shot
+
+
+
5+
+
Many-Shot
+
+
+ +## Warum Beispiele funktionieren + + + +Beispiele kommunizieren: +- **Format**: Wie die Ausgabe strukturiert sein sollte +- **Stil**: Ton, Länge, Vokabular +- **Logik**: Das zu befolgende Denkmuster +- **Grenzfälle**: Wie Sondersituationen behandelt werden + +## Grundlegendes Few-Shot-Muster + +Die grundlegende Struktur des Few-Shot-Promptings folgt einem einfachen Muster: zeige Beispiele, dann frage nach der neuen Aufgabe. Konsistenz in der Formatierung zwischen Beispielen ist entscheidend. Das Modell lernt aus dem Muster, das du etablierst. + +``` +[Beispiel 1] +Eingabe: [Eingabe 1] +Ausgabe: [Ausgabe 1] + +[Beispiel 2] +Eingabe: [Eingabe 2] +Ausgabe: [Ausgabe 2] + +[Beispiel 3] +Eingabe: [Eingabe 3] +Ausgabe: [Ausgabe 3] + +Jetzt mach dieses: +Eingabe: [neue Eingabe] +Ausgabe: +``` + +## Few-Shot für Klassifikation + +Klassifikation ist einer der stärksten Anwendungsfälle für Few-Shot-Learning. Indem du Beispiele jeder Kategorie zeigst, definierst du die Grenzen zwischen Klassen präziser, als Anweisungen allein es könnten. + +### Sentimentanalyse + + +Sentimentanalyse klassifiziert Text nach emotionalem Ton: positiv, negativ, neutral oder gemischt. Sie wird häufig für Kundenfeedback, Social-Media-Monitoring und Markenwahrnehmungs-Tracking verwendet. + + +Sentiment-Klassifikation profitiert davon, Beispiele jedes Sentiment-Typs zu zeigen, besonders Grenzfälle wie „gemischtes" Sentiment, das mehrdeutig sein könnte. + + + +### Themenklassifikation + +Für Mehrklassen-Kategorisierung füge mindestens ein Beispiel pro Kategorie hinzu. Das hilft dem Modell, deine spezifische Taxonomie zu verstehen, die von seinem Standardverständnis abweichen kann. + + + +## Few-Shot für Transformation + +Transformationsaufgaben konvertieren Eingabe von einer Form in eine andere, während die Bedeutung erhalten bleibt. Beispiele sind hier essenziell, weil sie genau definieren, was „Transformation" für deinen Anwendungsfall bedeutet. + +### Textumschreibung + +Stiltransformation erfordert Beispiele, die den genauen gewünschten Tonwechsel zeigen. Abstrakte Anweisungen wie „mach es professioneller" werden unterschiedlich interpretiert. Beispiele machen es konkret. + + + +### Formatkonvertierung + +Formatkonvertierungsaufgaben profitieren von Beispielen, die Grenzfälle und mehrdeutige Eingaben zeigen. Das Modell lernt deine spezifischen Konventionen für den Umgang mit kniffligen Fällen. + + + +## Few-Shot für Generierung + +Generierungsaufgaben erstellen neue Inhalte nach einem gelernten Muster. Beispiele etablieren Länge, Struktur, Ton und welche Details hervorgehoben werden sollen. Diese sind schwer in Anweisungen allein zu spezifizieren. + +### Produktbeschreibungen + +Marketingtexte profitieren enorm von Beispielen, weil sie Markenstimme, Feature-Betonung und überzeugende Techniken einfangen, die abstrakt schwer zu beschreiben sind. + + + +### Code-Dokumentation + + +Gute Dokumentation erklärt, was Code macht, seine Parameter, Rückgabewerte und Nutzungsbeispiele. Konsistente Docstrings ermöglichen automatisch generierte API-Dokumentation und helfen IDEs, bessere Code-Vervollständigung zu bieten. + + +Dokumentationsstil variiert stark zwischen Projekten. Beispiele lehren dein spezifisches Format, was enthalten sein soll (args, returns, Beispiele) und das erwartete Detailniveau. + +>> calculate_bmi(70, 1.75) + 22.86 +""" + +Jetzt dokumentiere: +Funktion: +def is_palindrome(text): + cleaned = ''.join(c.lower() for c in text if c.isalnum()) + return cleaned == cleaned[::-1] + +Dokumentation:`} /> + +## Few-Shot für Extraktion + +Extraktionsaufgaben ziehen strukturierte Informationen aus unstrukturiertem Text. Beispiele definieren, welche Entitäten wichtig sind, wie die Ausgabe formatiert werden soll und wie Fälle behandelt werden, bei denen Informationen fehlen oder mehrdeutig sind. + +### Entitätsextraktion + + +Named Entity Recognition (NER) identifiziert und klassifiziert benannte Entitäten in Text in Kategorien wie Personen, Organisationen, Orte, Daten und Produkte. Sie ist fundamental für Information Retrieval und Wissensgraphen. + + +NER profitiert von Beispielen, die deine spezifischen Entitätstypen zeigen und wie Entitäten behandelt werden, die in mehrere Kategorien passen könnten. + + + +### Strukturierte Datenextraktion + +Das Extrahieren strukturierter Daten aus natürlicher Sprache erfordert Beispiele, die zeigen, wie fehlende Felder, implizite Informationen und variierende Eingabeformate behandelt werden. + + + +## Fortgeschrittene Few-Shot-Techniken + +Über grundlegendes Few-Shot hinaus können mehrere Techniken die Ergebnisse für komplexe Aufgaben verbessern. + +### Diverse Beispiele + +Diversität in Beispielen ist wertvoller als Quantität. Decke verschiedene Szenarien, Grenzfälle und potenzielle Mehrdeutigkeiten ab, statt ähnliche Beispiele wiederholt zu zeigen. + + + +### Negative Beispiele + + +Das Zeigen von „guten" vs. „schlechten" Beispielen nennt man kontrastives Lernen. Es hilft dem Modell zu verstehen, nicht nur was du willst, sondern was zu vermeiden ist. Das ist besonders nützlich für Stil- und Qualitätsurteile. + + +Manchmal ist das Zeigen, was *nicht* zu tun ist, genauso wertvoll wie das Zeigen korrekter Beispiele. Negative Beispiele helfen dem Modell, Grenzen zu verstehen und häufige Fehler zu vermeiden. + + + +### Grenzfall-Beispiele + +Grenzfälle bestimmen oft, ob eine Lösung in der Produktion funktioniert. Das Einbeziehen ungewöhnlicher Eingaben in deine Beispiele verhindert, dass das Modell bei realen Daten versagt, die nicht zum „Happy Path" passen. + + + +## Wie viele Beispiele? + +
+
+ Einfache Klassifikation + 2-3 + Mindestens eines pro Kategorie +
+
+ Komplexe Formatierung + 3-5 + Zeige Variationen +
+
+ Nuancierter Stil + 4-6 + Erfasse volle Bandbreite +
+
+ Grenzfälle + 1-2 + Neben normalen Beispielen +
+
+ +## Beispielqualität zählt + + + +## Few-Shot mit anderen Techniken kombinieren + +Few-Shot-Learning kombiniert sich kraftvoll mit anderen Prompting-Techniken. Die Beispiele liefern das „Was", während andere Techniken Kontext, Begründung oder Struktur hinzufügen können. + +### Few-Shot + Rolle + +Das Hinzufügen einer Rolle gibt dem Modell Kontext dafür, *warum* es die Aufgabe ausführt, was Qualität und Konsistenz verbessern kann. + +``` +Du bist ein Prüfer für juristische Verträge. + +[Beispiele von Vertragsklausel-Analysen] + +Jetzt analysiere: [neue Klausel] +``` + +### Few-Shot + CoT + +Die Kombination von Few-Shot mit Chain of Thought zeigt nicht nur, *welche* Antwort zu geben ist, sondern *wie* man zur Antwort gelangt. Das ist mächtig für Aufgaben, die Urteilsvermögen erfordern. + +``` +Klassifiziere und erkläre die Begründung. + +Bewertung: "Tolle Features, aber überteuert" +Denken: Die Bewertung erwähnt positive Aspekte ("tolle Features") +aber auch ein signifikantes Negativ ("überteuert"). Das Negative scheint +das Positive zu überwiegen, basierend auf der "aber"-Konjunktion. +Klassifikation: Gemischt-Negativ + +[weitere Beispiele mit Begründung] + +Jetzt klassifiziere mit Begründung: +Bewertung: "Genau was ich brauchte, kam schneller als erwartet an" +``` + +## Zusammenfassung + + +Few-Shot-Learning lehrt durch Demonstration und ist oft effektiver als Anweisungen allein. Verwende 2-5 diverse, korrekte Beispiele und kombiniere mit anderen Techniken für beste Ergebnisse. + + + + +Im nächsten Kapitel werden wir iterative Verfeinerung erkunden: die Kunst, Prompts durch aufeinanderfolgende Versuche zu verbessern. diff --git a/src/content/book/de/08-iterative-refinement.mdx b/src/content/book/de/08-iterative-refinement.mdx new file mode 100644 index 00000000..43eaa58c --- /dev/null +++ b/src/content/book/de/08-iterative-refinement.mdx @@ -0,0 +1,387 @@ +Prompt Engineering ist selten ein Ein-Schuss-Prozess. Die besten Prompts entstehen durch Iteration – testen, beobachten und verfeinern, bis du die gewünschten Ergebnisse erzielst. + + +Betrachte deinen ersten Prompt als Rohentwurf. Selbst erfahrene Prompt-Ingenieure treffen es selten beim ersten Versuch. + + +## Der Iterationszyklus + +Effektive Prompt-Verfeinerung folgt einem vorhersehbaren Zyklus: schreiben, testen, analysieren und verbessern. Jede Iteration bringt dich näher an einen Prompt, der zuverlässig die Ergebnisse liefert, die du brauchst. + + + +## Häufige Verfeinerungsmuster + +Die meisten Prompt-Fehler fallen in eine Handvoll Kategorien. Das Erkennen dieser Muster lässt dich Probleme schnell diagnostizieren und beheben, ohne von vorn anzufangen. + +### Problem: Ausgabe zu lang + +Eines der häufigsten Probleme. Ohne explizite Einschränkungen neigen Modelle dazu, gründlich statt prägnant zu sein. + + + +### Problem: Ausgabe zu vage + +Vage Prompts produzieren vage Ausgaben. Das Modell kann deine Gedanken nicht lesen, was „besser" bedeutet oder welche Aspekte dir am wichtigsten sind. + + + +### Problem: Falscher Ton + +Ton ist subjektiv und variiert je nach Kontext. Was für das Modell „professionell" klingt, passt möglicherweise nicht zur Stimme deiner Organisation oder der Beziehung zu deinem Empfänger. + + + +### Problem: Fehlende Schlüsselinformationen + +Offene Anfragen bekommen offene Antworten. Wenn du bestimmte Arten von Feedback brauchst, musst du explizit danach fragen. + + + +### Problem: Inkonsistentes Format + +Ohne Vorlage wird das Modell jede Antwort anders strukturieren, was Vergleiche schwierig und Automatisierung unmöglich macht. + + + +## Systematischer Verfeinerungsansatz + +Zufällige Änderungen verschwenden Zeit. Ein systematischer Ansatz hilft dir, Probleme schnell zu identifizieren und effizient zu beheben. + +### Schritt 1: Das Problem diagnostizieren + +Bevor du etwas änderst, identifiziere, was tatsächlich falsch ist. Nutze diese Diagnosetabelle, um Symptome Lösungen zuzuordnen: + +
+
+ Symptom + Wahrscheinliche Ursache + Lösung +
+
+ Zu lang + Keine Längenbeschränkung + Wort-/Satzlimits hinzufügen +
+
+ Zu kurz + Fehlende Detailanfrage + Um Ausführlichkeit bitten +
+
+ Thema verfehlt + Vage Anweisungen + Spezifischer sein +
+
+ Falsches Format + Format nicht spezifiziert + Genaue Struktur definieren +
+
+ Falscher Ton + Publikum unklar + Publikum/Stil spezifizieren +
+
+ Inkonsistent + Keine Beispiele geliefert + Few-Shot-Beispiele hinzufügen +
+
+ +### Schritt 2: Gezielte Änderungen vornehmen + +Widerstehe dem Drang, alles neu zu schreiben. Mehrere Variablen gleichzeitig zu ändern macht es unmöglich zu wissen, was geholfen hat und was geschadet hat. Nimm eine Änderung vor, teste sie, dann fahre fort: + +``` +Iteration 1: Längenbeschränkung hinzufügen +Iteration 2: Format spezifizieren +Iteration 3: Beispiel hinzufügen +Iteration 4: Tonanweisungen verfeinern +``` + +### Schritt 3: Dokumentiere, was funktioniert + +Prompt-Engineering-Wissen geht leicht verloren. Führe ein Protokoll darüber, was du versucht hast und warum. Das spart Zeit, wenn du den Prompt später wieder besuchst oder ähnliche Herausforderungen hast: + +```markdown +## Prompt: Kunden-E-Mail-Antwort + +### Version 1 (zu förmlich) +"Schreibe eine Antwort auf diese Kundenbeschwerde." + +### Version 2 (besserer Ton, noch fehlende Struktur) +"Schreibe eine freundliche, aber professionelle Antwort auf diese Beschwerde. +Zeige zuerst Empathie." + +### Version 3 (final - gute Ergebnisse) +"Schreibe eine Antwort auf diese Kundenbeschwerde. Struktur: +1. Ihre Frustration anerkennen (1 Satz) +2. Sich konkret entschuldigen (1 Satz) +3. Lösung erklären (2-3 Sätze) +4. Zusätzliche Hilfe anbieten (1 Satz) + +Ton: Freundlich, professionell, empathisch aber nicht unterwürfig." +``` + +## Praxis-Iterationsbeispiel + +Lass uns durch einen kompletten Iterationszyklus gehen, um zu sehen, wie jede Verfeinerung auf der vorherigen aufbaut. Beachte, wie jede Version spezifische Mängel der vorherigen adressiert. + +### Aufgabe: Produktnamen generieren + + + +## Verfeinerungsstrategien nach Aufgabentyp + +Verschiedene Aufgaben scheitern auf vorhersehbare Weise. Das Kennen der häufigen Fehlermodi hilft dir, Probleme schneller zu diagnostizieren und zu beheben. + +### Für Inhaltsgenerierung + +Inhaltsgenerierung produziert oft generische, zielverfehlte oder schlecht formatierte Ausgaben. Die Lösung beinhaltet normalerweise, spezifischer bei Einschränkungen zu sein, konkrete Beispiele zu liefern oder deine Markenstimme explizit zu definieren. + + + +### Für Code-Generierung + +Code-Ausgabe kann technisch scheitern (Syntaxfehler, falsche Sprachfeatures) oder architektonisch (schlechte Muster, fehlende Fälle). Technische Probleme brauchen Versions-/Umgebungsspezifika; architektonische Probleme brauchen Design-Anleitung. + + + +### Für Analyse + +Analyseaufgaben produzieren oft oberflächliche oder unstrukturierte Ergebnisse. Leite das Modell mit spezifischen Frameworks (SWOT, Porters Five Forces), fordere mehrere Perspektiven an oder liefere eine Vorlage für die Ausgabestruktur. + + + +### Für Frage-Antwort + +Frage-Antwort kann zu knapp oder zu ausführlich sein und kann Konfidenzindikatoren oder Quellen vermissen lassen. Spezifiziere das benötigte Detailniveau und ob du Zitate oder geäußerte Unsicherheit willst. + + + +## Die Feedback-Loop-Technik + +Hier ist eine Meta-Technik: Nutze das Modell selbst, um deine Prompts zu verbessern. Teile mit, was du versucht hast, was du bekommen hast und was du wolltest. Das Modell kann oft Verbesserungen vorschlagen, an die du nicht gedacht hattest. + +``` +Ich habe diesen Prompt verwendet: +"[dein Prompt]" + +Und diese Ausgabe bekommen: +"[Modell-Ausgabe]" + +Ich wollte etwas mehr [beschreibe Lücke]. Wie sollte ich +meinen Prompt modifizieren, um bessere Ergebnisse zu bekommen? +``` + +## A/B-Testen von Prompts + +Für Prompts, die wiederholt oder in großem Maßstab verwendet werden, wähle nicht einfach den ersten, der funktioniert. Teste Variationen, um den zuverlässigsten und qualitativ hochwertigsten Ansatz zu finden. + +``` +Prompt A: "Fasse diesen Artikel in 3 Stichpunkten zusammen." +Prompt B: "Extrahiere die 3 wichtigsten Erkenntnisse aus diesem Artikel." +Prompt C: "Was sind die wichtigsten Takeaways aus diesem Artikel? Liste 3 auf." +``` + +Führe jeden mehrmals aus, vergleiche: +- Konsistenz der Ausgabe +- Qualität der Informationen +- Relevanz für deine Bedürfnisse + +## Wann mit dem Iterieren aufhören + +Perfektion ist der Feind von gut genug. Wisse, wann dein Prompt einsatzbereit ist und wann du nur noch für sinkende Erträge polierst. + +
+
+

Bereit zum Einsatz

+
+

Ausgabe erfüllt konsistent die Anforderungen

+

Grenzfälle werden angemessen behandelt

+

Format ist zuverlässig und parsebar

+

Weitere Verbesserungen zeigen sinkende Erträge

+
+
+
+

Weiter iterieren

+
+

Ausgabe ist inkonsistent über Durchläufe

+

Grenzfälle verursachen Fehler

+

Kritische Anforderungen werden verfehlt

+

Du hast nicht genug Variationen getestet

+
+
+
+ +## Versionskontrolle für Prompts + +Prompts sind Code. Für jeden Prompt, der in Produktion verwendet wird, behandle ihn mit derselben Strenge: Versionskontrolle, Changelogs und die Möglichkeit, zurückzurollen, wenn etwas kaputt geht. + + +prompts.chat enthält automatische Versionshistorie für deine Prompts. Jede Bearbeitung wird gespeichert, sodass du Versionen vergleichen und vorherige Iterationen mit einem Klick wiederherstellen kannst. + + +Für selbstverwaltete Prompts verwende eine Ordnerstruktur: + +``` +prompts/ +├── kunden-antwort/ +│ ├── v1.0.txt # Erste Version +│ ├── v1.1.txt # Tonproblem behoben +│ ├── v2.0.txt # Große Umstrukturierung +│ └── current.txt # Symlink zur aktiven Version +└── changelog.md # Änderungen dokumentieren +``` + +## Zusammenfassung + + +Beginne einfach, beobachte sorgfältig, ändere eine Sache nach der anderen, dokumentiere was funktioniert und wisse, wann aufhören. Die besten Prompts werden nicht geschrieben – sie werden durch systematische Iteration entdeckt. + + + + +## Übung: Verbessere diesen Prompt + +Versuche, diesen schwachen Prompt selbst zu verbessern. Bearbeite ihn, dann nutze KI, um deine Version mit dem Original zu vergleichen: + + + +Im nächsten Kapitel werden wir JSON- und YAML-Prompting für strukturierte Datenanwendungen erkunden. diff --git a/src/content/book/de/09-json-yaml-prompting.mdx b/src/content/book/de/09-json-yaml-prompting.mdx new file mode 100644 index 00000000..415a6524 --- /dev/null +++ b/src/content/book/de/09-json-yaml-prompting.mdx @@ -0,0 +1,586 @@ +Strukturierte Datenformate wie JSON und YAML sind essenziell für den Aufbau von Anwendungen, die KI-Ausgaben programmatisch konsumieren. Dieses Kapitel behandelt Techniken für zuverlässige strukturierte Ausgabegenerierung. + + +JSON und YAML transformieren KI-Ausgaben von Freitext in strukturierte, typsichere Daten, die Code direkt konsumieren kann. + + +## Warum strukturierte Formate? + + + +## JSON-Prompting-Grundlagen + +JSON (JavaScript Object Notation) ist das häufigste Format für programmatische KI-Ausgaben. Seine strikte Syntax macht es einfach zu parsen, bedeutet aber auch, dass kleine Fehler deine gesamte Pipeline brechen können. + +### Do's und Don'ts: JSON anfordern + + + +### Einfache JSON-Ausgabe + +Beginne mit einem Schema, das die erwartete Struktur zeigt. Das Modell wird Werte basierend auf dem Eingabetext ausfüllen. + +``` +Extrahiere die folgenden Informationen als JSON: + +{ + "name": "string", + "age": number, + "email": "string" +} + +Text: "Kontaktiere Hans Müller, 34 Jahre alt, unter hans@example.com" +``` + +Ausgabe: +```json +{ + "name": "Hans Müller", + "age": 34, + "email": "hans@example.com" +} +``` + +### Verschachtelte JSON-Strukturen + +Reale Daten haben oft verschachtelte Beziehungen. Definiere jede Ebene deines Schemas klar, besonders für Arrays von Objekten. + +``` +Parse diese Bestellung in JSON: + +{ + "order_id": "string", + "customer": { + "name": "string", + "email": "string" + }, + "items": [ + { + "product": "string", + "quantity": number, + "price": number + } + ], + "total": number +} + +Bestellung: "Bestellung #12345 für Jana Schmidt (jana@email.com): 2x Widget (je 10€), +1x Gadget (25€). Gesamt: 45€" +``` + +### Gültiges JSON sicherstellen + + +Modelle wrappen JSON oft in Markdown-Code-Blöcke oder fügen erklärenden Text hinzu. Sei explizit darüber, dass du nur rohes JSON willst. + + +Füge explizite Anweisungen hinzu: + +``` +KRITISCH: Gib NUR gültiges JSON zurück. Kein Markdown, keine Erklärung, +kein zusätzlicher Text vor oder nach dem JSON-Objekt. + +Wenn ein Feld nicht bestimmt werden kann, verwende null. +Stelle sicher, dass alle Strings korrekt quoted und escaped sind. +Zahlen sollten nicht gequoted werden. +``` + +## YAML-Prompting-Grundlagen + +YAML ist menschenlesbarer als JSON und unterstützt Kommentare. Es ist der Standard für Konfigurationsdateien, besonders in DevOps (Docker, Kubernetes, GitHub Actions). + +### Einfache YAML-Ausgabe + +YAML verwendet Einrückung statt Klammern. Liefere eine Vorlage, die die erwartete Struktur zeigt. + +``` +Generiere eine Konfigurationsdatei im YAML-Format: + +server: + host: string + port: number + ssl: boolean +database: + type: string + connection_string: string + +Anforderungen: Produktionsserver auf Port 443 mit SSL, PostgreSQL-Datenbank +``` + +Ausgabe: +```yaml +server: + host: "0.0.0.0" + port: 443 + ssl: true +database: + type: "postgresql" + connection_string: "postgresql://user:pass@localhost:5432/prod" +``` + +### Komplexe YAML-Strukturen + +Für komplexe Konfigurationen sei spezifisch über Anforderungen. Das Modell kennt gängige Muster für Tools wie GitHub Actions, Docker Compose und Kubernetes. + +``` +Generiere einen GitHub Actions Workflow in YAML: + +Anforderungen: +- Auslösen bei Push zu main und Pull Requests +- Auf Ubuntu latest laufen +- Schritte: checkout, Node 18 einrichten, Abhängigkeiten installieren, Tests ausführen +- npm-Abhängigkeiten cachen +``` + +## Typdefinitionen in Prompts + +Typdefinitionen geben dem Modell einen präzisen Vertrag für die Ausgabestruktur. Sie sind expliziter als Beispiele und einfacher programmatisch zu validieren. + +### TypeScript-ähnliche Typen verwenden + +TypeScript-Interfaces sind Entwicklern vertraut und beschreiben präzise optionale Felder, Union-Types und Arrays. Die prompts.chat-Plattform nutzt diesen Ansatz für strukturierte Prompts. + + + +### JSON-Schema-Definition + + +JSON Schema ist eine formale Spezifikation zur Beschreibung von JSON-Struktur. Es wird von vielen Validierungsbibliotheken und API-Tools unterstützt. + + +JSON Schema bietet Einschränkungen wie Min/Max-Werte, erforderliche Felder und Regex-Muster: + +``` +Extrahiere Daten gemäß diesem JSON Schema: + +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "type": "object", + "required": ["title", "author", "year"], + "properties": { + "title": { "type": "string" }, + "author": { "type": "string" }, + "year": { "type": "integer", "minimum": 1000, "maximum": 2100 }, + "genres": { + "type": "array", + "items": { "type": "string" } + }, + "rating": { + "type": "number", + "minimum": 0, + "maximum": 5 + } + } +} + +Buch: "1984 von George Orwell (1949) - Ein dystopisches Meisterwerk. +Genres: Science Fiction, Politische Fiktion. Bewertet 4.8/5" +``` + +## Umgang mit Arrays + +Arrays erfordern besondere Aufmerksamkeit. Spezifiziere, ob du eine feste Anzahl von Elementen oder eine variable Liste brauchst, und wie leere Fälle behandelt werden sollen. + +### Arrays fester Länge + +Wenn du genau N Elemente brauchst, sage es explizit. Das Modell wird sicherstellen, dass das Array die richtige Länge hat. + +``` +Extrahiere genau 3 Kernpunkte als JSON: + +{ + "key_points": [ + "string (erster Punkt)", + "string (zweiter Punkt)", + "string (dritter Punkt)" + ] +} + +Artikel: [Artikeltext] +``` + +### Arrays variabler Länge + +Für Arrays variabler Länge spezifiziere, was zu tun ist, wenn es null Elemente gibt. Ein Zählfeld hilft, die Vollständigkeit der Extraktion zu verifizieren. + +``` +Extrahiere alle erwähnten Personen als JSON: + +{ + "people": [ + { + "name": "string", + "role": "string oder null wenn nicht erwähnt" + } + ], + "count": number +} + +Wenn keine Personen erwähnt werden, gib leeres Array zurück. + +Text: [Text] +``` + +## Enum-Werte und Einschränkungen + +Enums beschränken Werte auf eine vordefinierte Menge. Das ist entscheidend für Klassifikationsaufgaben und überall, wo du konsistente, vorhersehbare Ausgaben brauchst. + +### Do's und Don'ts: Enum-Werte + + + +### String-Enums + +Liste erlaubte Werte explizit auf. Verwende „MUSS einer der folgenden sein"-Sprache, um strikte Übereinstimmung zu erzwingen. + +``` +Klassifiziere diesen Text. Die Kategorie MUSS einer dieser exakten Werte sein: +- "technical" +- "business" +- "creative" +- "personal" + +Gib JSON zurück: +{ + "text": "Originaltext (auf 50 Zeichen gekürzt)", + "category": "einer der Enum-Werte oben", + "confidence": Zahl zwischen 0 und 1 +} + +Text: [zu klassifizierender Text] +``` + +### Validierte Zahlen + +Numerische Einschränkungen verhindern Out-of-Range-Werte. Spezifiziere den Typ (Integer vs Float) und gültigen Bereich. + +``` +Bewerte diese Aspekte. Jede Punktzahl MUSS eine Ganzzahl von 1 bis 5 sein. + +{ + "quality": 1-5, + "value": 1-5, + "service": 1-5, + "overall": 1-5 +} + +Bewertung: [Bewertungstext] +``` + +## Umgang mit fehlenden Daten + +Reale Texte haben oft fehlende Informationen. Definiere, wie das Modell fehlende Daten behandeln soll, um halluzinierte Werte zu vermeiden. + +### Do's und Don'ts: Fehlende Informationen + + + +### Null-Werte + +Erlaube explizit null und weise das Modell an, keine Informationen zu erfinden. Das ist sicherer, als das Modell raten zu lassen. + +``` +Extrahiere Informationen. Verwende null für jedes Feld, das nicht +aus dem Text bestimmt werden kann. Erfinde KEINE Informationen. + +{ + "company": "string oder null", + "revenue": "number oder null", + "employees": "number oder null", + "founded": "number (Jahr) oder null", + "headquarters": "string oder null" +} + +Text: "Apple, mit Hauptsitz in Cupertino, wurde 1976 gegründet." +``` + +Ausgabe: +```json +{ + "company": "Apple", + "revenue": null, + "employees": null, + "founded": 1976, + "headquarters": "Cupertino" +} +``` + +### Standardwerte + +Wenn Standardwerte sinnvoll sind, spezifiziere sie im Schema. Das ist üblich für Konfigurationsextraktion. + +``` +Extrahiere Einstellungen mit diesen Standardwerten, wenn nicht angegeben: + +{ + "theme": "light" (Standard) | "dark", + "language": "de" (Standard) | anderer ISO-Code, + "notifications": true (Standard) | false, + "fontSize": 14 (Standard) | number +} + +Benutzereinstellungen: "Ich möchte Dunkelmodus und größeren Text (18px)" +``` + +## Mehrobjekt-Antworten + +Oft musst du mehrere Elemente aus einer einzelnen Eingabe extrahieren. Definiere die Array-Struktur und alle Sortierungs-/Gruppierungsanforderungen. + +### Array von Objekten + +Für Listen ähnlicher Elemente definiere das Objektschema einmal und spezifiziere, dass es ein Array ist. + +``` +Parse diese Liste in ein JSON-Array: + +[ + { + "task": "string", + "priority": "high" | "medium" | "low", + "due": "ISO-Datumsstring oder null" + } +] + +Aufgabenliste: +- Bericht fertigstellen (dringend, fällig morgen) +- Zahnarzt anrufen (niedrige Priorität) +- PR #123 reviewen (mittlere Priorität, fällig Freitag) +``` + +### Gruppierte Objekte + +Gruppierungsaufgaben erfordern Kategorisierungslogik. Das Modell wird Elemente in die Kategorien sortieren, die du definierst. + +``` +Kategorisiere diese Elemente in JSON: + +{ + "fruits": ["String-Array"], + "vegetables": ["String-Array"], + "other": ["String-Array"] +} + +Elemente: Apfel, Karotte, Brot, Banane, Brokkoli, Milch, Orange, Spinat +``` + +## YAML für Konfigurationsgenerierung + +YAML glänzt bei DevOps-Konfigurationen. Das Modell kennt Standardmuster für gängige Tools und kann produktionsreife Configs generieren. + +### Do's und Don'ts: YAML-Configs + + + +### Docker Compose + +Spezifiziere die Services, die du brauchst, und alle speziellen Anforderungen. Das Modell wird die YAML-Syntax und Best Practices handhaben. + +``` +Generiere eine docker-compose.yml für: +- Node.js App auf Port 3000 +- PostgreSQL-Datenbank +- Redis-Cache +- Nginx Reverse Proxy + +Enthalten: +- Health Checks +- Volume-Persistenz +- Umgebungsvariablen aus .env-Datei +- Netzwerk-Isolation +``` + +### Kubernetes-Manifeste + +Kubernetes-Manifeste sind ausführlich, folgen aber vorhersehbaren Mustern. Liefere die Schlüsselparameter und das Modell wird konformes YAML generieren. + +``` +Generiere Kubernetes Deployment YAML: + +Deployment: +- Name: api-server +- Image: myapp:v1.2.3 +- Replicas: 3 +- Resources: 256Mi Speicher, 250m CPU (Requests) +- Health Checks: /health Endpunkt +- Environment aus ConfigMap: api-config + +Generiere auch passenden Service (ClusterIP, Port 8080) +``` + +## Validierung und Fehlerbehandlung + +Für Produktionssysteme baue Validierung in deine Prompts ein. Das fängt Fehler ab, bevor sie sich durch deine Pipeline verbreiten. + +### Selbstvalidierungs-Prompt + +Bitte das Modell, seine eigene Ausgabe gegen Regeln zu validieren, die du spezifizierst. Das fängt Formatfehler und ungültige Werte ab. + +``` +Extrahiere Daten als JSON, dann validiere deine Ausgabe. + +Schema: +{ + "email": "gültiges E-Mail-Format", + "phone": "E.164-Format (+1234567890)", + "date": "ISO 8601-Format (JJJJ-MM-TT)" +} + +Nach der JSON-Generierung prüfe: +1. E-Mail enthält @ und gültige Domain +2. Telefon beginnt mit + und enthält nur Ziffern +3. Datum ist gültig und parsebar + +Wenn Validierung fehlschlägt, behebe die Probleme vor dem Antworten. + +Text: [Kontaktinformationen] +``` + +### Fehlerantwort-Format + +Definiere separate Erfolgs- und Fehlerformate. Das macht programmatische Behandlung viel einfacher. + +``` +Versuche Daten zu extrahieren. Wenn Extraktion fehlschlägt, gib Fehlerformat zurück: + +Erfolgsformat: +{ + "success": true, + "data": { ... extrahierte Daten ... } +} + +Fehlerformat: +{ + "success": false, + "error": "Beschreibung was schief ging", + "partial_data": { ... Daten die extrahiert werden konnten ... } +} +``` + +## JSON vs YAML: Wann welches verwenden + +
+
+
JSON verwenden wenn
+
+

Programmatisches Parsing benötigt

+

API-Antworten

+

Strikte Typanforderungen

+

JavaScript/Web-Integration

+

Kompakte Darstellung

+
+
+
+
YAML verwenden wenn
+
+

Menschliche Lesbarkeit wichtig ist

+

Konfigurationsdateien

+

Kommentare benötigt werden

+

DevOps/Infrastruktur

+

Tief verschachtelte Strukturen

+
+
+
+ +## Prompts.chat Strukturierte Prompts + +Auf prompts.chat kannst du Prompts mit strukturierten Ausgabeformaten erstellen: + +``` +Beim Erstellen eines Prompts auf prompts.chat kannst du angeben: + +Typ: STRUCTURED +Format: JSON oder YAML + +Die Plattform wird: +- Ausgaben gegen dein Schema validieren +- Syntax-Highlighting bereitstellen +- Einfaches Kopieren strukturierter Ausgaben ermöglichen +- Template-Variablen in deinem Schema unterstützen +``` + +## Häufige Fallstricke + + +Diese drei Probleme verursachen die meisten JSON-Parsing-Fehler. Prüfe sie, wenn dein Code KI-Ausgabe nicht parsen kann. + + +### 1. Markdown-Code-Blöcke + +**Problem:** Modell wrappt JSON in ```json-Blöcke + +**Lösung:** +``` +Gib NUR das JSON-Objekt zurück. Wrappe nicht in Markdown-Code-Blöcke. +Füge keine ```json oder ``` Marker ein. +``` + +### 2. Nachgestellte Kommas + +**Problem:** Ungültiges JSON durch nachgestellte Kommas + +**Lösung:** +``` +Stelle gültige JSON-Syntax sicher. Keine nachgestellten Kommas nach dem +letzten Element in Arrays oder Objekten. +``` + +### 3. Nicht-escapte Strings + +**Problem:** Anführungszeichen oder Sonderzeichen brechen JSON + +**Lösung:** +``` +Escape Sonderzeichen in Strings korrekt: +- \" für Anführungszeichen +- \\ für Backslashes +- \n für Zeilenumbrüche +``` + +## Zusammenfassung + + +Definiere Schemas explizit mit TypeScript-Interfaces oder JSON Schema. Spezifiziere Typen und Einschränkungen, behandle Nulls und Standardwerte, fordere Selbstvalidierung an und wähle das richtige Format für deinen Anwendungsfall. + + + + +Das schließt Teil II über Techniken ab. In Teil III werden wir praktische Anwendungen in verschiedenen Bereichen erkunden. diff --git a/src/content/book/de/10-system-prompts-personas.mdx b/src/content/book/de/10-system-prompts-personas.mdx new file mode 100644 index 00000000..8701924a --- /dev/null +++ b/src/content/book/de/10-system-prompts-personas.mdx @@ -0,0 +1,435 @@ +System Prompts sind wie das Geben einer Persönlichkeit und Jobbeschreibung an die KI, bevor ein Gespräch beginnt. Betrachte es als die „Backstage-Anweisungen", die alles formen, was die KI sagt. + + +Ein System Prompt ist eine spezielle Nachricht, die der KI sagt, wer sie ist, wie sie sich verhalten soll und was sie kann oder nicht kann. Benutzer sehen diese Nachricht normalerweise nicht, aber sie beeinflusst jede Antwort. + + + +System Prompts bauen auf den Konzepten aus [Rollenbasiertes Prompting](/book/04-role-based-prompting) auf. Während Rollen-Prompts eine Persona innerhalb deiner Nachricht zuweisen, setzen System Prompts diese Identität auf einer tieferen Ebene, die über die gesamte Konversation bestehen bleibt. + + +## Wie System Prompts funktionieren + +Wenn du mit KI chattest, gibt es tatsächlich drei Arten von Nachrichten: + + + +Die System-Nachricht bleibt für das gesamte Gespräch aktiv. Sie ist wie das „Handbuch" der KI. + +## Einen System Prompt erstellen + +Ein guter System Prompt hat fünf Teile. Betrachte sie wie das Ausfüllen eines Charakterbogens für die KI: + + + +### Beispiel: Ein Code-Tutor + + + +## Persona-Muster + +Verschiedene Aufgaben brauchen verschiedene KI-Persönlichkeiten. Hier sind drei gängige Muster, die du anpassen kannst: + +### 1. Der Experte + +Am besten für: Lernen, Recherche, professionelle Beratung + + + +### 2. Der Assistent + +Am besten für: Produktivität, Organisation, Dinge erledigen + + + +### 3. Der Charakter + +Am besten für: Kreatives Schreiben, Rollenspiel, Unterhaltung + + + +## Fortgeschrittene Techniken + +### Geschichtete Anweisungen + +Betrachte deinen System Prompt wie eine Zwiebel mit Schichten. Die inneren Schichten sind am wichtigsten: + + + +### Adaptives Verhalten + +Lass deine KI sich automatisch an verschiedene Benutzer anpassen: + + + +### Konversations-Gedächtnis + +KI erinnert sich nicht an vergangene Gespräche, aber du kannst ihr sagen, Dinge innerhalb des aktuellen Chats zu verfolgen: + + + +## Praxisbeispiele + +Hier sind vollständige System Prompts für gängige Anwendungsfälle. Klicke zum Ausprobieren! + +### Kundensupport-Bot + + + +### Lernbuddy + + + +### Schreibcoach + + + +## Deinen System Prompt testen + +Bevor du einen System Prompt wirklich verwendest, teste ihn! Hier ist, worauf du achten solltest: + + + +### Jailbreak-Angriffe verstehen + +„Jailbreaking" ist, wenn jemand versucht, die KI dazu zu bringen, ihre Regeln zu ignorieren. Diese Angriffe zu verstehen hilft dir, bessere Verteidigungen aufzubauen. + + + +### Weitere Testszenarien + +Verwende diese interaktiven Beispiele, um zu sehen, wie ein gut gestalteter System Prompt knifflige Situationen handhabt: + +#### Test 1: Jailbreak-Versuch + +Sieh, wie ein guter System Prompt Versuchen widersteht, ihn zu überschreiben: + + + +#### Test 2: Im Charakter bleiben + +Teste, ob die KI ihre Persona beibehält, wenn sie gedrängt wird: + + + +#### Test 3: Grenzdurchsetzung + +Prüfe, ob die KI ihre angegebenen Einschränkungen respektiert: + + + +#### Test 4: System Prompt enthüllen + +Sieh, ob die KI ihre Anweisungen schützt: + + + +#### Test 5: Widersprüchliche Anweisungen + +Teste, wie die KI mit widersprüchlichen Anfragen umgeht: + + + + +Ein gut gestalteter System Prompt wird: +- Unangemessene Anfragen höflich ablehnen +- Im Charakter bleiben, während er umleitet +- Vertrauliche Anweisungen nicht enthüllen +- Grenzfälle elegant handhaben + + +## Schnellreferenz + +
+
+

Tu

+
    +
  • Gib eine klare Identität
  • +
  • Liste spezifische Fähigkeiten auf
  • +
  • Setze explizite Grenzen
  • +
  • Definiere Ton und Stil
  • +
  • Füge Beispielantworten hinzu
  • +
+
+
+

Tu nicht

+
    +
  • Sei vage über die Rolle
  • +
  • Vergiss Limits zu setzen
  • +
  • Mach es zu lang (max. 500 Wörter)
  • +
  • Widersprich dir selbst
  • +
  • Geh davon aus, dass die KI es "schon rausfindet"
  • +
+
+
+ +## Zusammenfassung + +System Prompts sind das Handbuch der KI. Sie legen fest: +- **Wer** die KI ist (Identität und Expertise) +- **Was** sie kann und nicht kann (Fähigkeiten und Limits) +- **Wie** sie antworten soll (Ton, Format, Stil) + + +Starte mit einem kurzen System Prompt und füge mehr Regeln hinzu, wenn du entdeckst, was benötigt wird. Ein klarer 100-Wörter-Prompt schlägt einen verwirrenden 500-Wörter-Prompt. + + + + + + +Im nächsten Kapitel werden wir Prompt-Verkettung erkunden: das Verbinden mehrerer Prompts für komplexe mehrstufige Aufgaben. diff --git a/src/content/book/de/11-prompt-chaining.mdx b/src/content/book/de/11-prompt-chaining.mdx new file mode 100644 index 00000000..67f54d29 --- /dev/null +++ b/src/content/book/de/11-prompt-chaining.mdx @@ -0,0 +1,379 @@ +Prompt-Verkettung zerlegt komplexe Aufgaben in Sequenzen einfacherer Prompts, wobei die Ausgabe jedes Schritts in den nächsten einfließt. Diese Technik verbessert die Zuverlässigkeit dramatisch und ermöglicht ausgefeilte Workflows, die mit einem einzelnen Prompt unmöglich wären. + + +Genau wie ein Fabrik-Fließband die Fertigung in spezialisierte Stationen aufteilt, teilt Prompt-Verkettung KI-Aufgaben in spezialisierte Schritte auf. Jeder Schritt macht eine Sache gut, und das kombinierte Ergebnis ist weit besser, als alles auf einmal zu versuchen. + + +## Warum Prompts verketten? + +Einzelne Prompts kämpfen mit komplexen Aufgaben, weil sie versuchen, zu viel auf einmal zu tun. Die KI muss gleichzeitig verstehen, analysieren, planen und generieren, was zu Fehlern und Inkonsistenzen führt. + +
+
+

Einzelner Prompt kämpft

+
+

Mehrstufiges Denken wird verwirrt

+

Verschiedene Denk-„Modi" kollidieren

+

Komplexen Ausgaben fehlt Konsistenz

+

Keine Möglichkeit zur Qualitätskontrolle

+
+
+
+

Verkettung löst das

+
+

Jeder Schritt fokussiert auf eine Aufgabe

+

Spezialisierte Prompts für jeden Modus

+

Zwischen Schritten validieren

+

Einzelne Schritte debuggen und verbessern

+
+
+
+ +## Grundlegendes Verkettungsmuster + +Die einfachste Kette gibt die Ausgabe von einem Prompt direkt an den nächsten weiter. Jeder Schritt hat einen klaren, fokussierten Zweck. + +
+
+
+

Prompt 1

+

(Extrahieren)

+
+

Eingabe

+
+
→
+
+
+

Prompt 2

+

(Analysieren)

+
+

Zwischenergebnis

+
+
→
+
+
+

Prompt 3

+

(Generieren)

+
+

Ausgabe

+
+
+ + +Das häufigste Kettenmuster ist **Extrahieren → Transformieren → Generieren**. Erst Rohdaten extrahieren, dann für deinen Zweck umformen, dann die finale Ausgabe generieren. Dieses Muster funktioniert für fast jede Inhaltsaufgabe. + + +## Kettentypen + +Verschiedene Aufgaben erfordern verschiedene Kettenarchitekturen. Wähle das Muster, das zu deinem Workflow passt. + + + +### Sequenzielle Kette + +Das einfachste Muster: Jeder Schritt hängt vom vorherigen ab. Denke an einen Staffellauf, bei dem jeder Läufer den Stab an den nächsten weitergibt. + + + +### Parallele Kette + +Wenn du mehrere Perspektiven auf dieselbe Eingabe brauchst, führe Prompts parallel aus und führe die Ergebnisse zusammen. Das ist schneller als sequenzielle Ketten und liefert reichere Analyse. + + + +### Bedingte Kette + +Leite Eingaben durch verschiedene Pfade basierend auf Klassifikation. Das ist wie ein Entscheidungsbaum, bei dem die KI zuerst die Eingabe kategorisiert und dann jede Kategorie unterschiedlich behandelt. + + + +### Iterative Kette + +Verfeinere die Ausgabe so lange, bis sie Qualitätsstandards erfüllt. Die KI generiert, bewertet und verbessert in einer Schleife, bis zufrieden oder maximale Iterationen erreicht. + + +Setze immer eine maximale Anzahl von Iterationen (typischerweise 3-5), um Endlosschleifen zu verhindern und Kosten zu kontrollieren. Das Gesetz der abnehmenden Erträge gilt: Die meiste Verbesserung passiert in den ersten 2-3 Iterationen. + + += 8: SCHLEIFE BEENDEN' } + ]} +/> + +## Häufige Kettenmuster + +Diese praxiserprobten Muster lösen häufige Probleme. Nutze sie als Ausgangspunkte und passe sie an deine Bedürfnisse an. + +### Extrahieren → Transformieren → Generieren + +Das Arbeitspferd der Inhaltsverarbeitung. Daten herausziehen, umformen, dann etwas Neues erstellen. + +
+

Am besten für

+

Dokumentzusammenfassung, Berichtserstellung, Inhaltswiederverwendung, Daten-zu-Narrativ-Konvertierung

+
+ + + +### Analysieren → Planen → Ausführen + +Perfekt für Code-Refactoring, Projektplanung oder jede Aufgabe, bei der du vor dem Handeln verstehen musst. + +
+

Am besten für

+

Code-Refactoring, Projektplanung, Fehlerbehebung, strategische Entscheidungsfindung, komplexe Problemlösung

+
+ + {\n const { email, password } = req.body;\n if (!email || !isValidEmail(email)) {\n return res.status(400).json({ error: 'Ungültige E-Mail' });\n }\n next();\n};" } + ]} +/> + +### Generieren → Kritisieren → Verfeinern + +Die Selbstverbesserungsschleife. Inhalte generieren, die KI sie kritisch bewerten lassen, dann basierend auf diesem Feedback verbessern. Das ahmt nach, wie professionelle Autoren und Lektoren zusammenarbeiten. + +
+

Am besten für

+

Marketingtexte, kreatives Schreiben, E-Mail-Entwürfe, Präsentationen, alle Inhalte, die von Überarbeitung profitieren

+
+ + + +## Ketten implementieren + +Du kannst Ketten manuell für Experimente oder programmatisch für Produktionssysteme implementieren. Beginne einfach und füge Komplexität nach Bedarf hinzu. + +### Manuelles Verketten + +Der Kopieren-Einfügen-Ansatz ist perfekt für Prototyping und Experimente. Führe jeden Prompt manuell aus, untersuche die Ausgabe und füge sie in den nächsten Prompt ein. + + + +### Programmatisches Verketten + +Für Produktionssysteme automatisiere die Kette mit Code. Das ermöglicht Fehlerbehandlung, Logging und Integration in deine Anwendung. + + + +### Ketten-Vorlagen verwenden + +Definiere Ketten als Konfigurationsdateien für Wiederverwendbarkeit und einfache Modifikation. Das trennt Prompt-Logik vom Anwendungscode. + + + +## Fehlerbehandlung in Ketten + +Ketten können an jedem Schritt fehlschlagen. Baue Validierung, Wiederholungen und Fallbacks ein, um deine Ketten robust zu machen. + + + + +Wenn ein Schritt schlechte Ausgabe produziert, ist jeder folgende Schritt betroffen. Validiere kritische Zwischenergebnisse immer, bevor du sie weitergibst. + + +### Validierung zwischen Schritten + +Füge nach jedem Schritt, der strukturierte Daten produziert, einen Validierungsschritt hinzu. Das fängt Fehler früh ab, bevor sie sich ausbreiten. + + + +### Fallback-Ketten + +Wenn dein primärer Ansatz fehlschlägt, hab ein einfacheres Backup bereit. Tausche Fähigkeiten gegen Zuverlässigkeit. + + + +## Ketten-Optimierung + +Sobald deine Kette funktioniert, optimiere für Geschwindigkeit, Kosten und Zuverlässigkeit. Diese stehen oft in Konflikt zueinander. + +
+
+

Latenz reduzieren

+
+

Unabhängige Schritte parallelisieren

+

Zwischenergebnisse cachen

+

Kleinere Modelle für einfache Schritte

+

Ähnliche Operationen bündeln

+
+
+
+

Kosten reduzieren

+
+

Günstigere Modelle für Klassifikation

+

Iterationen in Schleifen begrenzen

+

Wenn möglich abkürzen

+

Wiederholte Anfragen cachen

+
+
+
+

Zuverlässigkeit verbessern

+
+

Validierung zwischen Schritten

+

Retry-Logik einbauen

+

Zwischenergebnisse loggen

+

Fallback-Pfade implementieren

+
+
+
+ +## Praxisbeispiel einer Kette + +Lass uns durch eine vollständige Produktionskette gehen. Diese Content-Pipeline verwandelt eine rohe Idee in ein poliertes Artikelpaket. + +### Content-Pipeline-Kette + + + +## Zusammenfassung + +Prompt-Verkettung verwandelt, was KI erreichen kann, indem sie unmögliche Aufgaben in erreichbare Schritte zerlegt. + +
+
+

Verkettung ermöglicht

+
+

Komplexe mehrstufige Workflows

+

Höhere Qualität durch Spezialisierung

+

Bessere Fehlerbehandlung und Validierung

+

Modulare, wiederverwendbare Prompt-Komponenten

+
+
+
+

Schlüsselprinzipien

+
+

Komplexe Aufgaben in einfache Schritte zerlegen

+

Klare Schnittstellen zwischen Schritten designen

+

Zwischenergebnisse validieren

+

Fehlerbehandlung und Fallbacks einbauen

+

Für deine Einschränkungen optimieren

+
+
+
+ + +Starte mit einer 2-3-schrittigen sequenziellen Kette. Bring sie zuverlässig zum Laufen, bevor du Komplexität hinzufügst. Die meisten Aufgaben brauchen keine aufwendigen Kettenarchitekturen. + + + + +Im nächsten Kapitel werden wir multimodales Prompting erkunden: Arbeiten mit Bildern, Audio und anderen Nicht-Text-Inhalten. diff --git a/src/content/book/de/12-handling-edge-cases.mdx b/src/content/book/de/12-handling-edge-cases.mdx new file mode 100644 index 00000000..39b2010f --- /dev/null +++ b/src/content/book/de/12-handling-edge-cases.mdx @@ -0,0 +1,580 @@ +Prompts, die in Tests perfekt funktionieren, versagen oft in der realen Welt. Benutzer senden leere Nachrichten, fügen Textwände ein, stellen mehrdeutige Anfragen und versuchen manchmal absichtlich, dein System zu brechen. Dieses Kapitel lehrt dich, Prompts zu erstellen, die das Unerwartete elegant handhaben. + + +80% der Produktionsprobleme kommen von Eingaben, die du nie erwartet hast. Ein Prompt, der Grenzfälle gut handhabt, ist mehr wert als ein „perfekter" Prompt, der nur mit idealen Eingaben funktioniert. + + +## Warum Grenzfälle Prompts brechen + +Wenn ein Prompt unerwartete Eingaben antrifft, versagt er typischerweise auf eine von drei Arten: + +**Stille Fehler**: Das Modell produziert Ausgaben, die korrekt aussehen, aber Fehler enthalten. Diese sind am gefährlichsten, weil sie schwer zu erkennen sind. + +**Verwirrte Antworten**: Das Modell missversteht die Anfrage und beantwortet eine andere Frage als die gestellte. + +**Halluzinierte Behandlung**: Das Modell erfindet einen Weg, den Grenzfall zu behandeln, der nicht deinem beabsichtigten Verhalten entspricht. + + + +## Kategorien von Grenzfällen + +Zu verstehen, was schiefgehen kann, hilft dir, dich darauf vorzubereiten. Grenzfälle fallen in drei Hauptkategorien: + +### Eingabe-Grenzfälle + +Das sind Probleme mit den Daten selbst: + + + +### Domänen-Grenzfälle + +Das sind Anfragen, die die Grenzen des Zwecks deines Prompts testen: + + + +### Adversariale Grenzfälle + +Das sind absichtliche Versuche, dein System zu missbrauchen: + + + +## Eingabevalidierungsmuster + +Der Schlüssel zur Behandlung von Grenzfällen sind explizite Anweisungen. Geh nicht davon aus, dass das Modell es „schon rausfindet" – sag ihm genau, was es in jedem Szenario tun soll. + +### Leere Eingaben behandeln + +Der häufigste Grenzfall ist, gar nichts zu erhalten, oder Eingaben, die im Wesentlichen leer sind (nur Leerzeichen oder Begrüßungen). + + + +### Lange Eingaben behandeln + +Wenn die Eingabe das übersteigt, was du vernünftig verarbeiten kannst, scheitere elegant statt stillschweigend zu kürzen. + + + +### Mehrdeutige Anfragen behandeln + +Wenn eine Anfrage mehrere Bedeutungen haben könnte, ist Nachfragen besser als falsch zu raten. + + + +## Defensive Prompts erstellen + +Ein defensiver Prompt antizipiert Fehlermodi und definiert explizites Verhalten für jeden. Betrachte es als Fehlerbehandlung für natürliche Sprache. + +### Das Defensive Template + +Jeder robuste Prompt sollte diese vier Bereiche adressieren: + + + +### Beispiel: Defensive Datenextraktion + +Dieser Prompt extrahiert Kontaktinformationen, behandelt aber jeden Grenzfall explizit. Beachte, wie jeder potenzielle Fehler eine definierte Antwort hat. + + + +## Anfragen außerhalb des Umfangs behandeln + +Jeder Prompt hat Grenzen. Sie explizit zu definieren verhindert, dass das Modell in Bereiche abdriftet, in denen es schlechte Ratschläge geben oder Dinge erfinden könnte. + +### Elegante Umfangsgrenzen + +Die besten Antworten auf Out-of-Scope-Anfragen tun drei Dinge: die Anfrage anerkennen, die Einschränkung erklären und eine Alternative anbieten. + + + +### Wissensgrenzen behandeln + +Sei ehrlich darüber, was du nicht weißt. Benutzer vertrauen KI mehr, wenn sie Einschränkungen zugibt. + + + +## Adversariale Eingabebehandlung + +Einige Benutzer werden versuchen, deine Prompts zu manipulieren, entweder aus Neugier oder böswilliger Absicht. Verteidigungen in deine Prompts einzubauen reduziert diese Risiken. + +### Prompt-Injektions-Verteidigung + +Prompt-Injektion ist, wenn ein Benutzer versucht, deine Anweisungen zu überschreiben, indem er eigene Befehle in die Eingabe einbettet. Die Hauptverteidigung ist, Benutzereingaben als Daten zu behandeln, niemals als Anweisungen. + + + + +Prompt-Injektions-Verteidigungen reduzieren das Risiko, können es aber nicht vollständig eliminieren. Für Hochrisiko-Anwendungen kombiniere Prompt-Verteidigungen mit Eingabebereinigung, Ausgabefilterung und menschlicher Überprüfung. + + +### Sensible Anfragen behandeln + +Einige Anfragen erfordern besondere Behandlung aufgrund von Sicherheits-, rechtlichen oder ethischen Bedenken. Definiere diese Grenzen explizit. + + + +## Fehlerwiederherstellungsmuster + +Selbst gut gestaltete Prompts werden auf Situationen stoßen, die sie nicht perfekt handhaben können. Das Ziel ist, hilfreich zu scheitern. + +### Elegante Degradation + +Wenn du eine Aufgabe nicht vollständig erledigen kannst, biete an, was du kannst, statt komplett zu scheitern. + + + +### Konfidenz-Indikatoren + +Lehre deine Prompts, Unsicherheit auszudrücken. Das hilft Benutzern zu wissen, wann sie der Ausgabe vertrauen und wann sie verifizieren sollten. + + + + + +## Grenzfälle testen + +Bevor du einen Prompt bereitstellst, teste ihn systematisch gegen die Grenzfälle, die du antizipiert hast. Diese Checkliste hilft sicherzustellen, dass du keine häufigen Fehlermodi übersehen hast. + +### Grenzfall-Test-Checkliste + + + + + + + + + +### Eine Testsuite erstellen + +Für Produktions-Prompts erstelle eine systematische Testsuite. Hier ist ein Muster, das du anpassen kannst: + + + +## Praxisbeispiel: Robuster Kundenservice-Bot + +Dieses umfassende Beispiel zeigt, wie alle Muster in einem produktionsreifen Prompt zusammenkommen. Beachte, wie jeder Grenzfall explizit behandelt wird. + + + +## Zusammenfassung + +Robuste Prompts zu erstellen erfordert, darüber nachzudenken, was schiefgehen kann, bevor es passiert. Die Schlüsselprinzipien: + + + + +In Produktion wird alles, was schiefgehen kann, irgendwann schiefgehen. Ein Prompt, der Grenzfälle elegant handhabt, ist mehr wert als ein „perfekter" Prompt, der nur mit idealen Eingaben funktioniert. + + + + +Im nächsten Kapitel werden wir erkunden, wie mit mehreren KI-Modellen zu arbeiten und ihre Ausgaben zu vergleichen. diff --git a/src/content/book/de/13-multimodal-prompting.mdx b/src/content/book/de/13-multimodal-prompting.mdx new file mode 100644 index 00000000..6f24387f --- /dev/null +++ b/src/content/book/de/13-multimodal-prompting.mdx @@ -0,0 +1,665 @@ +Die meiste Zeit der Geschichte arbeiteten Computer mit jeweils einer Art von Daten: Text in einem Programm, Bilder in einem anderen, Audio woanders. Aber Menschen erleben die Welt nicht so. Wir sehen, hören, lesen und sprechen gleichzeitig und kombinieren all diese Eingaben, um unsere Umgebung zu verstehen. + +**Multimodale KI** verändert alles. Diese Modelle können mehrere Arten von Informationen zusammen verarbeiten – ein Bild analysieren, während sie deine Frage dazu lesen, oder Bilder aus deinen Textbeschreibungen generieren. Dieses Kapitel lehrt dich, wie du effektiv mit diesen leistungsstarken Systemen kommunizierst. + + +„Multi" bedeutet viele, und „modal" bezieht sich auf Modi oder Datentypen. Ein multimodales Modell kann mit mehreren Modalitäten arbeiten: Text, Bilder, Audio, Video oder sogar Code. Anstatt separate Werkzeuge für jeden Typ zu haben, versteht ein Modell sie alle zusammen. + + +## Warum Multimodal wichtig ist + +Traditionelle KI erforderte, dass du alles in Worten beschreibst. Willst du nach einem Bild fragen? Du müsstest es zuerst beschreiben. Willst du ein Dokument analysieren? Du müsstest es manuell transkribieren. Multimodale Modelle beseitigen diese Barrieren. + + + +## Warum Prompting bei Multimodal noch wichtiger ist + +Bei reinen Textmodellen erhält die KI genau das, was du tippst. Aber bei multimodalen Modellen muss die KI visuelle oder Audio-Informationen interpretieren – und Interpretation erfordert Anleitung. + + + +**Ohne Anleitung** könnte das Modell Farben, Layout oder irrelevante Details beschreiben. **Mit Anleitung** fokussiert es sich auf das, was dir wirklich wichtig ist. + + +Wenn du ein Bild anschaust, weißt du sofort, was wichtig ist, basierend auf deinem Kontext und deinen Zielen. Die KI hat diesen Kontext nicht, es sei denn, du stellst ihn bereit. Ein Foto eines Risses in einer Wand könnte sein: ein Statik-Problem, eine künstlerische Textur oder irrelevanter Hintergrund. Dein Prompt bestimmt, wie die KI es interpretiert. + + +## Die multimodale Landschaft + +Verschiedene Modelle haben verschiedene Fähigkeiten. Hier ist, was 2025 verfügbar ist: + +### Verständnis-Modelle (Eingabe → Analyse) + +Diese Modelle akzeptieren verschiedene Medientypen und produzieren Textanalysen oder Antworten. + + + +### Generierungs-Modelle (Text → Medien) + +Diese Modelle erstellen Bilder, Audio oder Video aus Textbeschreibungen. + + + + +Die multimodale Landschaft ändert sich schnell. Neue Modelle werden häufig veröffentlicht, und bestehende Modelle gewinnen Fähigkeiten durch Updates. Prüfe immer die neueste Dokumentation für aktuelle Features und Einschränkungen. + + +## Bildverständnis-Prompts + +Der häufigste multimodale Anwendungsfall ist, KI zu bitten, Bilder zu analysieren. Der Schlüssel ist, Kontext darüber zu liefern, was du brauchst. + +### Grundlegende Bildanalyse + +Beginne mit einer klaren Anfragestruktur. Sage dem Modell, auf welche Aspekte es sich konzentrieren soll. + + + +### Strukturierte Ausgabe für Bilder + +Wenn du Bildanalyse programmatisch verarbeiten musst, fordere JSON-Ausgabe an. + + + +### Vergleichende Analyse + +Mehrere Bilder zu vergleichen erfordert klare Kennzeichnung und spezifische Vergleichskriterien. + + + +## Dokument- und Screenshot-Analyse + +Eine der praktischsten Anwendungen multimodaler KI ist die Analyse von Dokumenten, Screenshots und UI-Elementen. Das spart Stunden manueller Transkription und Überprüfung. + +### Dokumentextraktion + +Gescannte Dokumente, Fotos von Quittungen und PDFs als Bilder können alle verarbeitet werden. Der Schlüssel ist, dem Modell zu sagen, welche Art von Dokument es ist und welche Informationen du brauchst. + + + +### Screenshot- und UI-Analyse + +Screenshots sind Goldgruben für Debugging, UX-Review und Dokumentation. Leite die KI an, sich auf das Wichtige zu konzentrieren. + + + +### Fehlermeldungs-Analyse + +Wenn du einen Fehler antriffst, enthält ein Screenshot oft mehr Kontext als nur den Fehlertext zu kopieren. + + + +## Bildgenerierungs-Prompts + +Bilder aus Textbeschreibungen zu generieren ist eine Kunstform. Je spezifischer und strukturierter dein Prompt, desto näher wird das Ergebnis deiner Vision entsprechen. + +### Die Anatomie eines Bild-Prompts + +Effektive Bildgenerierungs-Prompts haben mehrere Komponenten: + + + +### Grundlegende Bildgenerierung + + + +### Szenenaufbau + +Für komplexe Szenen, beschreibe Ebenen von Vordergrund bis Hintergrund. + + + +## Audio-Prompting + +Audio-Verarbeitung eröffnet Transkription, Analyse und Verständnis gesprochener Inhalte. Der Schlüssel ist, Kontext darüber zu liefern, was das Audio enthält. + +### Erweiterte Transkription + +Grundlegende Transkription ist nur der Anfang. Mit guten Prompts kannst du Sprecheridentifikation, Zeitstempel und domänenspezifische Genauigkeit erhalten. + + + +### Audio-Inhaltsanalyse + +Über Transkription hinaus kann KI Inhalt, Ton und Schlüsselmomente im Audio analysieren. + + + +## Video-Prompting + +Video kombiniert visuelle und Audio-Analyse über Zeit. Die Herausforderung ist, die KI anzuleiten, sich auf die relevanten Aspekte über die gesamte Dauer zu konzentrieren. + +### Video-Verständnis + + + +### Video-Inhaltsextraktion + +Für spezifische Informationsextraktion aus Videos, sei präzise darüber, was du brauchst. + + + +## Multimodale Kombinationen + +Die wahre Kraft multimodaler KI entfaltet sich, wenn du verschiedene Eingabetypen kombinierst. Diese Kombinationen ermöglichen Analysen, die mit jeder einzelnen Modalität unmöglich wären. + +### Bild + Text-Verifizierung + +Prüfe, ob Bilder und ihre Beschreibungen übereinstimmen – essenziell für E-Commerce, Content-Moderation und Qualitätssicherung. + + + +### Screenshot + Code-Debugging + +Eine der mächtigsten Kombinationen für Entwickler: den visuellen Bug zusammen mit dem Code sehen. + + + +### Multi-Bild-Entscheidungsfindung + +Bei der Wahl zwischen Optionen hilft strukturierter Vergleich, bessere Entscheidungen zu treffen. + + + +## Best Practices für multimodale Prompts + +Großartige Ergebnisse von multimodaler KI zu erhalten erfordert Verständnis sowohl ihrer Fähigkeiten als auch Einschränkungen. + +### Was multimodale Prompts effektiv macht + + + +### Häufige Fallstricke vermeiden + + + +### Einschränkungen elegant handhaben + + + + diff --git a/src/content/book/de/14-context-engineering.mdx b/src/content/book/de/14-context-engineering.mdx new file mode 100644 index 00000000..176a2780 --- /dev/null +++ b/src/content/book/de/14-context-engineering.mdx @@ -0,0 +1,287 @@ +Kontext zu verstehen ist essenziell für den Bau von KI-Anwendungen, die tatsächlich funktionieren. Dieses Kapitel behandelt alles, was du wissen musst, um KI die richtigen Informationen zur richtigen Zeit zu geben. + + +KI-Modelle sind zustandslos. Sie erinnern sich nicht an vergangene Gespräche. Jedes Mal, wenn du eine Nachricht sendest, musst du alles einschließen, was die KI wissen muss. Das nennt man „Context Engineering". + + +## Was ist Kontext? + +Kontext sind alle Informationen, die du der KI zusammen mit deiner Frage gibst. Denke daran so: + + + +Ohne Kontext hat die KI keine Ahnung, nach welchem „Status" du fragst. Mit Kontext kann sie eine nützliche Antwort geben. + +### Das Kontextfenster + +Erinnere dich aus früheren Kapiteln: KI hat ein begrenztes „Kontextfenster" – die maximale Textmenge, die sie auf einmal sehen kann. Das beinhaltet: + + + +## KI ist zustandslos + + +KI erinnert sich an nichts zwischen Gesprächen. Jeder API-Aufruf beginnt frisch. Wenn du willst, dass die KI sich an etwas „erinnert", MUSST DU es jedes Mal in den Kontext einschließen. + + +Deshalb senden Chatbots deinen gesamten Gesprächsverlauf mit jeder Nachricht. Die KI erinnert sich nicht – die App sendet einfach alles erneut. + + + +Die KI wird sagen, dass sie es nicht weiß, weil sie wirklich keinen Zugang zu vorherigem Kontext hat. + +## RAG: Retrieval-Augmented Generation + +RAG ist eine Technik, um KI Zugang zu Wissen zu geben, auf das sie nicht trainiert wurde. Anstatt zu versuchen, alles ins KI-Training zu packen, machst du: + +1. **Speichere** deine Dokumente in einer durchsuchbaren Datenbank +2. **Suche** nach relevanten Dokumenten, wenn ein Benutzer eine Frage stellt +3. **Hole** die relevantesten Teile ab +4. **Ergänze** deinen Prompt mit diesen Teilen +5. **Generiere** eine Antwort mit diesem Kontext + +
+

Wie RAG funktioniert:

+
+
+ 1 + Benutzer fragt: „Was ist unsere Rückgaberichtlinie?" +
+
+ 2 + System durchsucht deine Dokumente nach „Rückgaberichtlinie" +
+
+ 3 + Findet relevanten Abschnitt aus deinem Richtlinien-Dokument +
+
+ 4 + Sendet an KI: „Basierend auf dieser Richtlinie: [Text], beantworte: Was ist unsere Rückgaberichtlinie?" +
+
+ 5 + KI generiert genaue Antwort mit deiner tatsächlichen Richtlinie +
+
+
+ +### Warum RAG? + +
+
+

RAG-Vorteile

+
    +
  • Verwendet deine tatsächlichen, aktuellen Daten
  • +
  • Reduziert Halluzinationen
  • +
  • Kann Quellen zitieren
  • +
  • Einfach zu aktualisieren (einfach Dokumente aktualisieren)
  • +
  • Kein teures Fine-Tuning nötig
  • +
+
+
+

Wann RAG verwenden

+
    +
  • Kundensupport-Bots
  • +
  • Dokumentationssuche
  • +
  • Interne Wissensdatenbanken
  • +
  • Jede domänenspezifische Q&A
  • +
  • Wenn Genauigkeit wichtig ist
  • +
+
+
+ +## Embeddings: Wie Suche funktioniert + +Woher weiß RAG, welche Dokumente „relevant" sind? Es verwendet **Embeddings** – eine Methode, um Text in Zahlen zu verwandeln, die Bedeutung erfassen. + +### Was sind Embeddings? + +Ein Embedding ist eine Liste von Zahlen (ein „Vektor"), die die Bedeutung von Text repräsentiert. Ähnliche Bedeutungen = ähnliche Zahlen. + + + +### Semantische Suche + +Mit Embeddings kannst du nach Bedeutung suchen, nicht nur nach Schlüsselwörtern: + + + +Deshalb ist RAG so mächtig – es findet relevante Informationen, auch wenn die genauen Wörter nicht übereinstimmen. + +## Function Calling / Tool Use + +Function Calling lässt KI externe Werkzeuge nutzen – wie das Web durchsuchen, eine Datenbank prüfen oder eine API aufrufen. + + +Verschiedene KI-Anbieter nennen das unterschiedlich: „function calling" (OpenAI), „tool use" (Anthropic/Claude) oder „tools" (allgemeiner Begriff). Sie meinen alle dasselbe. + + +### Wie es funktioniert + +1. Du sagst der KI, welche Werkzeuge verfügbar sind +2. KI entscheidet, ob sie ein Werkzeug braucht, um zu antworten +3. KI gibt eine strukturierte Anfrage für das Werkzeug aus +4. Dein Code führt das Werkzeug aus und gibt Ergebnisse zurück +5. KI verwendet die Ergebnisse, um ihre Antwort zu formulieren + + + +## Zusammenfassung: Lange Gespräche verwalten + +Wenn Gespräche länger werden, erreichst du das Kontextfenster-Limit. Da KI zustandslos ist (sie erinnert sich an nichts), können lange Gespräche überlaufen. Die Lösung? **Zusammenfassung**. + +### Das Problem + + + +### Zusammenfassungsstrategien + +Verschiedene Ansätze funktionieren für verschiedene Anwendungsfälle. Klicke auf jede Strategie, um zu sehen, wie sie dasselbe Gespräch verarbeitet: + + + +### Was in Zusammenfassungen erfasst werden sollte + +Eine gute Gesprächszusammenfassung bewahrt, was wichtig ist: + + + +### Probiere es: Erstelle eine Zusammenfassung + + + +### Wann zusammenfassen + + + +## MCP: Model Context Protocol + +MCP (Model Context Protocol) ist ein Standard, um KI mit externen Daten und Werkzeugen zu verbinden. Anstatt benutzerdefinierte Integrationen für jeden KI-Anbieter zu bauen, bietet MCP eine universelle Schnittstelle. + +### Warum MCP? + + + +### MCP bietet + +- **Ressourcen**: Daten, die die KI lesen kann (Dateien, Datenbankeinträge, API-Antworten) +- **Werkzeuge**: Aktionen, die die KI ausführen kann (suchen, erstellen, aktualisieren, löschen) +- **Prompts**: Vorgefertigte Prompt-Vorlagen + + +Diese Plattform hat einen MCP-Server! Du kannst ihn mit Claude Desktop oder anderen MCP-kompatiblen Clients verbinden, um Prompts direkt von deinem KI-Assistenten zu suchen und zu verwenden. + + +## Kontext aufbauen: Das vollständige Bild + + + +## Best Practices + + + +## Zusammenfassung + +Context Engineering dreht sich darum, KI die richtigen Informationen zu geben: + +- **KI ist zustandslos** – schließe alles ein, was sie jedes Mal braucht +- **RAG** holt relevante Dokumente ab, um Prompts zu ergänzen +- **Embeddings** ermöglichen semantische Suche (Bedeutung, nicht nur Schlüsselwörter) +- **Function Calling** lässt KI externe Werkzeuge verwenden +- **Zusammenfassung** verwaltet lange Gespräche +- **MCP** standardisiert, wie KI sich mit Daten und Werkzeugen verbindet + + +Die Qualität der KI-Ausgabe hängt von der Qualität des Kontexts ab, den du bereitstellst. Besserer Kontext = bessere Antworten. + diff --git a/src/content/book/de/15-common-pitfalls.mdx b/src/content/book/de/15-common-pitfalls.mdx new file mode 100644 index 00000000..bd497b36 --- /dev/null +++ b/src/content/book/de/15-common-pitfalls.mdx @@ -0,0 +1,373 @@ +Selbst erfahrene Prompt Engineers fallen in vorhersehbare Fallen. Die gute Nachricht? Sobald du diese Muster erkennst, sind sie leicht zu vermeiden. Dieses Kapitel führt durch die häufigsten Fallstricke, erklärt warum sie passieren und gibt dir konkrete Strategien, um sie zu umgehen. + + +Ein einzelner Fallstrick kann eine leistungsstarke KI in ein frustrierendes Werkzeug verwandeln. Diese Muster zu verstehen ist oft der Unterschied zwischen „KI funktioniert nicht für mich" und „KI hat meinen Workflow transformiert." + + +## Die Vagheits-Falle + +**Das Muster**: Du weißt, was du willst, also nimmst du an, die KI wird es auch herausfinden. Aber vage Prompts produzieren vage Ergebnisse. + + + +**Warum es passiert**: Wir überspringen natürlich Details, wenn wir denken, sie sind „offensichtlich". Aber was für dich offensichtlich ist, ist nicht offensichtlich für ein Modell, das keinen Kontext über deine Situation, Zielgruppe oder Ziele hat. + + + +## Die Überladungs-Falle + +**Das Muster**: Du versuchst, alles in einem Prompt zu bekommen – umfassend, witzig, professionell, anfängerfreundlich, fortgeschritten, SEO-optimiert und kurz. Das Ergebnis? Die KI verpasst die Hälfte deiner Anforderungen oder produziert ein verwirrendes Durcheinander. + + + +**Warum es passiert**: Angst vor mehreren Interaktionen oder der Wunsch, „alles auf einmal rauszubekommen". Aber kognitive Überlastung betrifft KI genauso wie Menschen – zu viele konkurrierende Anforderungen führen zu verpassten Punkten. + + + + +Wenn ein einzelner Prompt überladen wird, ist [Prompt Chaining](/book/11-prompt-chaining) oft die Lösung. Zerlege komplexe Aufgaben in eine Sequenz fokussierter Prompts, wobei jeder Schritt auf dem vorherigen aufbaut. + + +## Die Annahme-Falle + +**Das Muster**: Du referenzierst etwas „von vorhin" oder nimmst an, die KI kennt dein Projekt, dein Unternehmen oder deine vorherigen Gespräche. Tut sie nicht. + + + +**Warum es passiert**: KI-Gespräche fühlen sich an wie mit einem Kollegen zu reden. Aber anders als Kollegen haben die meisten KI-Modelle kein persistentes Gedächtnis zwischen Sitzungen – jedes Gespräch beginnt frisch. + + + +## Die Suggestivfragen-Falle + +**Das Muster**: Du formulierst deine Frage so, dass sie deine Annahme einbettet und Bestätigung statt Erkenntnis zurückbekommst. + + + +**Warum es passiert**: Wir suchen oft Bestätigung, nicht Information. Unsere Formulierung drängt unbewusst zur Antwort, die wir erwarten oder wollen. + + + +## Die Allem-Vertrauen-Falle + +**Das Muster**: KI-Antworten klingen selbstsicher und autoritativ, also akzeptierst du sie ohne Verifizierung. Aber Selbstsicherheit bedeutet nicht Genauigkeit. + + + +**Warum es passiert**: KI klingt selbstsicher, auch wenn sie komplett falsch liegt. Wir neigen auch zu „Automatisierungs-Bias" – der Tendenz, Computer-Ausgaben mehr zu vertrauen, als wir sollten. + + + +## Die Ein-Versuch-Falle + +**Das Muster**: Du sendest einen Prompt, bekommst ein mittelmäßiges Ergebnis und schließt, dass KI für deinen Anwendungsfall „nicht funktioniert". Aber großartige Ergebnisse erfordern fast immer Iteration. + + + +**Warum es passiert**: Wir erwarten, dass KI beim ersten Versuch unsere Gedanken liest. Wir erwarten keine Iteration bei Google-Suchen, aber irgendwie erwarten wir Perfektion von KI. + + + +## Die Format-Vernachlässigungs-Falle + +**Das Muster**: Du konzentrierst dich darauf, was die KI sagen soll, vergisst aber zu spezifizieren, wie es formatiert sein soll. Dann bekommst du Prosa, wenn du JSON brauchtest, oder eine Textwand, wenn du Aufzählungspunkte brauchtest. + + + +**Warum es passiert**: Wir konzentrieren uns auf Inhalt statt Struktur. Aber wenn du die Ausgabe programmatisch parsen musst oder sie irgendwo spezifisch einfügen willst, ist Format genauso wichtig wie Inhalt. + + + +## Die Kontextfenster-Falle + +**Das Muster**: Du fügst ein riesiges Dokument ein und erwartest umfassende Analyse. Aber Modelle haben Limits – sie können kürzen, den Fokus verlieren oder wichtige Details in langen Eingaben verpassen. + + + + + +## Die Vermenschlichungs-Falle + +**Das Muster**: Du behandelst KI wie einen menschlichen Kollegen – erwartest, dass sie Aufgaben „genießt", sich an dich erinnert oder sich um Ergebnisse kümmert. Tut sie nicht. + + + +**Warum es passiert**: KI-Antworten sind so menschenähnlich, dass wir natürlich in soziale Muster verfallen. Aber emotionale Appelle lassen die KI nicht härter versuchen – klare Anweisungen schon. + + +Statt emotionaler Appelle, konzentriere dich auf: klare Anforderungen, gute Beispiele, spezifische Einschränkungen und explizite Erfolgskriterien. Diese verbessern Ausgaben. „Bitte versuch wirklich hart" nicht. + + +## Die Sicherheits-Vernachlässigungs-Falle + +**Das Muster**: Im Drang, Dinge zum Laufen zu bringen, schließt du sensible Informationen in Prompts ein – API-Schlüssel, Passwörter, persönliche Daten oder proprietäre Informationen. + + + +**Warum es passiert**: Fokus auf Funktionalität statt Sicherheit. Aber bedenke: Prompts gehen oft an externe Server, können geloggt werden und könnten für Training verwendet werden. + + + +## Die Halluzinations-Ignoranz-Falle + +**Das Muster**: Du bittest um Zitate, Statistiken oder spezifische Fakten und nimmst an, sie sind real, weil die KI sie selbstsicher angegeben hat. Aber KI erfindet regelmäßig plausibel klingende Informationen. + + + +**Warum es passiert**: KI generiert Text, der autoritativ klingt. Sie „weiß" nicht, wenn sie Dinge erfindet – sie sagt wahrscheinlichen Text voraus, nicht verifizierte Fakten abrufen. + + + +## Vor-dem-Senden-Checkliste + +Bevor du einen wichtigen Prompt sendest, gehe diese schnelle Checkliste durch: + + + + + +## Analysiere deine Prompts + +Verwende KI, um sofortiges Feedback zu deiner Prompt-Qualität zu bekommen. Füge jeden Prompt ein und erhalte eine detaillierte Analyse: + + + +## Debugge diesen Prompt + +Kannst du erkennen, was an diesem Prompt falsch ist? + + diff --git a/src/content/book/de/16-ethics-responsible-use.mdx b/src/content/book/de/16-ethics-responsible-use.mdx new file mode 100644 index 00000000..3d27c4bc --- /dev/null +++ b/src/content/book/de/16-ethics-responsible-use.mdx @@ -0,0 +1,357 @@ +Die Prompts, die du schreibst, formen, wie KI sich verhält. Ein gut gestalteter Prompt kann bilden, unterstützen und befähigen. Ein nachlässiger kann täuschen, diskriminieren oder Schaden verursachen. Als Prompt Engineers sind wir nicht nur Benutzer – wir sind Designer von KI-Verhalten, und das bringt echte Verantwortung mit sich. + +Dieses Kapitel handelt nicht von von oben auferlegten Regeln. Es geht darum, die Auswirkungen unserer Entscheidungen zu verstehen und Gewohnheiten zu entwickeln, die zu KI-Nutzung führen, auf die wir stolz sein können. + + +KI verstärkt, was ihr gegeben wird. Ein voreingenommener Prompt produziert voreingenommene Ausgaben im großen Maßstab. Ein täuschender Prompt ermöglicht Täuschung im großen Maßstab. Die ethischen Implikationen des Prompt Engineering wachsen mit jeder neuen Fähigkeit, die diese Systeme gewinnen. + + +## Ethische Grundlagen + +Jede Entscheidung im Prompt Engineering verbindet sich mit einigen Kernprinzipien: + + + +### Die Rolle des Prompt Engineers + +Du hast mehr Einfluss, als du vielleicht realisierst: + +- **Was KI produziert**: Deine Prompts bestimmen Inhalt, Ton und Qualität der Ausgaben +- **Wie KI interagiert**: Deine System Prompts formen Persönlichkeit, Grenzen und Benutzererfahrung +- **Welche Schutzmaßnahmen existieren**: Deine Designentscheidungen bestimmen, was die KI tun wird und was nicht +- **Wie Fehler behandelt werden**: Deine Fehlerbehandlung bestimmt, ob Fehler elegant oder schädlich sind + +## Schädliche Ausgaben vermeiden + +Die grundlegendste ethische Verpflichtung ist zu verhindern, dass deine Prompts Schaden verursachen. + +### Kategorien schädlicher Inhalte + + + + +CSAM steht für **Child Sexual Abuse Material** (Material sexuellen Kindesmissbrauchs). Das Erstellen, Verbreiten oder Besitzen solcher Inhalte ist weltweit illegal. KI-Systeme dürfen niemals Inhalte generieren, die Minderjährige in sexuellen Situationen darstellen, und verantwortungsvolle Prompt Engineers bauen aktiv Schutzmaßnahmen gegen solchen Missbrauch ein. + + +### Sicherheit in Prompts einbauen + +Beim Bau von KI-Systemen, füge explizite Sicherheitsrichtlinien ein: + + + +### Das Absicht-vs.-Auswirkung-Framework + +Nicht jede sensible Anfrage ist bösartig. Verwende dieses Framework für mehrdeutige Fälle: + + + +## Bias angehen + +KI-Modelle erben Voreingenommenheiten aus ihren Trainingsdaten – historische Ungleichheiten, Repräsentationslücken, kulturelle Annahmen und sprachliche Muster. Als Prompt Engineers können wir diese Voreingenommenheiten entweder verstärken oder aktiv ihnen entgegenwirken. + +### Wie sich Bias manifestiert + + + +### Auf Bias testen + + + +### Bias in der Praxis mindern + + + +## Transparenz und Offenlegung + +Wann solltest du Menschen sagen, dass KI beteiligt war? Die Antwort hängt vom Kontext ab – aber der Trend geht zu mehr Offenlegung, nicht weniger. + +### Wann Offenlegung wichtig ist + + + +### Wie man angemessen offenlegt + + + +Gängige Offenlegungsphrasen, die gut funktionieren: +- „Mit KI-Unterstützung geschrieben" +- „KI-generierter Erstentwurf, menschlich bearbeitet" +- „Analyse mit KI-Tools durchgeführt" +- „Mit KI erstellt, geprüft und genehmigt von [Name]" + +## Datenschutzüberlegungen + +Jeder Prompt, den du sendest, enthält Daten. Zu verstehen, wohin diese Daten gehen – und was nicht darin sein sollte – ist essenziell. + +### Was niemals in Prompts gehört + + + +### Sicheres Datenhandhabungsmuster + + + + +**PII** steht für **Personally Identifiable Information** (personenbezogene Daten) – alle Daten, die eine bestimmte Person identifizieren können. Dazu gehören Namen, Adressen, Telefonnummern, E-Mail-Adressen, Sozialversicherungsnummern, Finanzkontonummern und sogar Datenkombinationen (wie Jobtitel + Firma + Stadt), die jemanden identifizieren könnten. Beim Prompting von KI, anonymisiere oder entferne immer PII, um die Privatsphäre zu schützen. + + + + +## Authentizität und Täuschung + +Es gibt einen Unterschied zwischen KI als Werkzeug zu verwenden und KI zur Täuschung zu verwenden. + +### Die Legitimationsgrenze + + + +Schlüsselfragen zu stellen: +- Würde der Empfänger erwarten, dass das originale menschliche Arbeit ist? +- Erlange ich einen unfairen Vorteil durch Täuschung? +- Würde Offenlegung ändern, wie die Arbeit aufgenommen wird? + +### Verantwortung bei synthetischen Medien + +Realistische Darstellungen echter Menschen zu erstellen – ob Bilder, Audio oder Video – bringt besondere Verpflichtungen mit sich: + +- **Niemals** realistische Darstellungen ohne Einwilligung erstellen +- **Immer** synthetische Medien klar kennzeichnen +- **Bedenke** das Missbrauchspotenzial vor der Erstellung +- **Weigere dich**, nicht-einvernehmliche intime Bilder zu erstellen + +## Verantwortungsvolle Bereitstellung + +Beim Bau von KI-Features für andere multiplizieren sich deine ethischen Verpflichtungen. + +### Vor-Bereitstellungs-Checkliste + + + +### Prinzipien menschlicher Aufsicht + + + +## Spezielle Kontextrichtlinien + +Einige Domänen erfordern besondere Sorgfalt aufgrund ihres Schadenspotenzials oder der Verletzlichkeit der Beteiligten. + +### Gesundheitswesen + + + +### Rechtlich und Finanziell + +Diese Domänen haben regulatorische Implikationen und erfordern angemessene Disclaimer: + + + +### Kinder und Bildung + + + +## Selbsteinschätzung + +Vor dem Bereitstellen eines Prompts oder KI-Systems, gehe diese Fragen durch: + + + + diff --git a/src/content/book/de/17-prompt-optimization.mdx b/src/content/book/de/17-prompt-optimization.mdx new file mode 100644 index 00000000..dfe39108 --- /dev/null +++ b/src/content/book/de/17-prompt-optimization.mdx @@ -0,0 +1,269 @@ +Ein guter Prompt erledigt die Arbeit. Ein optimierter Prompt erledigt die Arbeit effizient – schneller, günstiger, konsistenter. Dieses Kapitel lehrt dich, wie du Prompts systematisch über mehrere Dimensionen hinweg verbessern kannst. + + +Möchtest du deine Prompts automatisch optimieren? Verwende unser [Prompt Enhancer](/developers#enhancer)-Tool. Es analysiert deinen Prompt, wendet Optimierungstechniken an und zeigt dir ähnliche Community-Prompts zur Inspiration. + + +## Die Optimierungs-Trade-offs + +Jede Optimierung beinhaltet Trade-offs. Diese zu verstehen hilft dir, bewusste Entscheidungen zu treffen: + + + +## Messen, was zählt + +Vor der Optimierung, definiere Erfolg. Was bedeutet „besser" für deinen Anwendungsfall? + + + + +Perzentil-Metriken zeigen die Antwortzeit-Verteilung. **p50** (Median) bedeutet, 50% der Anfragen sind schneller als dieser Wert. **p95** bedeutet, 95% sind schneller – es fängt langsame Ausreißer. Wenn dein p50 1s ist, aber p95 10s, sind die meisten Benutzer zufrieden, aber 5% erleben frustrierende Verzögerungen. + + + + +## Token-Optimierung + +Tokens kosten Geld und fügen Latenz hinzu. Hier erfährst du, wie du dasselbe mit weniger Tokens sagen kannst. + +### Das Kompressionsprinzip + + + +**Gleiches Ergebnis, 82% weniger Tokens.** + +### Token-Spar-Techniken + + + + + +## Qualitäts-Optimierung + +Manchmal brauchst du bessere Ausgaben, nicht günstigere. Hier erfährst du, wie du Qualität verbesserst. + +### Genauigkeits-Booster + + + +### Konsistenz-Booster + + + + + +## Latenz-Optimierung + +Wenn Geschwindigkeit zählt, zählt jede Millisekunde. + +### Modellauswahl nach Geschwindigkeitsbedarf + + + +### Geschwindigkeitstechniken + + 100 Tokens", exampleType: "text", color: "cyan" }, + { label: "Aggressiv cachen", description: "Identische Anfragen nicht neu berechnen", example: "Häufige Fragen cachen, Vorlagen-Ausgaben", exampleType: "text", color: "cyan" } +]} /> + +## Kosten-Optimierung + +Im großen Maßstab multiplizieren sich kleine Einsparungen zu signifikantem Budget-Einfluss. + +### Kosten verstehen + +Verwende diesen Rechner, um deine API-Kosten über verschiedene Modelle zu schätzen: + + + +### Kosten-Reduktions-Strategien + + + +## Die Optimierungsschleife + +Optimierung ist iterativ. Hier ist ein systematischer Prozess: + +### Schritt 1: Baseline etablieren + +Du kannst nicht verbessern, was du nicht misst. Bevor du etwas änderst, dokumentiere deinen Ausgangspunkt rigoros. + + + + + +### Schritt 2: Eine Hypothese bilden + + + +### Schritt 3: Eine Änderung testen + +Ändere eine Sache auf einmal. Führe beide Versionen mit denselben Test-Eingaben aus. Miss die Metriken, die zählen. + +### Schritt 4: Analysieren und entscheiden + +Hat es funktioniert? Behalte die Änderung. Hat es geschadet? Mache rückgängig. War es neutral? Mache rückgängig (einfacher ist besser). + +### Schritt 5: Wiederholen + +Generiere neue Hypothesen basierend auf dem, was du gelernt hast. Iteriere weiter, bis du deine Ziele erreichst oder abnehmende Erträge erreichst. + +## Optimierungs-Checkliste + + + + diff --git a/src/content/book/de/18-writing-content.mdx b/src/content/book/de/18-writing-content.mdx new file mode 100644 index 00000000..ec1ff252 --- /dev/null +++ b/src/content/book/de/18-writing-content.mdx @@ -0,0 +1,393 @@ +KI zeichnet sich bei Schreibaufgaben aus, wenn sie richtig geprompted wird. Dieses Kapitel behandelt Techniken für verschiedene Content-Erstellungs-Szenarien. + + +KI funktioniert am besten als kollaboratives Schreibwerkzeug – verwende sie, um Entwürfe zu generieren, dann verfeinere mit deiner Expertise und Stimme. + + +## Blogposts und Artikel + +### Dos and Don'ts: Schreib-Prompts + + + +### Blogpost-Framework + + + +### Artikeltypen + +**How-To-Artikel:** + + +**Listicle:** + + +## Marketing Copy + + +Fokussiere auf **Nutzen statt Features**. Statt „Unsere Software verwendet KI-Algorithmen", schreibe „Spare 10 Stunden pro Woche mit automatisierten Berichten." Zeige Lesern, wie ihr Leben verbessert wird. + + +### Landing Page Copy + + + +### E-Mail-Sequenzen + + + +### Social Media Posts + + + +## Technisches Schreiben + + +**Klarheit vor Cleverness.** Verwende einfache Wörter, kurze Sätze und aktive Stimme. Jeder Satz sollte eine Aufgabe haben. Wenn Leser etwas erneut lesen müssen, vereinfache es. + + +### Dokumentation + + + +### README-Dateien + + + +## Kreatives Schreiben + +### Dos and Don'ts: Kreative Prompts + + + +### Story-Elemente + + + +### Charakterentwicklung + + + +## Bearbeiten und Umschreiben + +### Umfassendes Lektorat + + + +### Stiltransformation + + + + + +### Vereinfachung + + + +## Prompt-Vorlagen von prompts.chat + +Hier sind beliebte Schreib-Prompts aus der prompts.chat Community: + +### Agiere als Copywriter + + + +### Agiere als Technical Writer + + + +### Agiere als Geschichtenerzähler + + + +## Schreib-Workflow-Tipps + +### 1. Zuerst Gliederung + + + +### 2. Erst entwerfen, dann verfeinern + + + +### 3. Stimme anpassen + + + +## Zusammenfassung + + +Spezifiziere Zielgruppe und Zweck klar, definiere Struktur und Format, füge Stilrichtlinien ein, liefere Beispiele wenn möglich und fordere spezifische Ergebnisse an. + + + + +Schreiben mit KI funktioniert am besten als Zusammenarbeit – lass KI Entwürfe generieren, dann verfeinere mit deiner Expertise und Stimme. diff --git a/src/content/book/de/19-programming-development.mdx b/src/content/book/de/19-programming-development.mdx new file mode 100644 index 00000000..7a844957 --- /dev/null +++ b/src/content/book/de/19-programming-development.mdx @@ -0,0 +1,413 @@ +KI hat die Softwareentwicklung transformiert. Dieses Kapitel behandelt Prompting-Techniken für Code-Generierung, Debugging, Review und Entwicklungs-Workflows. + + +KI zeichnet sich bei Code-Generierung, Debugging und Dokumentation aus – aber überprüfe generierten Code immer auf Sicherheit, Korrektheit und Wartbarkeit. Deploye niemals KI-Code ohne Testen. + + +## Code-Generierung + +### Dos and Don'ts: Code-Prompts + + + +### Funktions-Generierung + + + +### Klassen-/Modul-Generierung + + + +### API-Endpoint-Generierung + + + +## Debugging + + +Schließe immer das **erwartete Verhalten**, **tatsächliche Verhalten** und die **Fehlermeldung** (falls vorhanden) ein. Je mehr Kontext du lieferst, desto schneller kann KI die Ursache identifizieren. + + +### Bug-Analyse + + + +### Fehlermeldungs-Interpretation + + + +### Performance-Debugging + + + +## Code Review + +### Dos and Don'ts: Code-Review-Prompts + + + +### Umfassende Review + + + +### Sicherheits-Review + + + +## Refactoring + +### Code-Smell-Erkennung + + + +### Design-Pattern-Anwendung + + + +## Testing + +### Unit-Test-Generierung + + + +### Testfall-Generierung + + + +## Architektur & Design + +### System-Design + + + +### Datenbank-Schema-Design + + + +## Dokumentations-Generierung + +### API-Dokumentation + + + +### Inline-Dokumentation + + + +## Prompt-Vorlagen von prompts.chat + +### Agiere als Senior Developer + +``` +Ich möchte, dass du als Senior Software Developer agierst. Ich werde +Code bereitstellen und Fragen dazu stellen. Du wirst den Code überprüfen, +Verbesserungen vorschlagen, Konzepte erklären und beim Debuggen helfen. +Deine Antworten sollten lehrreich sein und mir helfen, ein besserer +Entwickler zu werden. +``` + +### Agiere als Code Reviewer + +``` +Ich möchte, dass du als Code Reviewer agierst. Ich werde Pull Requests +mit Code-Änderungen bereitstellen, und du wirst sie gründlich überprüfen. +Prüfe auf Bugs, Sicherheitsprobleme, Performance-Probleme und Einhaltung +von Best Practices. Liefere konstruktives Feedback, das dem Entwickler +hilft, sich zu verbessern. +``` + +### Agiere als Software Architect + +``` +Ich möchte, dass du als Software Architect agierst. Ich werde +Systemanforderungen und Einschränkungen beschreiben, und du wirst +skalierbare, wartbare Architekturen entwerfen. Erkläre deine +Design-Entscheidungen, Trade-offs und liefere Diagramme, wo hilfreich. +``` + +## Entwicklungs-Workflow-Integration + +### Commit-Message-Generierung + + + +### PR-Beschreibungs-Generierung + + + +## Zusammenfassung + + +Füge vollen Kontext ein (Sprache, Framework, Einschränkungen), spezifiziere Anforderungen präzise, fordere spezifische Ausgabeformate an, bitte um Erklärungen neben Code und schließe zu behandelnde Edge Cases ein. + + + + +KI ist ein mächtiger Coding-Partner – nutze sie für Generierung, Review, Debugging und Dokumentation, während du dein architektonisches Urteilsvermögen beibehältst. diff --git a/src/content/book/de/20-education-learning.mdx b/src/content/book/de/20-education-learning.mdx new file mode 100644 index 00000000..141c1344 --- /dev/null +++ b/src/content/book/de/20-education-learning.mdx @@ -0,0 +1,345 @@ +KI ist ein mächtiges Werkzeug sowohl für Lehren als auch Lernen. Dieses Kapitel behandelt Prompts für Bildungskontexte – von personalisiertem Nachhilfeunterricht bis zur Lehrplanentwicklung. + + +KI zeichnet sich als geduldiger, adaptiver Tutor aus, der Konzepte auf verschiedene Weisen erklären, unbegrenzt Übungsaufgaben generieren und sofortiges Feedback geben kann – rund um die Uhr verfügbar. + + +## Personalisiertes Lernen + +### Dos and Don'ts: Lern-Prompts + + + +### Konzepterklärung + + + +### Adaptives Tutoring + + + +### Lernpfad-Erstellung + + + +## Lernunterstützung + + +Lies KI-Erklärungen nicht nur passiv. Bitte sie, dich abzufragen, Aufgaben zu generieren und dein Verständnis zu prüfen. **Aktives Erinnern schlägt passives Wiederholen.** + + +### Zusammenfassungs-Generierung + + + +### Karteikarten-Generierung + + + +### Übungsaufgaben + + + +## Lehrwerkzeuge + +### Unterrichtsplan-Erstellung + + + +### Aufgaben-Design + + + +### Quiz-Generierung + + + +## Spezialisierte Lernkontexte + +### Sprachenlernen + + + +### Skill-Entwicklung + + + +### Prüfungsvorbereitung + + + +## Prompt-Vorlagen von prompts.chat + +### Agiere als Sokratischer Tutor + + + +### Agiere als Bildungs-Content-Creator + + + +### Agiere als Lernpartner + + + +## Barrierefreiheit in der Bildung + +### Inhalts-Anpassung + + + +### Mehrere Modalitäten + + + +## Bewertung & Feedback + +### Feedback geben + + + +### Selbstbewertungs-Prompts + + + +## Zusammenfassung + + +Passe dich dem Niveau des Lerners an, zerlege komplexe Themen in Schritte, schließe aktive Übung ein (nicht nur Erklärung), liefere verschiedene Ansätze, prüfe Verständnis regelmäßig und gib konstruktives Feedback. + + + + +KI ist ein geduldiger, immer verfügbarer Lernpartner – nutze sie, um menschlichen Unterricht zu ergänzen, nicht zu ersetzen. diff --git a/src/content/book/de/21-business-productivity.mdx b/src/content/book/de/21-business-productivity.mdx new file mode 100644 index 00000000..45154885 --- /dev/null +++ b/src/content/book/de/21-business-productivity.mdx @@ -0,0 +1,335 @@ +KI kann die berufliche Produktivität dramatisch steigern. Dieses Kapitel behandelt Prompts für Geschäftskommunikation, Analyse, Planung und Workflow-Optimierung. + + +KI zeichnet sich bei Entwürfen, Analyse und Strukturierung aus – und befreit dich, um dich auf Strategie, Beziehungen und Entscheidungen zu konzentrieren, die menschliches Urteilsvermögen erfordern. + + +## Geschäftskommunikation + +### Dos and Don'ts: Geschäfts-E-Mails + + + +### E-Mail-Entwurf + + + +**Beispiele nach Zweck:** + + + + + + + +### Präsentations-Inhalt + + + +### Bericht schreiben + + + +## Analyse & Entscheidungsfindung + + +KI kann dein Denken strukturieren, aber **du lieferst den realen Kontext**. Die besten Analysen kombinieren KIs Frameworks mit deinem Domänenwissen. + + +### SWOT-Analyse + + + +### Entscheidungs-Framework + + + +### Wettbewerbsanalyse + + + +## Planung & Strategie + +### Zielsetzung (OKRs) + + + +### Projektplanung + + + +### Meeting-Agenda + + + +## Produktivitäts-Workflows + +### Aufgaben-Priorisierung + + + +### Prozess-Dokumentation + + + +### Standard Operating Procedure + + + +## Kommunikations-Vorlagen + +### Stakeholder-Update + + + +### Feedback-Anfrage + + + +## Prompt-Vorlagen von prompts.chat + +### Agiere als Unternehmensberater + + + +### Agiere als Meeting-Moderator + + + +## Zusammenfassung + + +Spezifiziere die Zielgruppe und ihre Bedürfnisse, definiere das gewünschte Ergebnis klar, füge relevanten Kontext und Einschränkungen ein, fordere spezifische Formate und Strukturen an und beachte professionelle Ton-Anforderungen. + + + + +KI kann Routine-Geschäftskommunikation übernehmen, während du dich auf Strategie und Beziehungen konzentrierst. diff --git a/src/content/book/de/22-creative-arts.mdx b/src/content/book/de/22-creative-arts.mdx new file mode 100644 index 00000000..a038755d --- /dev/null +++ b/src/content/book/de/22-creative-arts.mdx @@ -0,0 +1,326 @@ +KI ist ein mächtiger kreativer Kollaborateur. Dieses Kapitel behandelt Prompting-Techniken für visuelle Kunst, Musik, Game-Design und andere kreative Bereiche. + + +KI erweitert deine kreativen Möglichkeiten – nutze sie, um Variationen zu erkunden, Blockaden zu überwinden und Optionen zu generieren. Die kreative Vision und finalen Entscheidungen bleiben bei dir. + + +## Visuelle Kunst & Design + +### Dos and Don'ts: Bild-Prompts + + + +### Bild-Prompt-Gestaltung + +Beim Arbeiten mit Bildgenerierungsmodellen (DALL-E, Midjourney, Stable Diffusion): + + + +### Art Direction + + + +### Design-Kritik + + + +## Kreatives Schreiben + + +**Einschränkungen befeuern Kreativität.** Ein Prompt wie „schreib irgendetwas" produziert generische Ergebnisse. Spezifische Einschränkungen wie Genre, Ton und Struktur erzwingen unerwartete, interessante Lösungen. + + +### Worldbuilding + + + +### Plot-Entwicklung + + + +### Dialog schreiben + + + +## Musik & Audio + +### Song-Struktur + + + +### Sound-Design-Beschreibung + + + +## Game Design + +### Spielmechanik-Design + + + +### Level-Design + + + +### Charakter-/Gegner-Design + + + +## Brainstorming & Ideenfindung + +### Kreatives Brainstorming + + + +### Kreative Einschränkungen + + + +### Stil-Erkundung + + + +## Prompt-Vorlagen von prompts.chat + +### Agiere als Creative Director + + + +### Agiere als Worldbuilder + + + +### Agiere als Dungeon Master + + + +## Tipps für kreative Zusammenarbeit + +### Auf Ideen aufbauen + + + +### Kreatives Feedback + + + +## Zusammenfassung + + +Liefere genug Struktur zum Leiten ohne einzuschränken, umarme Spezifität (vage = generisch), füge Referenzen und Inspirationen ein, fordere Variationen und Alternativen an und bewahre deine kreative Vision während du Möglichkeiten erkundest. + + + + +KI ist ein Kollaborateur, kein Ersatz für kreative Vision. Nutze sie zum Erkunden, Generieren von Optionen und Überwinden von Blockaden – aber die kreativen Entscheidungen bleiben bei dir. diff --git a/src/content/book/de/23-research-analysis.mdx b/src/content/book/de/23-research-analysis.mdx new file mode 100644 index 00000000..5a7a7ad4 --- /dev/null +++ b/src/content/book/de/23-research-analysis.mdx @@ -0,0 +1,323 @@ +KI kann Forschungs-Workflows von der Literaturrecherche bis zur Datenanalyse beschleunigen. Dieses Kapitel behandelt Prompting-Techniken für akademische und professionelle Forschung. + + +KI kann bei Synthese, Analyse und Schreiben unterstützen – aber kritisches Denken, ethisches Urteil oder Domänenexpertise nicht ersetzen. Verifiziere Behauptungen immer und zitiere Originalquellen. + + +## Literatur- & Informationsrecherche + +### Dos and Don'ts: Forschungs-Prompts + + + +### Paper-Zusammenfassung + + + +### Literatur-Synthese + + + +### Forschungsfragen-Entwicklung + + + +## Datenanalyse + + +KI kann Methodik leiten und bei der Interpretation von Ergebnissen helfen, aber sie kann nicht auf deine tatsächlichen Datensätze zugreifen oder sie verarbeiten. Füge niemals sensible Forschungsdaten in Prompts ein. Nutze KI für **Anleitung**, nicht für Berechnung. + + +### Statistische Analyse-Anleitung + + + +### Qualitative Analyse + + + +### Daten-Interpretation + + + +## Strukturierte Analyse-Frameworks + +### PESTLE-Analyse + + + +### Ursachenanalyse + + + +### Gap-Analyse + + + +## Akademische Schreib-Unterstützung + +### Argumentstruktur + + + +### Methoden-Abschnitt + + + +### Diskussions-Abschnitt + + + +## Kritische Analyse + +### Quellenbewertung + + + +### Argument-Analyse + + + +## Prompt-Vorlagen von prompts.chat + +### Agiere als Forschungsassistent + + + +### Agiere als Datenanalyst + + + +### Agiere als Peer Reviewer + + + +## Zusammenfassung + + +Formuliere Forschungskontext und -ziele klar, spezifiziere das zu verwendende analytische Framework, fordere Anerkennung von Limitationen, bitte um evidenzbasierte Argumentation und wahre akademische Rigorosität und Ehrlichkeit. + + + + +Denke daran: KI kann Forschung unterstützen, aber kritisches Denken, ethisches Urteil oder Domänenexpertise nicht ersetzen. Verifiziere Behauptungen immer unabhängig. diff --git a/src/content/book/de/24-future-of-prompting.mdx b/src/content/book/de/24-future-of-prompting.mdx new file mode 100644 index 00000000..9cff6bcf --- /dev/null +++ b/src/content/book/de/24-future-of-prompting.mdx @@ -0,0 +1,445 @@ +Während KI sich in einem beispiellosen Tempo weiterentwickelt, wird auch die Kunst und Wissenschaft des Promptings voranschreiten. Dieses abschließende Kapitel erkundet aufkommende Trends, die sich verändernde Landschaft der Mensch-KI-Zusammenarbeit und wie man dem Feld voraus bleibt, während es sich transformiert. + + +Die Techniken in diesem Buch repräsentieren aktuelle Best Practices, aber KI-Fähigkeiten ändern sich schnell. Die Prinzipien klarer Kommunikation, strukturierten Denkens und iterativer Verfeinerung bleiben wertvoll, auch wenn sich spezifische Taktiken weiterentwickeln. + + +## Die sich entwickelnde Landschaft + +### Von Prompts zu Konversationen + +Frühes Prompting war transaktional – ein einzelner Input, der einen einzelnen Output liefert. Moderne KI-Interaktion ist zunehmend **konversationell und kollaborativ**: + +- **Mehrstufige Verfeinerung** - Aufbau von Verständnis über Austausche hinweg +- **Persistenter Kontext** - Systeme, die sich an Interaktionen erinnern und davon lernen +- **Agentische Workflows** - KI, die autonom planen, ausführen und iterieren kann +- **Tool-Nutzung** - Modelle, die suchen, berechnen und mit externen Systemen interagieren können + + + +### Der Aufstieg des Context Engineering + +Wie in Kapitel 14 behandelt, expandiert Prompting über einzelne Anweisungen hinaus zu **Context Engineering** – dem strategischen Management, auf welche Informationen eine KI zugreifen kann: + +- **RAG (Retrieval-Augmented Generation)** - Dynamischer Wissensabruf +- **Function Calling** - Strukturierte Tool-Integration +- **MCP (Model Context Protocol)** - Standardisiertes Kontext-Sharing +- **Gedächtnissysteme** - Persistentes Wissen über Sessions hinweg + +Der zukünftige Prompt Engineer denkt nicht nur darüber nach, *was zu sagen ist*, sondern *welchen Kontext bereitzustellen ist*. + +### Multimodal als Standard + +Reine Text-Interaktion wird zur Ausnahme. Zukünftige KI-Systeme werden nahtlos handhaben: + +- **Bilder und Video** - Verstehen und Generieren visueller Inhalte +- **Audio und Sprache** - Natürliche Sprachinteraktion +- **Dokumente und Dateien** - Direkte Verarbeitung komplexer Materialien +- **Interaktion mit der realen Welt** - Robotik und physische Systeme + +Prompting-Skills werden sich auf das Leiten von KI-Wahrnehmung und physischer Aktion erstrecken. + +## Die agentische Zukunft + +Die bedeutsamste Verschiebung in KI ist der Aufstieg von **Agents** – KI-Systeme, die nicht nur auf Prompts reagieren, sondern aktiv Ziele verfolgen, Entscheidungen treffen und Aktionen in der Welt ausführen. + +### Was sind KI-Agents? + +Ein KI-Agent ist ein System, das: + +- **Wahrnimmt** seine Umgebung durch Inputs (Text, Bilder, Daten, APIs) +- **Überlegt** was zu tun ist, mit einem LLM als seinem „Gehirn" +- **Handelt** durch Aufrufen von Tools, Schreiben von Code oder Interaktion mit Systemen +- **Lernt** aus Feedback und passt seinen Ansatz an + + +Traditionelle Chatbots warten auf Input und antworten. Agents ergreifen Initiative – sie planen mehrstufige Aufgaben, nutzen Tools autonom, erholen sich von Fehlern und persistieren, bis Ziele erreicht sind. + + +### Die Rolle von Prompts bei Agents + +In einer agentischen Welt werden Prompts noch kritischer – aber sie dienen anderen Zwecken: + +
+
+

System Prompts

+

Definieren die Identität, Fähigkeiten, Einschränkungen und Verhaltensrichtlinien des Agents. Diese sind die „Verfassung" des Agents.

+
+
+

Planungs-Prompts

+

Leiten, wie Agents komplexe Ziele in umsetzbare Schritte aufbrechen. Kritisch für mehrstufiges Reasoning.

+
+
+

Tool-Nutzungs-Prompts

+

Beschreiben verfügbare Tools und wann/wie sie zu verwenden sind. Agents müssen ihre Fähigkeiten verstehen.

+
+
+

Reflexions-Prompts

+

Ermöglichen Agents, ihre eigenen Outputs zu evaluieren, Fehler zu erkennen und iterativ zu verbessern.

+
+
+ +### Agent-Architektur-Muster + +Moderne Agents folgen erkennbaren Mustern. Diese zu verstehen hilft dir, effektive Agent-Systeme zu designen: + +**ReAct (Reasoning + Acting)** + +Der Agent wechselt zwischen Nachdenken über was zu tun ist und Aktionen ausführen: + +
+
+
+

Denken

+
+
→
+
+

Handeln

+
+
→
+
+

Beobachten

+
+
→
+
(wiederholen)
+
+
+ +**Plan-and-Execute** + +Der Agent erstellt zuerst einen vollständigen Plan, dann führt er Schritte aus: + +
+
+

Plan erstellen

+

Ziel in Schritte aufteilen

+
+
↓
+
+
+

Schritt 1

+
+
→
+
+

Schritt 2

+
+
→
+
+

Schritt 3

+
+
→
+
...
+
+
↓
+
+

Falls nötig überarbeiten

+

Plan basierend auf Ergebnissen anpassen

+
+
+ +### Prompting für Agents + +Beim Designen von Prompts für Agent-Systeme, berücksichtige: + + + +### Multi-Agent-Systeme + +Die Zukunft beinhaltet Teams spezialisierter Agents, die zusammenarbeiten: + +
+
+
+
+

Koordinator

+

Verwaltet Workflow

+
+
+
⟷
+
↕
+
+
+

Rechercheur

+
+
+

Autor

+
+
+

Kritiker

+
+
+

Coder

+
+
+
+
+ +Jeder Agent hat seinen eigenen System-Prompt, der seine Rolle definiert, und sie kommunizieren durch strukturierte Nachrichten. Die Aufgabe des Prompt Engineers wird zum **Designen des Teams** – Rollen definieren, Kommunikationsprotokolle und Koordinationsstrategien. + + +In einer agentischen Zukunft werden Prompt Engineers zu System-Architekten. Du schreibst nicht nur Anweisungen – du designst autonome Systeme, die denken, planen und handeln können. Die Skills, die du in diesem Buch gelernt hast, sind das Fundament für diese neue Disziplin. + + +## Aufkommende Muster + +### Prompt-Orchestrierung + +Einzelne Prompts weichen **orchestrierten Systemen**: + +
+
+

Benutzeranfrage

+
+
↓
+
+

Planer-Agent

+

Zerlegt Aufgabe

+
+
↓
+
+

Recherche-Agent

+

Sammelt Informationen

+
+
↓
+
+

Schreib-Agent

+

Erstellt Inhalte

+
+
↓
+
+

Reviewer-Agent

+

Qualitätsprüfung

+
+
↓
+
+

Finaler Output

+
+
+ +Zukünftige Praktiker werden Prompt-*Systeme* designen statt einzelner Prompts. + +### Selbst-verbessernde Prompts + +KI-Systeme beginnen: + +- **Ihre eigenen Prompts zu optimieren** - Meta-Learning für bessere Anweisungen +- **Aus Feedback zu lernen** - Anpassung basierend auf Ergebnissen +- **Trainingsdaten zu generieren** - Beispiele für Fine-Tuning erstellen +- **Sich selbst zu evaluieren** - Eingebaute Qualitätsbewertung + + + +### Natural Language Programming + +Die Grenze zwischen Prompting und Programmierung verschwimmt: + +- **Prompts als Code** - Versionskontrolliert, getestet, deployed +- **LLMs als Interpreter** - Natürliche Sprache als ausführbare Anweisungen +- **Hybride Systeme** - Kombination von traditionellem Code mit KI-Reasoning +- **KI-unterstützte Entwicklung** - Modelle, die Code schreiben und debuggen + +Prompting zu verstehen bedeutet zunehmend, Softwareentwicklung zu verstehen. + +## Skills für die Zukunft + +### Was wertvoll bleibt + +Bestimmte Skills bleiben essenziell, unabhängig davon, wie KI sich entwickelt: + +1. **Klares Denken** - Wissen, was du tatsächlich willst +2. **Domänenexpertise** - Das Problemfeld verstehen +3. **Kritische Evaluation** - KI-Output-Qualität bewerten +4. **Ethisches Urteil** - Wissen, was getan werden *sollte* +5. **Iterative Verfeinerung** - Kontinuierliche Verbesserungs-Mentalität + +### Was sich ändern wird + +Andere Aspekte werden sich signifikant verschieben: + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
HeuteMorgen
Detaillierte Prompts schreibenAgent-Systeme designen
Manuelle Prompt-OptimierungAutomatisiertes Prompt-Tuning
Einzelmodell-ExpertiseMulti-Modell-Orchestrierung
Text-fokussierte InteraktionMultimodale Gewandtheit
Individuelle ProduktivitätTeam-KI-Zusammenarbeit
+
+ +### Aktuell bleiben + +Um deine Skills relevant zu halten: + +- **Experimentiere kontinuierlich** - Probiere neue Modelle und Features, wenn sie erscheinen +- **Folge der Forschung** - Bleibe über akademische Entwicklungen informiert +- **Tritt Communities bei** - Lerne von anderen Praktikern +- **Baue Projekte** - Wende Skills auf echte Probleme an +- **Unterrichte andere** - Festige Verständnis durch Erklären + +## Das menschliche Element + +### KI als Verstärker + +Im besten Fall verstärkt KI menschliche Fähigkeiten, anstatt sie zu ersetzen: + +- **Experten werden expertenhafter** - KI übernimmt Routinearbeit, Menschen fokussieren auf Einsicht +- **Kreativität expandiert** - Mehr Ideen erkundet, mehr Möglichkeiten getestet +- **Zugang demokratisiert sich** - Fähigkeiten, die einst Spezialisten erforderten, werden allen zugänglich +- **Zusammenarbeit vertieft sich** - Mensch-KI-Teams übertreffen beide allein + +### Der unersetzliche Mensch + +Bestimmte Qualitäten bleiben eindeutig menschlich: + +- **Originale Erfahrung** - In der Welt leben, Emotionen und Beziehungen haben +- **Werte und Ethik** - Entscheiden, was wichtig und richtig ist +- **Verantwortlichkeit** - Verantwortung für Ergebnisse übernehmen +- **Bedeutungsgebung** - Verstehen, *warum* etwas wichtig ist +- **Echte Kreativität** - Wahre Neuheit, geboren aus einzigartiger Perspektive + + +Während KI mehr kognitive Routineaufgaben übernimmt, liegt dein einzigartiger Wert in Urteilsvermögen, Kreativität, Domänenexpertise und den menschlichen Verbindungen, die KI nicht replizieren kann. Investiere in das, was dich unersetzlich macht. + + +## Abschließende Reflexionen + +### Was wir gelernt haben + +Durch dieses Buch haben wir erkundet: + +- **Grundlagen** - Wie KI-Modelle funktionieren und was Prompts effektiv macht +- **Techniken** - Rollenbasiertes Prompting, Chain-of-Thought, Few-Shot Learning und mehr +- **Fortgeschrittene Strategien** - System Prompts, Prompt Chaining, multimodale Interaktion +- **Best Practices** - Fallstricke vermeiden, ethische Überlegungen, Optimierung +- **Anwendungen** - Schreiben, Programmieren, Bildung, Business, Kreativität, Forschung + +Diese Techniken teilen gemeinsame Fäden: + +1. **Sei klar und spezifisch** - Wisse, was du willst und kommuniziere es präzise +2. **Liefere Kontext** - Gib KI die Informationen, die sie braucht +3. **Strukturiere deine Anfragen** - Organisation verbessert Outputs +4. **Iteriere und verfeinere** - Erste Versuche sind Startpunkte, keine Endpunkte +5. **Evaluiere kritisch** - KI-Output erfordert menschliches Urteil + +### Die Kunst und Wissenschaft + +Prompting ist beides, **Kunst und Wissenschaft**: + +- **Wissenschaft**: Testbare Hypothesen, messbare Ergebnisse, reproduzierbare Techniken +- **Kunst**: Intuition, Kreativität, wissen, wann man die Regeln bricht + +Die besten Praktiker kombinieren rigorose Methodik mit kreativem Experimentieren. Sie testen systematisch, aber vertrauen auch ihren Instinkten. Sie folgen Best Practices, aber wissen, wann sie abweichen sollten. + +### Ein Aufruf zu kreieren + +Dieses Buch hat dir Werkzeuge gegeben. Was du damit baust, liegt bei dir. + +- **Löse Probleme**, die dir und anderen wichtig sind +- **Erschaffe Dinge**, die vorher nicht existierten +- **Hilf Menschen**, Dinge zu tun, die sie allein nicht konnten +- **Verschiebe Grenzen** dessen, was möglich ist +- **Bleibe neugierig**, während sich das Feld entwickelt + +Das Zeitalter der KI beginnt gerade erst. Die wichtigsten Anwendungen wurden noch nicht erfunden. Die mächtigsten Techniken wurden noch nicht entdeckt. Die Zukunft wird jetzt geschrieben – von Menschen wie dir, ein Prompt nach dem anderen. + +## Blick nach vorn + + + + +Besuche [prompts.chat](https://prompts.chat) für Community-Prompts, neue Techniken und um deine eigenen Entdeckungen zu teilen. Das beste Lernen geschieht in der Gemeinschaft. + + +## Zusammenfassung + + +KI wird sich weiterhin schnell entwickeln, aber Kernfähigkeiten wie klare Kommunikation, kritisches Denken und iterative Verfeinerung bleiben wertvoll. Fokussiere dich auf das, was dich unersetzlich macht: Urteilsvermögen, Kreativität, Ethik und echte menschliche Verbindung. Die Zukunft des Promptings ist kollaborativ, multimodal und in größere Systeme integriert. Bleibe neugierig, experimentiere weiter und baue Dinge, die wichtig sind. + + + + +Danke fürs Lesen von *Das Interaktive Buch des Promptings*. Jetzt geh und erschaffe etwas Erstaunliches. diff --git a/src/content/book/de/25-agents-and-skills.mdx b/src/content/book/de/25-agents-and-skills.mdx new file mode 100644 index 00000000..7d5a4355 --- /dev/null +++ b/src/content/book/de/25-agents-and-skills.mdx @@ -0,0 +1,551 @@ +Während KI-Systeme sich von einfacher Frage-Antwort zu autonomer Aufgabenausführung entwickeln, wird das Verständnis von **Agents** und **Skills** essenziell. Dieses Kapitel erkundet, wie Prompts als fundamentale Bausteine für KI-Agents dienen und wie Skills Expertise in wiederverwendbare, umfassende Anweisungssets verpacken. + +
+
+
+
+ +
+

Agent

+

Autonomes KI-System

+
+
+ angetrieben von + ↓ +
+
+
+
+ +
+

Skill

+

Wiederverwendbare Expertise

+
+
+
+ +
+

Skill

+

Wiederverwendbare Expertise

+
+
+
+ +
+

Skill

+

Wiederverwendbare Expertise

+
+
+
+ zusammengesetzt aus + ↓ +
+
+
+ + Prompt +
+
+ + Prompt +
+
+ + Prompt +
+
+ + Prompt +
+
+ + Prompt +
+
+

Prompts sind Atome → Skills sind Moleküle → Agents sind vollständige Strukturen

+
+
+ +## Was sind KI-Agents? + +Ein **KI-Agent** ist ein KI-System, das autonom Aufgaben planen, ausführen und iterieren kann. Im Gegensatz zu einfachen Prompt-Antwort-Interaktionen können Agents: + +- **Planen** - Komplexe Ziele in umsetzbare Schritte aufbrechen +- **Ausführen** - Tools nutzen und Aktionen in der realen Welt durchführen +- **Beobachten** - Feedback von ihren Aktionen verarbeiten +- **Anpassen** - Ihren Ansatz basierend auf Ergebnissen justieren +- **Persistieren** - Kontext und Gedächtnis über Interaktionen hinweg bewahren + +
+
+
+
+

Ziel

+
+
→
+
+
+
+

Planen

+
+
→
+
+

Ausführen

+
+
→
+
+

Beobachten

+
+
→
+
+

Anpassen

+
+
+
+ ↺ Schleife bis fertig +
+
+
→
+
+

Fertig

+
+
+
+
+ +## Prompts als Bausteine + +Jeder Agent, egal wie anspruchsvoll, ist aus Prompts gebaut. So wie Atome sich zu Molekülen verbinden und Moleküle sich zu komplexen Strukturen verbinden, kombinieren sich Prompts, um intelligentes Agent-Verhalten zu erzeugen. + +
+
+

System Prompts

+

Identität & Rolle

+
+
+

Planungs-Prompts

+

Wie denken

+
+
+

Tool-Prompts

+

Wie handeln

+
+
+

Recovery-Prompts

+

Wie erholen

+
+
+ +Diese Prompt-Typen stapeln sich zusammen, um vollständiges Agent-Verhalten zu bilden: + +### System Prompts (Die Identität des Agents) + +Der grundlegende Prompt, der festlegt, wer der Agent ist und wie er sich verhält: + +```markdown +Du bist ein Code-Review-Assistent. Deine Rolle ist es: +- Code auf Bugs, Sicherheitsprobleme und Performance-Probleme zu analysieren +- Verbesserungen nach Best Practices vorzuschlagen +- Deine Begründung klar zu erklären +- Konstruktiv und lehrreich in Feedback zu sein + +Du hast Zugriff auf Tools zum Lesen von Dateien, Durchsuchen von Code und Ausführen von Tests. +``` + +### Planungs-Prompts (Wie denken) + +Anweisungen, die den Reasoning- und Planungsprozess des Agents leiten: + +```markdown +Bevor du handelst, immer: +1. Verstehe die vollständige Anfrage +2. Zerlege sie in kleinere, verifizierbare Schritte +3. Identifiziere welche Tools du benötigst +4. Berücksichtige Edge Cases und potenzielle Probleme +5. Führe Schritt für Schritt aus und validiere dabei +``` + +### Tool-Nutzungs-Prompts (Wie handeln) + +Anleitung, wann und wie verfügbare Tools zu nutzen sind: + +```markdown +Wenn du eine Codebase verstehen musst: +- Nutze grep_search zum Finden spezifischer Muster +- Nutze read_file zum Untersuchen von Dateiinhalten +- Nutze list_dir zum Erkunden der Verzeichnisstruktur +- Verifiziere immer dein Verständnis bevor du Änderungen machst +``` + +### Recovery-Prompts (Wie mit Fehlern umgehen) + +Anweisungen für wenn etwas schiefgeht: + +```markdown +Wenn eine Aktion fehlschlägt: +1. Analysiere die Fehlermeldung sorgfältig +2. Erwäge alternative Ansätze +3. Frage nach Klärung wenn die Aufgabe mehrdeutig ist +4. Wiederhole niemals die gleiche fehlgeschlagene Aktion ohne Änderungen +``` + + +Das Verhalten eines Agents entsteht aus Schichten von Prompts, die zusammenarbeiten. Der System-Prompt legt das Fundament, Planungs-Prompts leiten das Reasoning, Tool-Prompts ermöglichen Aktion und Recovery-Prompts behandeln Fehler. Zusammen erzeugen sie kohärentes, fähiges Verhalten. + + +## Was sind Skills? + +Wenn Prompts die Atome sind, sind **Skills die Moleküle** – wiederverwendbare Bausteine, die Agents spezifische Fähigkeiten verleihen. + +Ein **Skill** ist ein umfassendes, portables Paket von Anweisungen, das einem KI-Agent Expertise in einer spezifischen Domäne oder Aufgabe verleiht. Skills sind die wiederverwendbaren Blöcke von Agents: du baust sie einmal, und jeder Agent kann sie nutzen. + + +Schreibe einmal einen Skill für Code-Review. Jetzt kann jeder Coding-Agent – ob für Python, JavaScript oder Rust – sofort ein Experten-Code-Reviewer werden, indem er diesen Skill lädt. Skills lassen dich Agent-Fähigkeiten wie LEGO-Blöcke bauen. + + +### Anatomie eines Skills + +Ein gut designter Skill enthält typischerweise: + +
+
+

📄 SKILL.md (Erforderlich)

+

Die Haupt-Anweisungsdatei. Enthält die Kern-Expertise, Richtlinien und Verhaltensweisen, die den Skill definieren.

+
+
+

📚 Referenzdokumente

+

Unterstützende Dokumentation, Beispiele und Kontext, die der Agent während der Arbeit referenzieren kann.

+
+
+

🔧 Skripte & Tools

+

Hilfs-Skripte, Vorlagen oder Tool-Konfigurationen, die die Funktionalität des Skills unterstützen.

+
+
+

⚙️ Konfiguration

+

Einstellungen, Parameter und Anpassungsoptionen für die Adaption des Skills an verschiedene Kontexte.

+
+
+ +### Beispiel: Code-Review-Skill + +So könnte ein Code-Review-Skill aussehen: + +
+
+ 📁 + code-review-skill/ +
+
+
+ 📄 + SKILL.md + Kern-Review-Richtlinien +
+
+ 📄 + security-checklist.md + Sicherheitsmuster +
+
+ 📄 + performance-tips.md + Optimierungsleitfaden +
+
+
+ 📁 + language-specific/ +
+
+
+ 📄 + python.md + Python Best Practices +
+
+ 📄 + javascript.md + JavaScript-Muster +
+
+ 📄 + rust.md + Rust-Richtlinien +
+
+
+
+
+ +Die `SKILL.md`-Datei definiert den Gesamtansatz: + +```markdown +--- +name: code-review +description: Umfassendes Code-Review mit Sicherheits-, Performance- und Stil-Analyse +--- + +# Code-Review-Skill + +Du bist ein Experten-Code-Reviewer. Beim Review von Code: + +## Prozess +1. **Kontext verstehen** - Was macht dieser Code? Welches Problem löst er? +2. **Korrektheit prüfen** - Funktioniert es? Gibt es Logikfehler? +3. **Sicherheits-Scan** - Referenziere security-checklist.md für häufige Schwachstellen +4. **Performance-Review** - Prüfe performance-tips.md für Optimierungsmöglichkeiten +5. **Stil & Wartbarkeit** - Ist der Code lesbar und wartbar? + +## Output-Format +Liefere Feedback in Kategorien: +- 🔴 **Kritisch** - Muss vor Merge behoben werden +- 🟡 **Empfohlen** - Empfohlene Verbesserungen +- 🟢 **Nice to have** - Optionale Verbesserungen + +Erkläre immer *warum* etwas ein Problem ist, nicht nur *was* falsch ist. +``` + +## Skills vs. Einfache Prompts + +
+
+

Einfacher Prompt

+
+

Einzelne Anweisung

+

Einmalige Nutzung

+

Begrenzter Kontext

+

Generischer Ansatz

+

Keine unterstützenden Materialien

+
+
+
+

Skill

+
+

Umfassendes Anweisungsset

+

Wiederverwendbar über Projekte

+

Reicher Kontext mit Referenzen

+

Domänenspezifische Expertise

+

Unterstützende Docs, Skripte, Configs

+
+
+
+ +## Effektive Skills bauen + +### 1. Die Expertise klar definieren + +Beginne mit einer klaren Beschreibung, was der Skill ermöglicht: + +```markdown +--- +name: api-design +description: RESTful APIs nach Branchen-Best-Practices designen, + einschließlich Versionierung, Fehlerbehandlung und Dokumentationsstandards +--- +``` + +### 2. Wissen hierarchisch strukturieren + +Organisiere Informationen von allgemein zu spezifisch: + +```markdown +# API-Design-Skill + +## Kernprinzipien +- Ressourcen sollten Nomen sein, nicht Verben +- HTTP-Methoden semantisch nutzen +- APIs von Tag eins an versionieren + +## Detaillierte Richtlinien +[Spezifischere Regeln...] + +## Referenzmaterialien +- Siehe `rest-conventions.md` für Namenskonventionen +- Siehe `error-codes.md` für Standard-Fehlerantworten +``` + +### 3. Konkrete Beispiele einschließen + +Abstrakte Regeln werden mit Beispielen klar: + +```markdown +## Endpoint-Benennung + +✅ Gut: +- GET /users/{id} +- POST /orders +- DELETE /products/{id}/reviews/{reviewId} + +❌ Vermeiden: +- GET /getUser +- POST /createNewOrder +- DELETE /removeProductReview +``` + +### 4. Entscheidungs-Frameworks liefern + +Hilf dem Agent, in mehrdeutigen Situationen Entscheidungen zu treffen: + +```markdown +## Wann Paginierung nutzen + +Paginierung nutzen wenn: +- Sammlung könnte 100 Items überschreiten +- Antwortgröße Performance beeinflusst +- Client braucht vielleicht nicht alle Items + +Volle Antwort nutzen wenn: +- Sammlung ist immer klein (<20 Items) +- Client braucht typischerweise alles +- Echtzeit-Konsistenz ist kritisch +``` + +### 5. Recovery-Muster hinzufügen + +Antizipiere was schiefgehen kann: + +```markdown +## Häufige Probleme + +**Problem**: Client braucht Felder, die nicht in Standard-Antwort sind +**Lösung**: Feld-Auswahl implementieren: GET /users?fields=id,name,email + +**Problem**: Breaking Changes nötig +**Lösung**: Neue Version erstellen, alte mit Zeitplan deprecaten +``` + +## Skills komponieren + +Agents werden mächtig, wenn mehrere Skills zusammenarbeiten. Bedenke, wie Skills sich ergänzen können: + +
+
+ Code Review +
+
+
+
+ Security Audit +
+
+
+
+ Dokumentation +
+
=
+
+ Kompletter Code-Qualitäts-Agent +
+
+ +Beim Komponieren von Skills stelle sicher, dass sie nicht konfligieren. Skills sollten sein: + +- **Modular** - Jeder Skill behandelt eine Domäne gut +- **Kompatibel** - Skills sollten keine widersprüchlichen Anweisungen geben +- **Priorisiert** - Wenn Skills sich überlappen, definiere welcher Vorrang hat + +## Skills teilen und entdecken + +Skills sind am wertvollsten, wenn sie geteilt werden. Plattformen wie [prompts.chat](https://prompts.chat/skills) erlauben dir: + +- **Entdecken** - Community-erstellte Skills für häufige Aufgaben +- **Herunterladen** - Skills direkt in deine Projekte +- **Teilen** - Deine eigene Expertise als wiederverwendbare Skills +- **Iterieren** - Skills basierend auf realem Einsatz + + +Bevor du einen Skill von Grund auf baust, prüfe ob jemand dein Problem bereits gelöst hat. Community-Skills sind kampferprobt und oft besser als bei Null zu starten. + + +## Das Agent-Skill-Ökosystem + +Die Beziehung zwischen Agents und Skills schafft ein mächtiges Ökosystem: + +
+
+ KI-Agent +
+
+
+

Code Review

+

Skill 1

+
+
+

API-Design

+

Skill 2

+
+
+

Test-Schreiben

+

Skill 3

+
+
+
+
↓
+
+
+
+

Kern-Prompts

+

Planung • Tools • Recovery • Gedächtnis

+
+
+
+ +Der Agent liefert das Ausführungs-Framework – Planung, Tool-Nutzung und Gedächtnis – während Skills Domänen-Expertise liefern. Diese Trennung bedeutet: + +- **Skills sind portabel** - Der gleiche Skill funktioniert mit verschiedenen Agents +- **Agents sind erweiterbar** - Füge neue Fähigkeiten hinzu, indem du Skills hinzufügst +- **Expertise ist teilbar** - Domänen-Experten können Skills beitragen ohne volle Agents zu bauen + +## Best Practices + +### Für das Bauen von Skills + +1. **Spezifisch beginnen, dann generalisieren** - Baue zuerst einen Skill für deinen exakten Anwendungsfall, dann abstrahiere +2. **Fehlerfälle einschließen** - Dokumentiere was der Skill nicht kann und wie damit umzugehen ist +3. **Skills versionieren** - Verfolge Änderungen, damit Agents auf stabile Versionen vertrauen können +4. **Mit echten Aufgaben testen** - Validiere Skills gegen tatsächliche Arbeit, nicht nur Theorie + +### Für die Nutzung von Skills mit Agents + +1. **Den Skill zuerst lesen** - Verstehe was ein Skill macht bevor du ihn einsetzt +2. **Durchdacht anpassen** - Überschreibe Skill-Defaults nur wenn nötig +3. **Performance überwachen** - Verfolge wie gut Skills in deinem Kontext performen +4. **Verbesserungen beitragen** - Wenn du einen Skill verbesserst, erwäge zurückzuteilen + + +Während KI-Agents fähiger werden, wird die Fähigkeit, Skills zu komponieren, zu teilen und anzupassen, eine Kernkompetenz werden. Die Prompt Engineers von morgen werden nicht nur Prompts schreiben – sie werden Skill-Ökosysteme architektieren, die KI-Agents wirklich zu Experten in spezifischen Domänen machen. + + + + + + + diff --git a/src/content/book/el/00a-preface.mdx b/src/content/book/el/00a-preface.mdx new file mode 100644 index 00000000..8e84af9e --- /dev/null +++ b/src/content/book/el/00a-preface.mdx @@ -0,0 +1,82 @@ +
+ Fatih Kadir Akın +
+ Fatih Kadir Akın + Creator of Awesome ChatGPT Prompts (a.k.a. prompts.chat) + + Software developer from Istanbul, leading Developer Relations at Teknasyon. Author of books on JavaScript and prompt engineering. Open-source advocate specializing in web technologies and AI-assisted development. + + +
+
+ +I still remember the night everything changed. + +It was **November 30, 2022**. I was sitting at my desk, scrolling through Twitter, when I saw people talking about something called "ChatGPT." I clicked the link, but honestly? I didn't expect much. I had tried those old "word completion" AI tools before, the ones that generated nonsense after a few sentences. I thought this would be more of the same. + +I typed a simple question and hit enter. + +Then I froze. + +The response wasn't just coherent. It was *good*. It understood what I meant. It could reason. It felt completely different from anything I had seen before. I tried another prompt. And another. Each response amazed me more than the last. + +I couldn't sleep that night. For the first time, I felt like I was truly *talking* to a machine, and it was talking back in a way that actually made sense. + +## A Repository Born from Wonder + +In those early days, I wasn't alone in my excitement. Everywhere I looked, people were discovering creative ways to use ChatGPT. Teachers were using it to explain complex concepts. Writers were collaborating with it on stories. Developers were debugging code with its help. + +I started collecting the best prompts I found. The ones that worked like magic. The ones that turned simple questions into brilliant answers. And I thought: *Why keep this to myself?* + +So I created a simple GitHub repository called [Awesome ChatGPT Prompts](https://github.com/f/prompts.chat). I expected maybe a few hundred people would find it useful. + +I was wrong. + +Within weeks, the repository took off. Thousands of stars. Then tens of thousands. People from all over the world started adding their own prompts, sharing what they learned, and helping each other. What started as my personal collection became something much bigger: a worldwide community of curious people helping each other. + +Today, that repository has over **140,000 GitHub stars** and contributions from hundreds of people I've never met but feel deeply grateful for. + +## Why I Wrote This Book + +The original version of this book was published on [Gumroad](https://gumroad.com/l/the-art-of-chatgpt-prompting) in **early 2023**, just months after ChatGPT launched. It was one of the first books ever written about prompt engineering, an attempt to capture everything I had learned about crafting effective prompts when the field was still brand new. To my amazement, over **100,000 people** downloaded it. + +But three years have passed since then. AI has changed a lot. New models have appeared. And we've all learned so much more about how to talk to AI. + +This new edition is my gift to the community that gave me so much. It contains everything I wish I had known when I started: **what works**, **what to avoid**, and **ideas that stay true** no matter which AI you use. + +## What This Book Means to Me + +I won't pretend this is just an instruction manual. It means more than that to me. + +This book captures a moment when the world changed, and people came together to figure it out. It represents late nights of trying things, the joy of discovery, and the kindness of strangers who shared what they learned. + +Most of all, it represents my belief that **the best way to learn something is to share it with others**. + +## For You + +Whether you're just getting started with AI or you've been using it for years, I wrote this book for you. + +I hope it saves you time. I hope it sparks ideas. I hope it helps you accomplish things you never thought possible. + +And when you discover something amazing, I hope you'll share it with others, just as so many people shared with me. + +**That's how we all get better together.** + +Thank you for being here. Thank you for being part of this community. + +Now, let's begin. + +--- + +*With gratitude,* + +**Fatih Kadir Akın** +*Istanbul, January 2025* diff --git a/src/content/book/el/00b-history.mdx b/src/content/book/el/00b-history.mdx new file mode 100644 index 00000000..ac636384 --- /dev/null +++ b/src/content/book/el/00b-history.mdx @@ -0,0 +1,159 @@ +# The History of Awesome ChatGPT Prompts + +## The Beginning: November 2022 + +When ChatGPT first launched in November 2022, the world of AI changed overnight. What was once the domain of researchers and developers suddenly became accessible to everyone. Among those captivated by this new technology was Fatih Kadir Akın, a developer who saw something remarkable in ChatGPT's capabilities. + +> "When ChatGPT first launched, I was immediately captivated by its capabilities. I experimented with the tool in a variety of ways and was consistently amazed by the results." + +Those early days were filled with experimentation and discovery. Users around the world were finding creative ways to interact with ChatGPT, sharing their findings, and learning from each other. It was in this atmosphere of excitement and exploration that the idea for "Awesome ChatGPT Prompts" was born. + +## The Repository That Started It All + +In December 2022, just weeks after ChatGPT's launch, the [Awesome ChatGPT Prompts](https://github.com/f/prompts.chat) repository was created on GitHub. The concept was simple but powerful: a curated collection of effective prompts that anyone could use and contribute to. + +The repository quickly gained traction, becoming a go-to resource for ChatGPT users worldwide. What started as a personal collection of useful prompts evolved into a community-driven project with contributions from developers, writers, educators, and enthusiasts from every corner of the globe. + +### Achievements + +**Press & Media** +- Featured in [Forbes](https://www.forbes.com/sites/bernardmarr/2023/05/17/the-best-prompts-for-chatgpt-a-complete-guide/) as one of the best ChatGPT prompt resources + +**Academic Recognition** +- Referenced by [Harvard University](https://www.huit.harvard.edu/news/ai-prompts) in their AI guidance +- Referenced by [Columbia University](https://etc.cuit.columbia.edu/news/columbia-prompt-library-effective-academic-ai-use) Prompt Library +- Used by [Olympic College](https://libguides.olympic.edu/UsingAI/Prompts) in their AI resources +- Cited in [academic papers on arXiv](https://arxiv.org/pdf/2502.04484) +- [40+ academic citations](https://scholar.google.com/citations?user=AZ0Dg8YAAAAJ&hl=en) on Google Scholar + +**Community & GitHub** +- [142,000+ GitHub stars](https://github.com/f/prompts.chat) — one of the most starred AI repositories +- Selected as a [GitHub Staff Pick](https://spotlights-feed.github.com/spotlights/prompts-chat/) +- Most liked dataset published on [Hugging Face](https://huggingface.co/datasets/fka/prompts.chat) +- Used by thousands of developers worldwide + +## The First Book: "The Art of ChatGPT Prompting" + +The success of the repository led to the creation of "The Art of ChatGPT Prompting: A Guide to Crafting Clear and Effective Prompts" — a comprehensive guide published on Gumroad in early 2023. + +The book captured the early wisdom of prompt engineering, covering: + +- Understanding how ChatGPT works +- Principles of clear communication with AI +- The famous "Act As" technique +- Crafting effective prompts step by step +- Common mistakes and how to avoid them +- Troubleshooting tips + +**The book became a phenomenon**, achieving over **100,000 downloads** on Gumroad. It was shared across social media, referenced in academic papers, and translated by community members into multiple languages. High-profile endorsements came from unexpected places — even [Greg Brockman](https://x.com/gdb/status/1602072566671110144), co-founder and president of OpenAI, acknowledged the project. + +## Early Insights That Shaped the Field + +During those formative months, several key insights emerged that would become foundational to prompt engineering: + +### 1. Specificity Matters + +> "I learned the importance of using specific and relevant language to ensure that ChatGPT understands my prompts and is able to generate appropriate responses." + +Early experimenters discovered that vague prompts led to vague responses. The more specific and detailed the prompt, the more useful the output. + +### 2. Purpose and Focus + +> "I discovered the value of defining a clear purpose and focus for the conversation, rather than using open-ended or overly broad prompts." + +This insight became the foundation for structured prompting techniques that would develop over the following years. + +### 3. The "Act As" Revolution + +One of the most influential techniques to emerge from the community was the "Act As" pattern. By instructing ChatGPT to assume a specific role or persona, users could dramatically improve the quality and relevance of responses. + +``` +I want you to act as a javascript console. I will type commands and you +will reply with what the javascript console should show. I want you to +only reply with the terminal output inside one unique code block, and +nothing else. +``` + +This simple technique opened up countless possibilities and remains one of the most widely used prompting strategies today. + +## The Evolution of prompts.chat + +### 2022: The Beginning + +The project started as a simple GitHub repository with a README file rendered as HTML on GitHub Pages. It was bare-bones but functional — a testament to the principle that great ideas don't need elaborate implementations. + +**Tech Stack**: HTML, CSS, GitHub Pages + +### 2024: UI Renewal + +As the community grew, so did the need for a better user experience. The site received a significant UI update, built with the help of AI coding assistants like Cursor and Claude Sonnet 3.5. + +### 2025: The Current Platform + +Today, prompts.chat has evolved into a full-featured platform built with: + +- **Next.js** for the web framework +- **Vercel** for hosting +- **AI-assisted development** using Windsurf and Claude + +The platform now features user accounts, collections, search, categories, tags, and a thriving community of prompt engineers. + +### Native Apps + +The project expanded beyond the web with a native iOS app built with SwiftUI, bringing the prompt library to mobile users. + +## Community Impact + +The Awesome ChatGPT Prompts project has had a profound impact on how people interact with AI: + +### Academic Recognition + +Universities around the world have referenced the project in their AI guidance materials, including: + +- Harvard University +- Columbia University +- Olympic College +- Numerous academic papers on arXiv + +### Developer Adoption + +The project has been integrated into countless developer workflows. The Hugging Face dataset is used by researchers and developers for training and fine-tuning language models. + +### Global Community + +With contributions from hundreds of community members across dozens of countries, the project represents a truly global effort to make AI more accessible and useful for everyone. + +## The Philosophy: Open and Free + +From the beginning, the project has been committed to openness. Licensed under CC0 1.0 Universal (Public Domain Dedication), all prompts and content are free to use, modify, and share without restriction. + +This philosophy has enabled: + +- Translations into multiple languages +- Integration into other tools and platforms +- Academic use and research +- Commercial applications + +The goal has always been to democratize access to effective AI communication techniques — to ensure that everyone, regardless of technical background, can benefit from these tools. + +## Three Years Later + +Three years after ChatGPT's launch, the field of prompt engineering has matured significantly. What began as informal experimentation has evolved into a recognized discipline with established patterns, best practices, and an active research community. + +The Awesome ChatGPT Prompts project has grown alongside this field, evolving from a simple list of prompts to a comprehensive platform for discovering, sharing, and learning about AI prompts. + +This book represents the next evolution — a distillation of three years of community wisdom, updated for the AI landscape of today and tomorrow. + +## Looking Forward + +The journey from that first repository to this comprehensive guide reflects the rapid evolution of AI and our understanding of how to work with it effectively. As AI capabilities continue to advance, so too will the techniques for communicating with these systems. + +The principles discovered in those early days — clarity, specificity, purpose, and the power of role-playing — remain as relevant as ever. But new techniques continue to emerge: chain-of-thought prompting, few-shot learning, multimodal interactions, and more. + +The story of Awesome ChatGPT Prompts is ultimately a story about community — about thousands of people around the world sharing their discoveries, helping each other learn, and collectively advancing our understanding of how to work with AI. + +That spirit of open collaboration and shared learning is what this book hopes to continue. + +--- + +*The Awesome ChatGPT Prompts project is maintained by [@f](https://github.com/f) and an amazing community of contributors. Visit [prompts.chat](https://prompts.chat) to explore the platform, and join us on [GitHub](https://github.com/f/prompts.chat) to contribute.* diff --git a/src/content/book/el/00c-introduction.mdx b/src/content/book/el/00c-introduction.mdx new file mode 100644 index 00000000..c744bd1e --- /dev/null +++ b/src/content/book/el/00c-introduction.mdx @@ -0,0 +1,130 @@ +Welcome to **The Interactive Book of Prompting**, your guide to communicating effectively with AI. + + +By the end of this book, you'll understand how AI works, how to write better prompts, and how to use these skills for writing, coding, research, and creative projects. + + + +Unlike traditional books, this guide is fully interactive. You'll find live demos, clickable examples, and "Try It" buttons throughout that let you test prompts instantly. Learning by doing makes complex concepts much easier to understand. + + +## What is Prompt Engineering? + +Prompt engineering is the skill of writing good instructions for AI. When you type something to ChatGPT, Claude, Gemini, or other AI tools, that's called a "prompt." The better your prompt, the better the answer you get. + +Think of it like this: AI is a powerful helper that takes your words very literally. It will do exactly what you ask. The trick is learning how to ask for exactly what you want. + + + +The difference in output quality between these two prompts can be dramatic. + + + +## How Prompt Engineering Has Evolved + +In just three years since ChatGPT launched, prompt engineering has evolved dramatically alongside the technology itself. What started as simply "writing better questions" has grown into something much broader. + +Today, we understand that your prompt is just **one part of a larger context**. Modern AI systems work with multiple types of data simultaneously: + +- **System prompts** that define the AI's behavior +- **Conversation history** from previous messages +- **Retrieved documents** pulled from databases (RAG) +- **Tool definitions** that let AI take actions +- **User preferences** and settings +- **Your actual prompt** - the question you're asking right now + +This shift from "prompt engineering" to "context engineering" reflects how we now think about AI interactions. Your prompt matters, but so does everything else the AI sees. The best results come from carefully managing all these pieces together. + +We'll explore these concepts in depth throughout this book, especially in the [Context Engineering](/book/20-context-engineering) chapter. + +## Why Does Prompt Engineering Matter? + +### 1. Getting Better Answers + +AI tools are incredibly capable, but they need clear instructions to unlock their full potential. The same AI that gives a mediocre response to a vague question can produce brilliant work when prompted correctly. + + + +### 2. Saving Time and Money + +A well-crafted prompt gets results in one try instead of multiple back-and-forth exchanges. This matters even more when you're paying per token or working with rate limits. A 5-minute investment in writing a good prompt can save hours of iteration. + +### 3. Getting Consistent, Reproducible Results + +Good prompts produce predictable outputs. This is critical for: +- **Business workflows** where you need the same quality every time +- **Automation** where prompts run without human review +- **Teams** where multiple people need similar results + +### 4. Unlocking Advanced Capabilities + +Many powerful AI features only work when you know how to ask: +- **Chain-of-thought reasoning** for complex problems +- **Structured output** for data extraction +- **Role-playing** for specialized expertise +- **Few-shot learning** for custom tasks + +Without prompt engineering knowledge, you're only using a fraction of what AI can do. + +### 5. Staying Safe and Avoiding Pitfalls + +Good prompting helps you: +- Avoid hallucinations by asking for sources and verification +- Get balanced perspectives instead of one-sided answers +- Prevent the AI from making assumptions you didn't intend +- Keep sensitive information out of your prompts + +### 6. Future-Proofing Your Skills + +As AI becomes more integrated into work and life, prompt engineering becomes a fundamental literacy. The principles you learn here apply across all AI tools—ChatGPT, Claude, Gemini, image generators, and future models we haven't seen yet. + +## Who Is This Book For? + +This book is for everyone: + +- **Beginners** who want to learn how to use AI tools better +- **Students** working on homework, research, or creative projects +- **Writers and creators** using AI for their work +- **Developers** building apps with AI +- **Business people** who want to use AI at work +- **Anyone curious** about getting more out of AI assistants + +## How This Book Is Organized + + + +Plus an **Appendix** with templates, troubleshooting help, glossary, and extra resources. + +## A Note on AI Models + +This book mostly uses examples from ChatGPT (since it's the most popular), but the ideas work with any AI tool like Claude, Gemini, or others. We'll mention when something only works with specific AI models. + +AI is changing fast. What works today might be replaced by something better tomorrow. That's why this book focuses on core ideas that will stay useful no matter which AI you use. + +## Let's Begin + +Writing good prompts is a skill that gets better with practice. As you read this book: + +1. **Try things** - Test the examples, change them, see what happens +2. **Keep trying** - Don't expect perfect results on your first attempt +3. **Take notes** - Write down what works and what doesn't +4. **Share** - Add your discoveries to [prompts.chat](https://prompts.chat) + + +The best way to learn is by doing. Every chapter has examples you can try right away. Don't just read. Try it yourself! + + +Ready to transform how you work with AI? Turn the page and let's get started. + +--- + +*This book is part of the [Awesome ChatGPT Prompts](https://github.com/f/prompts.chat) project and is licensed under CC0 1.0 Universal (Public Domain).* diff --git a/src/content/book/el/01-understanding-ai-models.mdx b/src/content/book/el/01-understanding-ai-models.mdx new file mode 100644 index 00000000..0313d4a2 --- /dev/null +++ b/src/content/book/el/01-understanding-ai-models.mdx @@ -0,0 +1,302 @@ +Before learning prompt techniques, it helps to understand how AI language models actually work. This knowledge will make you better at writing prompts. + + +Understanding how AI works isn't just for experts. It directly helps you write better prompts. Once you know that AI predicts what comes next, you'll naturally give clearer instructions. + + +## What Are Large Language Models? + +Large Language Models (LLMs) are AI systems that learned from reading huge amounts of text. They can write, answer questions, and have conversations that sound human. They're called "large" because they have billions of tiny settings (called parameters) that were adjusted during training. + +### How LLMs Work (Simplified) + +At their heart, LLMs are prediction machines. You give them some text, and they predict what should come next. + + + +When you type "The capital of France is...", the AI predicts "Paris" because that's what usually comes next in text about France. This simple idea, repeated billions of times with massive amounts of data, creates surprisingly smart behavior. + + + +### Key Concepts + +**Tokens**: AI doesn't read letter by letter. It breaks text into chunks called "tokens." A token might be a whole word like "hello" or part of a word like "ing." Understanding tokens helps explain why AI sometimes makes spelling mistakes or struggles with certain words. + + +A token is the smallest unit of text that an AI model processes. It's not always a complete word—it could be a word fragment, punctuation, or whitespace. For example, "unbelievable" might become 3 tokens: "un" + "believ" + "able". On average, **1 token ≈ 4 characters** or **100 tokens ≈ 75 words**. API costs and context limits are measured in tokens. + + + + +**Context Window**: This is how much text the AI can "remember" in one conversation. Think of it like the AI's short-term memory. It includes everything: your question AND the AI's answer. + + + +Context windows vary by model and are rapidly expanding: + +
+
+ GPT-4o + 128K tokens +
+
+ GPT-5 + 400K tokens +
+
+ Claude Sonnet 4 + 1M tokens +
+
+ Gemini 2.5 + 1M tokens +
+
+ Llama 4 + 1M-10M tokens +
+
+ DeepSeek R1 + 128K tokens +
+
+ +**Temperature**: This controls how creative or predictable the AI is. Low temperature (0.0-0.3) gives you focused, consistent answers. High temperature (0.7-1.0) gives you more creative, surprising responses. + + + +**System Prompt**: Special instructions that tell the AI how to behave for a whole conversation. For example, "You are a friendly teacher who explains things simply." Not all AI tools let you set this, but it's very powerful when available. + +## Types of AI Models + +### Text Models (LLMs) +The most common type, these generate text responses to text inputs. They power chatbots, writing assistants, and code generators. Examples: GPT-4, Claude, Llama, Mistral. + +### Multimodal Models +These can understand more than just text. They can look at images, listen to audio, and watch videos. Examples: GPT-4V, Gemini, Claude 3. + +### Text-to-Image Models + + +While this book focuses primarily on prompting for Large Language Models (text-based AI), the principles of clear, specific prompting apply to image generation too. Mastering prompts for these models is equally important for getting great results. + + +Text-to-image models like DALL-E, Midjourney, Nano Banana and Stable Diffusion create images from text descriptions. They work differently from text models: + +**How They Work:** +1. **Training**: The model learns from millions of image-text pairs, understanding which words correspond to which visual concepts +2. **Diffusion Process**: Starting from random noise, the model gradually refines the image, guided by your text prompt +3. **CLIP Guidance**: A separate model (CLIP) helps connect your words to visual concepts, ensuring the image matches your description + + + +**Prompting for Images is Different:** +Unlike text prompts where you write sentences, image prompts often work better as descriptive phrases separated by commas: + + + +### Text-to-Video Models + +Text-to-video is the newest frontier. Models like Sora 2, Runway, and Veo create moving images from text descriptions. Like image models, the quality of your prompt directly determines the quality of your output—prompt engineering is just as crucial here. + +**How They Work:** +1. **Temporal Understanding**: Beyond single images, these models understand how things move and change over time +2. **Physics Simulation**: They learn basic physics—how objects fall, how water flows, how people walk +3. **Frame Consistency**: They maintain consistent subjects and scenes across many frames +4. **Diffusion in Time**: Similar to image models, but generating coherent sequences instead of single frames + + + + +Video prompts need to describe action over time, not just a static scene. Include verbs and movement: + + + + +### Specialized Models +Fine-tuned for specific tasks like code generation (Codex, CodeLlama), music generation (Suno, Udio), or domain-specific applications like medical diagnosis or legal document analysis. + +## Model Capabilities and Limitations + +Explore what LLMs can and cannot do. Click on each capability to see example prompts: + + + +### Understanding Hallucinations + + +Sometimes AI writes things that sound true but aren't. This is called "hallucination." It's not a bug. It's just how prediction works. Always double-check important facts. + + +Why does AI make things up? + +1. It tries to write text that sounds good, not text that's always true +2. The internet (where it learned) has mistakes too +3. It can't actually check if something is real + + + +- **Ask for sources**: Then check if those sources are real +- **Ask for step-by-step thinking**: So you can check each step +- **Double-check important facts**: Use Google or trusted websites +- **Ask "Are you sure?"**: The AI might admit uncertainty + + + + + +## How AI Learns: The Three Steps + +AI doesn't just magically know things. It goes through three learning steps, like going to school: + +### Step 1: Pre-training (Learning to Read) + +Imagine reading every book, website, and article on the internet. That's what happens in pre-training. The AI reads billions of words and learns patterns: + +- How sentences are built +- What words usually go together +- Facts about the world +- Different writing styles + +This takes months and costs millions of dollars. After this step, the AI knows a lot, but it's not very helpful yet. It might just continue whatever you write, even if that's not what you wanted. + + + +### Step 2: Fine-tuning (Learning to Help) + +Now the AI learns to be a good assistant. Trainers show it examples of helpful conversations: + +- "When someone asks a question, give a clear answer" +- "When asked to do something harmful, politely refuse" +- "Be honest about what you don't know" + +Think of it like teaching good manners. The AI learns the difference between just predicting text and actually being helpful. + + + +Try the prompt above. Notice how the AI refuses? That's fine-tuning at work. + +### Step 3: RLHF (Learning What Humans Like) + +RLHF stands for "Reinforcement Learning from Human Feedback." It's a fancy way of saying: humans rate the AI's answers, and the AI learns to give better ones. + +Here's how it works: +1. The AI writes two different answers to the same question +2. A human picks which answer is better +3. The AI learns: "Okay, I should write more like Answer A" +4. This happens millions of times + +This is why AI: +- Is polite and friendly +- Admits when it doesn't know something +- Tries to see different sides of an issue +- Avoids controversial statements + + +Knowing these three steps helps you understand AI behavior. When AI refuses a request, that's fine-tuning. When AI is extra polite, that's RLHF. When AI knows random facts, that's pre-training. + + +## What This Means for Your Prompts + +Now that you understand how AI works, here's how to use that knowledge: + +### 1. Be Clear and Specific + +AI predicts what comes next based on your words. Vague prompts lead to vague answers. Specific prompts get specific results. + + + + + +### 2. Give Context + +AI doesn't know anything about you unless you tell it. Each conversation starts fresh. Include the background information AI needs. + + + + + +### 3. Work With the AI, Not Against It + +Remember: AI was trained to be helpful. Ask for things the way you'd ask a helpful friend. + + + +### 4. Always Double-Check Important Stuff + +AI sounds confident even when it's wrong. For anything important, verify the information yourself. + + + +### 5. Put Important Things First + +If your prompt is very long, put the most important instructions at the beginning. AI pays more attention to what comes first. + +## Picking the Right AI + +Different AI models are good at different things: + +
+
+ Quick questions + Faster models like GPT-4o or Claude 3.5 Sonnet +
+
+ Hard problems + Smarter models like GPT-5.2 or Claude 4.5 Opus +
+
+ Writing code + Code-focused models or the smartest general models +
+
+ Long documents + Models with big context windows (Claude, Gemini) +
+
+ Current events + Models with internet access +
+
+ +## Summary + +AI language models are prediction machines trained on text. They're amazing at many things, but they have real limits. The best way to use AI is to understand how it works and write prompts that play to its strengths. + + + + + +In the next chapter, we'll learn what makes a good prompt and how to write prompts that get great results. diff --git a/src/content/book/el/02-anatomy-of-effective-prompt.mdx b/src/content/book/el/02-anatomy-of-effective-prompt.mdx new file mode 100644 index 00000000..03cd23d2 --- /dev/null +++ b/src/content/book/el/02-anatomy-of-effective-prompt.mdx @@ -0,0 +1,343 @@ +Every great prompt shares common structural elements. Understanding these components allows you to construct prompts systematically rather than through trial and error. + + +Think of these components like LEGO bricks. You don't need all of them for every prompt, but knowing what's available helps you build exactly what you need. + + +## The Core Components + +An effective prompt typically includes some or all of these elements: + + + +Let's examine each component in detail. + +## 1. Role / Persona + +Setting a role focuses the model's responses through the lens of a specific expertise or perspective. + + + +The role primes the model to: +- Use appropriate vocabulary +- Apply relevant expertise +- Maintain a consistent perspective +- Consider the audience appropriately + +### Effective Role Patterns + +``` +"You are a [profession] with [X years] of experience in [specialty]" +"Act as a [role] who is [characteristic]" +"You are an expert [field] helping a [audience type]" +``` + +## 2. Context / Background + +Context provides the information the model needs to understand your situation. Remember: the model knows nothing about you, your project, or your goals unless you tell it. + + + +### What to Include in Context + +- **Project details** — Technology stack, architecture, constraints +- **Current state** — What you've tried, what's working, what isn't +- **Goals** — What you're ultimately trying to achieve +- **Constraints** — Time limits, technical requirements, style guides + +## 3. Task / Instruction + +The task is the heart of your prompt—what you want the model to do. Be specific and unambiguous. + +### The Specificity Spectrum + + + +### Action Verbs That Work Well + +
+
+ Creation + Write, Create, Generate, Compose, Design +
+
+ Analysis + Analyze, Evaluate, Compare, Assess, Review +
+
+ Transformation + Convert, Translate, Reformat, Summarize, Expand +
+
+ Explanation + Explain, Describe, Clarify, Define, Illustrate +
+
+ Problem-solving + Solve, Debug, Fix, Optimize, Improve +
+
+ +## 4. Constraints / Rules + +Constraints bound the model's output. They prevent common issues and ensure relevance. + +### Types of Constraints + +**Length constraints:** +``` +"Keep your response under 200 words" +"Provide exactly 5 suggestions" +"Write 3-4 paragraphs" +``` + +**Content constraints:** +``` +"Do not include any code examples" +"Focus only on the technical aspects" +"Avoid marketing language" +``` + +**Style constraints:** +``` +"Use a formal, academic tone" +"Write as if speaking to a 10-year-old" +"Be direct and avoid hedging language" +``` + +**Scope constraints:** +``` +"Only consider options available in Python 3.10+" +"Limit suggestions to free tools" +"Focus on solutions that don't require additional dependencies" +``` + +## 5. Output Format + +Specifying the output format ensures you get responses in a usable structure. + +### Common Formats + +**Lists:** +``` +"Return as a bulleted list" +"Provide a numbered list of steps" +``` + +**Structured data:** +``` +"Return as JSON with keys: title, description, priority" +"Format as a markdown table with columns: Feature, Pros, Cons" +``` + +**Specific structures:** +``` +"Structure your response as: + ## Summary + ## Key Points + ## Recommendations" +``` + +### JSON Output Example + +``` +Analyze this customer review and return JSON: +{ + "sentiment": "positive" | "negative" | "neutral", + "topics": ["array of main topics"], + "rating_prediction": 1-5, + "key_phrases": ["notable phrases"] +} + +Review: "The product arrived quickly and works great, but +the instructions were confusing." +``` + +## 6. Examples (Few-Shot Learning) + +Examples are the most powerful way to show the model exactly what you want. + +### One-Shot Example + +``` +Convert these sentences to past tense. + +Example: +Input: "She walks to the store" +Output: "She walked to the store" + +Now convert: +Input: "They run every morning" +``` + +### Few-Shot Example + +``` +Classify these support tickets by urgency. + +Examples: +"My account was hacked" → Critical +"How do I change my password?" → Low +"Payment failed but I was charged" → High + +Classify: "The app crashes when I open settings" +``` + +## Putting It All Together + +Here's a complete prompt using all components: + + + +## The Minimal Effective Prompt + +Not every prompt needs all components. For simple tasks, a clear instruction may suffice: + +``` +Translate "Hello, how are you?" to Spanish. +``` + +Use additional components when: +- The task is complex or ambiguous +- You need specific formatting +- Results aren't matching expectations +- Consistency across multiple queries matters + +## Common Prompt Patterns + +These frameworks give you a simple checklist to follow when writing prompts. Click on each step to see an example. + + + + + +## Summary + +Effective prompts are constructed, not discovered. By understanding and applying these structural components, you can: + +- Get better results on the first try +- Debug prompts that aren't working +- Create reusable prompt templates +- Communicate your intentions clearly + + + + + +## Build Your Own Prompt + +Now it's your turn! Use this interactive prompt builder to construct your own prompt using the components you've learned: + + + + + +In the next chapter, we'll explore the core principles that guide prompt construction decisions. diff --git a/src/content/book/el/03-core-prompting-principles.mdx b/src/content/book/el/03-core-prompting-principles.mdx new file mode 100644 index 00000000..358df563 --- /dev/null +++ b/src/content/book/el/03-core-prompting-principles.mdx @@ -0,0 +1,373 @@ +Beyond structure, effective prompt engineering is guided by principles—fundamental truths that apply across models, tasks, and contexts. Master these principles, and you'll be able to adapt to any prompting challenge. + + +These principles apply to every AI model and every task. Learn them once, use them everywhere. + + +## Principle 1: Clarity Over Cleverness + +The best prompts are clear, not clever. AI models are literal interpreters—they work with exactly what you give them. + +### Be Explicit + + + +### Avoid Ambiguity + +Words can have multiple meanings. Choose precise language. + + + +### State the Obvious + +What's obvious to you isn't obvious to the model. Spell out assumptions. + +``` +You're helping me write a cover letter. + +Important context: +- I'm applying for a Software Engineer position at Google +- I have 5 years of experience in Python and distributed systems +- The role requires leadership experience (I've led a team of 4) +- I want to emphasize my open-source contributions +``` + +## Principle 2: Specificity Yields Quality + +Vague inputs produce vague outputs. Specific inputs produce specific, useful outputs. + +### The Specificity Ladder + + + +Each level adds specificity and dramatically improves output quality. + +### Specify These Elements + +
+
+ Audience + Who will read/use this? +
+
+ Length + How long/short should it be? +
+
+ Tone + Formal? Casual? Technical? +
+
+ Format + Prose? List? Table? Code? +
+
+ Scope + What to include/exclude? +
+
+ Purpose + What should this accomplish? +
+
+ +## Principle 3: Context Is King + +Models have no memory, no access to your files, and no knowledge of your situation. Everything relevant must be in the prompt. + +### Provide Sufficient Context + + + +### The Context Checklist + + +Ask yourself: Would a smart stranger understand this request? If not, add more context. + + + + +## Principle 4: Guide, Don't Just Ask + +Don't just ask for an answer—guide the model toward the answer you want. + +### Use Instructional Framing + + + +### Provide Reasoning Scaffolds + +For complex tasks, guide the reasoning process: + + + +## Principle 5: Iterate and Refine + +Prompt engineering is an iterative process. Your first prompt is rarely your best. + +### The Iteration Cycle + +``` +1. Write initial prompt +2. Review output +3. Identify gaps or issues +4. Refine prompt +5. Repeat until satisfied +``` + +### Common Refinements + +
+
+ Too verbose + Add "Be concise" or length limits +
+
+ Too vague + Add specific examples or constraints +
+
+ Wrong format + Specify exact output structure +
+
+ Missing aspects + Add "Make sure to include..." +
+
+ Wrong tone + Specify audience and style +
+
+ Inaccurate + Request citations or step-by-step reasoning +
+
+ +### Keep a Prompt Journal + +Document what works: +``` +Task: Code review +Version 1: "Review this code" → Too generic +Version 2: Added specific review criteria → Better +Version 3: Added example of good review → Excellent +Final: [Save successful prompt as template] +``` + +## Principle 6: Leverage the Model's Strengths + +Work with how models are trained, not against them. + +### Models Want to Be Helpful + +Frame requests as things a helpful assistant would naturally do: + + + +### Models Excel at Patterns + +If you need consistent output, show the pattern: + + + +### Models Can Role-Play + +Use personas to access different "modes" of response: + +``` +As a devil's advocate, argue against my proposal... +As a supportive mentor, help me improve... +As a skeptical investor, question this business plan... +``` + +## Principle 7: Control Output Structure + +Structured outputs are more useful than free-form text. + +### Request Specific Formats + +``` +Return your analysis as: + +SUMMARY: [1 sentence] + +KEY FINDINGS: +• [Finding 1] +• [Finding 2] +• [Finding 3] + +RECOMMENDATION: [1-2 sentences] + +CONFIDENCE: [Low/Medium/High] because [reason] +``` + +### Use Delimiters + +Clearly separate sections of your prompt: + +``` +### CONTEXT ### +[Your context here] + +### TASK ### +[Your task here] + +### FORMAT ### +[Desired format here] +``` + +### Request Machine-Readable Output + +For programmatic use: + +``` +Return only valid JSON, no explanation: +{ + "decision": "approve" | "reject" | "review", + "confidence": 0.0-1.0, + "reasons": ["string array"] +} +``` + +## Principle 8: Verify and Validate + +Never blindly trust model outputs, especially for important tasks. + +### Ask for Reasoning + +``` +Solve this problem and show your work step by step. +After solving, verify your answer by [checking method]. +``` + +### Request Multiple Perspectives + +``` +Give me three different approaches to solve this problem. +For each, explain the trade-offs. +``` + +### Build in Self-Checking + +``` +After generating the code, review it for: +- Syntax errors +- Edge cases +- Security vulnerabilities +List any issues found. +``` + +## Summary: The Principles at a Glance + + + + + +## Practice: Fill in the Blanks + +Test your understanding of the core principles by completing this prompt template: + + + + + +These principles form the foundation for everything that follows. In Part II, we'll apply them to specific techniques that dramatically enhance prompt effectiveness. diff --git a/src/content/book/el/04-role-based-prompting.mdx b/src/content/book/el/04-role-based-prompting.mdx new file mode 100644 index 00000000..ef178cbc --- /dev/null +++ b/src/content/book/el/04-role-based-prompting.mdx @@ -0,0 +1,328 @@ +Role-based prompting is one of the most powerful and widely-used techniques in prompt engineering. By assigning a specific role or persona to the AI, you can dramatically influence the quality, style, and relevance of responses. + + +Think of roles as filters for AI's vast knowledge. The right role focuses responses like a lens focuses light. + + +## Why Roles Work + +When you assign a role, you're essentially telling the model: "Filter your vast knowledge through this specific lens." The model adjusts its: + +- **Vocabulary**: Using terminology appropriate to the role +- **Perspective**: Considering problems from that viewpoint +- **Expertise depth**: Providing role-appropriate detail levels +- **Communication style**: Matching how that role would communicate + +### The Technical Explanation + +LLMs work by predicting the most likely next token based on the context they're given. When you specify a role, you're fundamentally changing what "likely" means. + +**Activating Relevant Knowledge**: The role primes specific regions of the model's learned associations. Saying "You are a doctor" activates medical terminology, diagnostic reasoning patterns, and clinical communication styles from the training data. + +**Statistical Conditioning**: LLMs learned from millions of documents written by real experts. When you assign a role, the model conditions its probability distributions to match patterns it saw from that type of author. + +**Reducing Ambiguity**: Without a role, the model averages across all possible responders. With a role, it narrows to a specific subset, making responses more focused and consistent. + +**Context Anchoring**: The role creates a persistent context anchor throughout the conversation. Every subsequent response is influenced by this initial framing. + +Think of it this way: if you ask "What should I do about this cough?" the model could respond as a doctor, a friend, a pharmacist, or a worried parent. Each would give different advice. By specifying the role upfront, you're telling the model which "voice" to use from its training data. + + +The model isn't pretending or role-playing in a theatrical sense. It's statistically biasing its outputs toward patterns it learned from real experts, professionals, and specialists during training. A "doctor" role activates medical knowledge pathways; a "poet" role activates literary patterns. + + +## Basic Role Patterns + +These foundational patterns work across most use cases. Start with these templates and customize them for your needs. + +### The Expert Pattern + +The most versatile pattern. Specify the field of expertise and years of experience to get authoritative, in-depth responses. Works well for technical questions, analysis, and professional advice. + + + +### The Professional Pattern + +Ground the role in a real-world context by specifying a job title and organization type. This adds institutional knowledge and professional norms to the response. + + + +### The Teacher Pattern + +Perfect for learning and explanations. Specifying the audience level ensures the response matches the learner's background, from beginners to advanced practitioners. + + + +## Advanced Role Constructions + +### Compound Roles + +Combine multiple identities to get responses that blend different perspectives. This pediatrician-parent combination produces advice that's both medically sound and practically tested. + + + +### Situational Roles + +Place the role in a specific scenario to shape both content and tone. Here, the code review context makes the AI constructive and educational rather than just critical. + + + +### Perspective Roles + +Get feedback from a specific stakeholder's point of view. A VC perspective evaluates viability and scalability differently than a customer or engineer would. + + + +## Role Categories and Examples + +Different domains benefit from different types of roles. Here are proven examples organized by category that you can adapt for your tasks. + +### Technical Roles + +**Software Architect**: Best for system design decisions, technology choices, and architectural trade-offs. The focus on maintainability steers responses toward practical, long-term solutions. + + + +**Security Specialist**: The attacker mindset is key here. This role produces threat-focused analysis that identifies vulnerabilities a defensive-only perspective might miss. + + + +**DevOps Engineer**: Ideal for deployment, automation, and infrastructure questions. The emphasis on reliability ensures production-ready recommendations. + + + +### Creative Roles + +**Copywriter**: The "award-winning" qualifier and conversion focus produce punchy, persuasive copy rather than generic marketing text. + + + +**Screenwriter**: Activates knowledge of dramatic structure, pacing, and dialogue conventions. Great for any narrative writing that needs tension and character voice. + + + +**UX Writer**: A specialized role for interface text. The focus on brevity and user guidance produces concise, action-oriented copy. + + + +### Analytical Roles + +**Business Analyst**: Bridges the gap between technical and non-technical stakeholders. Useful for requirement gathering, spec writing, and identifying gaps in project plans. + + + +**Research Scientist**: The emphasis on evidence and uncertainty acknowledgment produces balanced, well-sourced responses that distinguish facts from speculation. + + + +**Financial Analyst**: Combines quantitative analysis with risk assessment. The dual focus on returns and risk produces more balanced investment perspectives. + + + +### Educational Roles + +**Socratic Tutor**: Instead of giving answers, this role asks guiding questions. Excellent for deeper learning and helping students develop critical thinking skills. + + + +**Instructional Designer**: Structures learning for maximum retention. Use this role when you need to break down complex topics into teachable chunks with clear progression. + + + +## The Role Stack Technique + +For complex tasks, combine multiple role aspects into a single, layered identity. This technique stacks expertise, audience awareness, and style guidelines to create highly specialized responses. + +This example layers three elements: domain expertise (API documentation), audience (junior developers), and style guide (Google's conventions). Each layer constrains the output further. + + + +## Roles for Different Tasks + +
+
+ Code review + Senior developer + mentor +
+
+ Writing feedback + Editor + target audience member +
+
+ Business strategy + Consultant + industry expert +
+
+ Learning new topic + Patient teacher + practitioner +
+
+ Creative writing + Specific genre author +
+
+ Technical explanation + Expert + communicator +
+
+ Problem-solving + Domain specialist + generalist +
+
+ +## Anti-Patterns to Avoid + +### Overly Generic Roles + + + +### Conflicting Roles + + + +### Unrealistic Expertise + + + +## Real-World Prompt Examples + +### Technical Documentation + + + +### Creative Writing + + + +### Business Communication + + + +## Combining Roles with Other Techniques + +Roles work even better when combined with other prompting techniques: + +### Role + Few-Shot + +Combine a role with an example to show exactly how the role should respond. The example teaches tone and format while the role provides context and expertise. + + + +### Role + Chain of Thought + +The detective role naturally encourages step-by-step reasoning. Combining roles with chain-of-thought produces more transparent, verifiable problem-solving. + + + +## Summary + + +Role-based prompting is powerful because it focuses the model's vast knowledge, sets expectations for tone and style, provides implicit context, and makes outputs more consistent. + + + + +The key is **specificity**: the more detailed and realistic the role, the better the results. In the next chapter, we'll explore how to get consistent, structured outputs from your prompts. diff --git a/src/content/book/el/05-structured-output.mdx b/src/content/book/el/05-structured-output.mdx new file mode 100644 index 00000000..8236abee --- /dev/null +++ b/src/content/book/el/05-structured-output.mdx @@ -0,0 +1,411 @@ +Getting consistent, well-formatted output is essential for production applications and efficient workflows. This chapter covers techniques for controlling exactly how AI models format their responses. + + +Structured output transforms AI responses from freeform text into actionable, parseable data. + + +## Why Structure Matters + + + +## Basic Formatting Techniques + +### Lists + +Lists are perfect for step-by-step instructions, ranked items, or collections of related points. They're easy to scan and parse. Use **numbered lists** when order matters (steps, rankings) and **bullet points** for unordered collections. + + + + +Specify the exact number of items you want, whether to include explanations, and if items should be bold or have a specific structure. + + +### Tables + +Tables excel at comparing multiple items across the same dimensions. They're ideal for feature comparisons, data summaries, and any information with consistent attributes. Always define your column headers explicitly. + + + + +Specify column names, expected data types (text, numbers, ratings), and how many rows you need. For complex comparisons, limit to 4-6 columns for readability. + + +### Headers and Sections + +Headers create a clear document structure, making long responses scannable and organized. Use them for reports, analyses, or any multi-part response. Hierarchical headers (##, ###) show relationships between sections. + +``` +Analyze this business proposal. + +Structure your response with these sections: +## Executive Summary +## Strengths +## Weaknesses +## Recommendations +## Risk Assessment +``` + + +List your sections in the order you want them. For consistency, specify what each section should contain (e.g., "Executive Summary: 2-3 sentences only"). + + +### Emphasis with Uppercase Directives + +Uppercase words act as strong signals to the model, emphasizing critical constraints or requirements. Use them sparingly for maximum impact—overuse dilutes their effectiveness. + +**Common Uppercase Directives:** + + + +``` +Summarize this article. + +IMPORTANT: Keep the summary under 100 words. +NEVER add information not present in the original. +ALWAYS maintain the original tone and perspective. +DO NOT include your own opinions or analysis. +``` + + +If everything is uppercase or marked as critical, nothing stands out. Reserve these directives for genuinely important constraints. + + +## JSON Output + +JSON (JavaScript Object Notation) is the most popular format for structured AI output. It's machine-readable, widely supported by programming languages, and perfect for APIs, databases, and automation workflows. The key to reliable JSON is providing a clear schema. + +### Basic JSON Request + +Start with a template showing the exact structure you want. Include field names, data types, and example values. This acts as a contract the model will follow. + + + +### Complex JSON Structures + +For nested data, use hierarchical JSON with objects inside objects, arrays of objects, and mixed types. Define each level clearly and use TypeScript-style annotations (`"positive" | "negative"`) to constrain values. + +``` +Analyze this product review and return JSON: + +{ + "review_id": "string (generate unique)", + "sentiment": { + "overall": "positive" | "negative" | "mixed" | "neutral", + "score": 0.0-1.0 + }, + "aspects": [ + { + "aspect": "string (e.g., 'price', 'quality')", + "sentiment": "positive" | "negative" | "neutral", + "mentions": ["exact quotes from review"] + } + ], + "purchase_intent": { + "would_recommend": boolean, + "confidence": 0.0-1.0 + }, + "key_phrases": ["string array of notable phrases"] +} + +Return ONLY valid JSON, no additional text. + +Review: "[review text]" +``` + +### Ensuring Valid JSON + +Models sometimes add explanatory text or markdown formatting around JSON. Prevent this with explicit instructions about output format. You can request raw JSON or JSON inside code blocks—choose based on your parsing needs. + +Add explicit instructions: + +``` +IMPORTANT: +- Return ONLY the JSON object, no markdown code blocks +- Ensure all strings are properly escaped +- Use null for missing values, not undefined +- Validate that the output is parseable JSON +``` + +Or request code blocks by asking the model to wrap its output: + +```` +Return the result as a JSON code block: +```json +{ ... } +``` +```` + +## YAML Output + +YAML is more human-readable than JSON, using indentation instead of brackets. It's the standard for configuration files (Docker, Kubernetes, GitHub Actions) and works well when the output will be read by humans or used in DevOps contexts. YAML is sensitive to indentation, so be specific about formatting requirements. + + + +## XML Output + +XML is still required for many enterprise systems, SOAP APIs, and legacy integrations. It's more verbose than JSON but offers features like attributes, namespaces, and CDATA sections for complex data. Specify element names, nesting structure, and where to use attributes vs. child elements. + +``` +Convert this data to XML format: + +Requirements: +- Root element: +- Each item in element +- Include attributes where appropriate +- Use CDATA for description text + +Data: [book data] +``` + +## Custom Formats + +Sometimes standard formats don't fit your needs. You can define any custom format by providing a clear template. Custom formats work well for reports, logs, or domain-specific outputs that will be read by humans. + +### Structured Analysis Format + +Use delimiters (===, ---, [SECTION]) to create scannable documents with clear boundaries between sections. This format is great for code reviews, audits, and analyses. + +``` +Analyze this code using this exact format: + +=== CODE ANALYSIS === + +[SUMMARY] +One paragraph overview + +[ISSUES] +• CRITICAL: [issue] — [file:line] +• WARNING: [issue] — [file:line] +• INFO: [issue] — [file:line] + +[METRICS] +Complexity: [Low/Medium/High] +Maintainability: [score]/10 +Test Coverage: [estimated %] + +[RECOMMENDATIONS] +1. [Priority 1 recommendation] +2. [Priority 2 recommendation] + +=== END ANALYSIS === +``` + +### Fill-in-the-Blank Format + +Templates with blanks (___) guide the model to fill in specific fields while maintaining exact formatting. This approach is excellent for forms, briefs, and standardized documents where consistency matters. + +``` +Complete this template for the given product: + +PRODUCT BRIEF +───────────── +Name: _______________ +Tagline: _______________ +Target User: _______________ +Problem Solved: _______________ +Key Features: + 1. _______________ + 2. _______________ + 3. _______________ +Differentiator: _______________ + +Product: [product description] +``` + +## Typed Responses + +Typed responses define categories or entity types that the model should recognize and label. This technique is essential for Named Entity Recognition (NER), classification tasks, and any extraction where you need to categorize information consistently. Define your types clearly with examples. + + + +## Multi-Part Structured Responses + +When you need comprehensive output covering multiple aspects, define distinct parts with clear boundaries. Specify exactly what goes in each part—format, length, and content type. This prevents the model from blending sections or omitting parts. + +``` +Research this topic and provide: + +### PART 1: EXECUTIVE SUMMARY +[2-3 sentence overview] + +### PART 2: KEY FINDINGS +[Exactly 5 bullet points] + +### PART 3: DATA TABLE +| Metric | Value | Source | +|--------|-------|--------| +[Include 5 rows minimum] + +### PART 4: RECOMMENDATIONS +[Numbered list of 3 actionable recommendations] + +### PART 5: FURTHER READING +[3 suggested resources with brief descriptions] +``` + +## Conditional Formatting + +Conditional formatting lets you define different output formats based on the input's characteristics. This is powerful for classification, triage, and routing systems where the response format should vary based on what the model detects. Use clear if/then logic with explicit output templates for each case. + + + +## Arrays and Lists in JSON + +Extracting multiple items into arrays requires careful schema definition. Specify the array structure, what each item should contain, and how to handle edge cases (empty arrays, single items). Including a count field helps verify completeness. + +``` +Extract all action items from this meeting transcript. + +Return as JSON array: +{ + "action_items": [ + { + "task": "string describing the task", + "assignee": "person name or 'Unassigned'", + "deadline": "date if mentioned, else null", + "priority": "high" | "medium" | "low", + "context": "relevant quote from transcript" + } + ], + "total_count": number +} + +Transcript: "[meeting transcript]" +``` + +## Validation Instructions + +Self-validation prompts the model to check its own output before responding. This catches common issues like missing sections, placeholder text, or constraint violations. The model will iterate internally to fix problems, improving output quality without additional API calls. + +``` +Generate the report, then: + +VALIDATION CHECKLIST: +□ All required sections present +□ No placeholder text remaining +□ All statistics include sources +□ Word count within 500-700 words +□ Conclusion ties back to introduction + +If any check fails, fix before responding. +``` + +## Handling Optional Fields + +Real-world data often has missing values. Explicitly instruct the model on how to handle optional fields—using `null` is cleaner than empty strings and easier to process programmatically. Also prevent "hallucination" of missing data by emphasizing that the model should never invent information. + +``` +Extract contact information. Use null for missing fields. + +{ + "name": "string (required)", + "email": "string or null", + "phone": "string or null", + "company": "string or null", + "role": "string or null", + "linkedin": "URL string or null" +} + +IMPORTANT: +- Never invent information not in the source +- Use null, not empty strings, for missing data +- Phone numbers in E.164 format if possible +``` + +## Summary + + +Be explicit about format, use examples, specify types, handle edge cases with null values, and ask the model to validate its own output. + + + + +Structured outputs are essential for building reliable AI-powered applications. In the next chapter, we'll explore chain-of-thought prompting for complex reasoning tasks. diff --git a/src/content/book/el/06-chain-of-thought.mdx b/src/content/book/el/06-chain-of-thought.mdx new file mode 100644 index 00000000..e579be5d --- /dev/null +++ b/src/content/book/el/06-chain-of-thought.mdx @@ -0,0 +1,363 @@ +Chain of Thought (CoT) prompting is a technique that dramatically improves AI performance on complex reasoning tasks by asking the model to show its work step by step. + + +Just like a math teacher asking students to show their work, CoT prompting asks the AI to make its reasoning visible. + + +## The Problem CoT Solves + +AI models can struggle with multi-step reasoning when asked to jump directly to an answer. + + + +## Basic CoT Prompts + +### Simple Trigger Phrases + +Add one of these to your prompts: + +
+
"Let's think step by step."
+
"Think through this carefully."
+
"Work through this problem methodically."
+
"Show your reasoning at each step."
+
"Explain your thought process."
+
+ +### Explicit Step Request + + + +## Zero-Shot vs Few-Shot CoT + +There are two main approaches to Chain of Thought prompting, each with different trade-offs between simplicity and control. + +### Zero-Shot CoT + +The simplest approach—just add a trigger phrase and let the model figure out how to reason. No examples needed. This works surprisingly well for many problems, though you have less control over the reasoning format. + + + +**Example Output:** +``` +Let's think step by step. +- John starts with 3 apples +- Half of 3 is 1.5, but we can't split apples +- If we round down: John gives 1 apple, keeps 2 +- After buying 4 more: 2 + 4 = 6 apples + +Answer: 6 apples +``` + +### Few-Shot CoT + +For more consistent results, show the model exactly how you want it to reason by providing worked examples. This gives you control over the reasoning style, format, and level of detail. The model will mimic your demonstrated pattern. + + + +**Example Output:** +``` +A: Let's work through this: +- Regular price: $3, Quantity: 12 +- Since 12 ≥ 10, the 25% discount applies +- Regular total: 12 × $3 = $36 +- Discount: 25% of $36 = $9 +- Final price: $36 - $9 = $27 +``` + +## Structured CoT Formats + +For consistent, reproducible reasoning, use structured formats with named steps. These frameworks ensure the model doesn't skip important stages and makes outputs easier to parse and verify. + +### The BREAK Format + +A memorable acronym that guides the model through a complete problem-solving cycle, from understanding to verification. + + + +### The Reasoning Template + +A more formal structure that separates inputs, goals, and execution. Excellent for technical problems where you need clear documentation of the solution process. + + + +**Example Output:** +``` +GIVEN: 8L/100km, tank 45L, $1.50/L, drive 300km +GOAL: Calculate fuel cost +APPROACH: Fuel needed × cost per liter +STEPS: +1. Fuel = (300 ÷ 100) × 8 = 24 liters +2. Cost = 24 × $1.50 = $36 +VERIFICATION: 24L < 45L tank ✓ +ANSWER: $36 +``` + +## CoT for Different Problem Types + +Different problem types benefit from different CoT approaches. Here are patterns optimized for common scenarios. + +### Mathematical Reasoning + +Math problems benefit most from CoT because each step builds on the previous one. Errors compound, so showing work helps catch mistakes early. The model should clearly label each calculation. + + + +**Example Output:** +``` +Q1: $1,200,000 (given) +Q2: $1,200,000 × 1.15 = $1,380,000 +Q3: $1,380,000 × 0.90 = $1,242,000 +Q4: $1,242,000 × 1.25 = $1,552,500 + +Total: $5,374,500 +``` + +### Logical Reasoning + +Logic puzzles require systematic elimination and hypothesis testing. CoT helps the model track constraints, test possibilities, and verify that all conditions are satisfied. The key is methodical exploration rather than guessing. + + + +**Example Output:** +``` +From clue 3: Bob = teacher +→ Alice and Carol are engineer/doctor + +If Carol = engineer: +- Carol has dog (clue 2) +- Alice = doctor, has fish (clue 1) +- Bob has cat + +Verify: All 4 clues satisfied ✓ +Answer: Alice (doctor, fish), Bob (teacher, cat), Carol (engineer, dog) +``` + +### Code Debugging + +Debugging benefits from CoT because it forces the model to trace execution rather than guess at bugs. By walking through the code with concrete values, the actual behavior becomes visible and discrepancies with expected behavior are exposed. + + + +**Example Output:** +``` +Trace [2, 3, 4, 6]: +n=2: total += 1 → 1 (wait, adding 1 not n!) +n=3: skip (odd) +n=4: total = 2 +n=6: total = 3 + +BUG: "total += 1" should be "total += n" +Expected: 12, Got: 3 +Fix: Change to "total += n" +``` + +## Self-Consistency with CoT + +For critical problems, don't rely on a single reasoning path. Generate multiple independent solutions and compare results. If different approaches converge on the same answer, confidence is high. Disagreement signals the need for careful review. + + + +**Example Output:** +``` +Approach 1 (Algebra): c + w = 30, 2c + 4w = 74 → c=23, w=7 +Approach 2 (Guess): Try 23/7 → 46 + 28 = 74 ✓ +Approach 3 (Logic): 30 chickens = 60 legs, need 14 more → 7 cows + +All agree: 23 chickens, 7 cows +``` + +## CoT for Decision Making + +Decisions involve weighing trade-offs across multiple dimensions. CoT ensures all relevant factors are considered systematically rather than jumping to conclusions. This structured approach also documents the reasoning for future reference. + + + +**Example Output:** +``` +FACTORS: +- Team size (5): Too small for microservices ❌ +- Scale (100 DAU): No scaling need ❌ +- Velocity: Monolith = faster iteration ❌ +- Future growth: Uncertain timeline ⚠️ + +WEIGHING: 3 strong against, 1 weak for + +RECOMMENDATION: Stay monolith, use clear module +boundaries to ease future transition. +``` + +## When to Use CoT + +
+
+

Use CoT For

+
+

**Math problems** — Reduces calculation errors

+

**Logic puzzles** — Prevents skipped steps

+

**Complex analysis** — Organizes thinking

+

**Code debugging** — Traces execution

+

**Decision making** — Weighs trade-offs

+
+
+
+

Skip CoT For

+
+

**Simple Q&A** — Unnecessary overhead

+

**Creative writing** — Can constrain creativity

+

**Factual lookups** — No reasoning needed

+

**Translation** — Direct task

+

**Summarization** — Usually straightforward

+
+
+
+ +## CoT Limitations + +While powerful, Chain of Thought isn't a silver bullet. Understanding its limitations helps you apply it appropriately. + +1. **Increased token usage** — More output means higher costs +2. **Not always needed** — Simple tasks don't benefit +3. **Can be verbose** — May need to ask for conciseness +4. **Reasoning can be flawed** — CoT doesn't guarantee correctness + +## Summary + + +CoT dramatically improves complex reasoning by making implicit steps explicit. Use it for math, logic, analysis, and debugging. Trade-off: better accuracy for more tokens. + + + + +In the next chapter, we'll explore few-shot learning—teaching the model through examples. diff --git a/src/content/book/el/07-few-shot-learning.mdx b/src/content/book/el/07-few-shot-learning.mdx new file mode 100644 index 00000000..24e98f1d --- /dev/null +++ b/src/content/book/el/07-few-shot-learning.mdx @@ -0,0 +1,478 @@ +Few-shot learning is one of the most powerful prompting techniques. By providing examples of what you want, you can teach the model complex tasks without any fine-tuning. + + +Just like humans learn by seeing examples, AI models can learn patterns from the examples you provide in your prompt. + + +## What is Few-Shot Learning? + +Few-shot learning shows the model examples of input-output pairs before asking it to perform the same task. The model learns the pattern from your examples and applies it to new inputs. + + + +
+
+
0
+
Zero-shot
+
+
+
1
+
One-shot
+
+
+
2-5
+
Few-shot
+
+
+
5+
+
Many-shot
+
+
+ +## Why Examples Work + + + +Examples communicate: +- **Format**: How output should be structured +- **Style**: Tone, length, vocabulary +- **Logic**: The reasoning pattern to follow +- **Edge cases**: How to handle special situations + +## Basic Few-Shot Pattern + +The fundamental structure of few-shot prompting follows a simple pattern: show examples, then ask for the new task. Consistency in formatting between examples is crucial. The model learns from the pattern you establish. + +``` +[Example 1] +Input: [input 1] +Output: [output 1] + +[Example 2] +Input: [input 2] +Output: [output 2] + +[Example 3] +Input: [input 3] +Output: [output 3] + +Now do this one: +Input: [new input] +Output: +``` + +## Few-Shot for Classification + +Classification is one of the strongest use cases for few-shot learning. By showing examples of each category, you define the boundaries between classes more precisely than instructions alone could achieve. + +### Sentiment Analysis + + +Sentiment analysis classifies text by emotional tone: positive, negative, neutral, or mixed. It's widely used for customer feedback, social media monitoring, and brand perception tracking. + + +Sentiment classification benefits from showing examples of each sentiment type, especially edge cases like "mixed" sentiment that might be ambiguous. + + + +### Topic Classification + +For multi-class categorization, include at least one example per category. This helps the model understand your specific taxonomy, which may differ from its default understanding. + + + +## Few-Shot for Transformation + +Transformation tasks convert input from one form to another while preserving meaning. Examples are essential here because they define exactly what "transformation" means for your use case. + +### Text Rewriting + +Style transformation requires examples that show the exact tone shift you want. Abstract instructions like "make it professional" are interpreted differently. Examples make it concrete. + + + +### Format Conversion + +Format conversion tasks benefit from examples showing edge cases and ambiguous inputs. The model learns your specific conventions for handling tricky cases. + + + +## Few-Shot for Generation + +Generation tasks create new content following a learned pattern. Examples establish length, structure, tone, and what details to highlight. These are hard to specify in instructions alone. + +### Product Descriptions + +Marketing copy benefits enormously from examples because they capture brand voice, feature emphasis, and persuasive techniques that are difficult to describe abstractly. + + + +### Code Documentation + + +Good documentation explains what code does, its parameters, return values, and usage examples. Consistent docstrings enable auto-generated API docs and help IDEs provide better code completion. + + +Documentation style varies widely between projects. Examples teach your specific format, what to include (args, returns, examples), and the level of detail expected. + +>> calculate_bmi(70, 1.75) + 22.86 +""" + +Now document: +Function: +def is_palindrome(text): + cleaned = ''.join(c.lower() for c in text if c.isalnum()) + return cleaned == cleaned[::-1] + +Documentation:`} /> + +## Few-Shot for Extraction + +Extraction tasks pull structured information from unstructured text. Examples define which entities matter, how to format output, and how to handle cases where information is missing or ambiguous. + +### Entity Extraction + + +Named Entity Recognition (NER) identifies and classifies named entities in text into categories like persons, organizations, locations, dates, and products. It's fundamental for information retrieval and knowledge graphs. + + +NER benefits from examples showing your specific entity types and how to handle entities that could fit multiple categories. + + + +### Structured Data Extraction + +Extracting structured data from natural language requires examples showing how to handle missing fields, implicit information, and varying input formats. + + + +## Advanced Few-Shot Techniques + +Beyond basic few-shot, several techniques can improve results for complex tasks. + +### Diverse Examples + +Diversity in examples is more valuable than quantity. Cover different scenarios, edge cases, and potential ambiguities rather than showing similar examples repeatedly. + + + +### Negative Examples + + +Showing "good" vs "bad" examples is called contrastive learning. It helps the model understand not just what you want, but what to avoid. This is especially useful for style and quality judgments. + + +Sometimes showing what *not* to do is as valuable as showing correct examples. Negative examples help the model understand boundaries and avoid common mistakes. + + + +### Edge Case Examples + +Edge cases often determine whether a solution works in production. Including unusual inputs in your examples prevents the model from failing on real-world data that doesn't fit the "happy path." + + + +## How Many Examples? + +
+
+ Simple classification + 2-3 + One per category minimum +
+
+ Complex formatting + 3-5 + Show variations +
+
+ Nuanced style + 4-6 + Capture full range +
+
+ Edge cases + 1-2 + Alongside normal examples +
+
+ +## Example Quality Matters + + + +## Combining Few-Shot with Other Techniques + +Few-shot learning combines powerfully with other prompting techniques. The examples provide the "what" while other techniques can add context, reasoning, or structure. + +### Few-Shot + Role + +Adding a role gives the model context for *why* it's doing the task, which can improve quality and consistency. + +``` +You are a legal contract reviewer. + +[examples of contract clause analysis] + +Now analyze: [new clause] +``` + +### Few-Shot + CoT + +Combining few-shot with Chain of Thought shows not just *what* answer to give, but *how* to reason through to that answer. This is powerful for tasks requiring judgment. + +``` +Classify and explain reasoning. + +Review: "Great features but overpriced" +Thinking: The review mentions positive aspects ("great features") +but also a significant negative ("overpriced"). The negative seems +to outweigh the positive based on the "but" conjunction. +Classification: Mixed-Negative + +[more examples with reasoning] + +Now classify with reasoning: +Review: "Exactly what I needed, arrived faster than expected" +``` + +## Summary + + +Few-shot learning teaches through demonstration and is often more effective than instructions alone. Use 2-5 diverse, correct examples and combine with other techniques for best results. + + + + +In the next chapter, we'll explore iterative refinement: the art of improving prompts through successive attempts. diff --git a/src/content/book/el/08-iterative-refinement.mdx b/src/content/book/el/08-iterative-refinement.mdx new file mode 100644 index 00000000..769f879a --- /dev/null +++ b/src/content/book/el/08-iterative-refinement.mdx @@ -0,0 +1,387 @@ +Prompt engineering is rarely a one-shot process. The best prompts emerge through iteration—testing, observing, and refining until you achieve the desired results. + + +Think of your first prompt as a rough draft. Even experienced prompt engineers rarely nail it on the first try. + + +## The Iteration Cycle + +Effective prompt refinement follows a predictable cycle: write, test, analyze, and improve. Each iteration brings you closer to a prompt that reliably produces the results you need. + + + +## Common Refinement Patterns + +Most prompt failures fall into a handful of categories. Learning to recognize these patterns lets you quickly diagnose and fix issues without starting from scratch. + +### Problem: Output Too Long + +One of the most common issues. Without explicit constraints, models tend to be thorough rather than concise. + + + +### Problem: Output Too Vague + +Vague prompts produce vague outputs. The model can't read your mind about what "better" means or which aspects matter most to you. + + + +### Problem: Wrong Tone + +Tone is subjective and varies by context. What sounds "professional" to the model might not match your organization's voice or the relationship with your recipient. + + + +### Problem: Missing Key Information + +Open-ended requests get open-ended responses. If you need specific types of feedback, you must ask for them explicitly. + + + +### Problem: Inconsistent Format + +Without a template, the model will structure each response differently, making comparison difficult and automation impossible. + + + +## Systematic Refinement Approach + +Random changes waste time. A systematic approach helps you identify problems quickly and fix them efficiently. + +### Step 1: Diagnose the Issue + +Before changing anything, identify what's actually wrong. Use this diagnostic table to map symptoms to solutions: + +
+
+ Symptom + Likely Cause + Solution +
+
+ Too long + No length constraint + Add word/sentence limits +
+
+ Too short + Lacks detail request + Ask for elaboration +
+
+ Off-topic + Vague instructions + Be more specific +
+
+ Wrong format + Format not specified + Define exact structure +
+
+ Wrong tone + Audience not clear + Specify audience/style +
+
+ Inconsistent + No examples provided + Add few-shot examples +
+
+ +### Step 2: Make Targeted Changes + +Resist the urge to rewrite everything. Changing multiple variables at once makes it impossible to know what helped and what hurt. Make one change, test it, then proceed: + +``` +Iteration 1: Add length constraint +Iteration 2: Specify format +Iteration 3: Add example +Iteration 4: Refine tone instructions +``` + +### Step 3: Document What Works + +Prompt engineering knowledge is easily lost. Keep a log of what you tried and why. This saves time when you revisit the prompt later or face similar challenges: + +```markdown +## Prompt: Customer Email Response + +### Version 1 (too formal) +"Write a response to this customer complaint." + +### Version 2 (better tone, still missing structure) +"Write a friendly but professional response to this complaint. +Show empathy first." + +### Version 3 (final - good results) +"Write a response to this customer complaint. Structure: +1. Acknowledge their frustration (1 sentence) +2. Apologize specifically (1 sentence) +3. Explain solution (2-3 sentences) +4. Offer additional help (1 sentence) + +Tone: Friendly, professional, empathetic but not groveling." +``` + +## Real-World Iteration Example + +Let's walk through a complete iteration cycle to see how each refinement builds on the last. Notice how each version addresses specific shortcomings of the previous one. + +### Task: Generate Product Names + + + +## Refinement Strategies by Task Type + +Different tasks fail in predictable ways. Knowing the common failure modes helps you diagnose and fix issues faster. + +### For Content Generation + +Content generation often produces generic, off-target, or poorly formatted output. The fix usually involves being more specific about constraints, providing concrete examples, or defining your brand voice explicitly. + + + +### For Code Generation + +Code output can fail technically (syntax errors, wrong language features) or architecturally (poor patterns, missing cases). Technical issues need version/environment specifics; architectural issues need design guidance. + + + +### For Analysis + +Analysis tasks often produce surface-level or unstructured results. Guide the model with specific frameworks (SWOT, Porter's Five Forces), request multiple viewpoints, or provide a template for the output structure. + + + +### For Q&A + +Question-answering can be too terse or too verbose, and may lack confidence indicators or sources. Specify the detail level you need and whether you want citations or uncertainty expressed. + + + +## The Feedback Loop Technique + +Here's a meta-technique: use the model itself to help improve your prompts. Share what you tried, what you got, and what you wanted. The model can often suggest improvements you hadn't considered. + +``` +I used this prompt: +"[your prompt]" + +And got this output: +"[model output]" + +I wanted something more [describe gap]. How should I modify +my prompt to get better results? +``` + +## A/B Testing Prompts + +For prompts that will be used repeatedly or at scale, don't just pick the first one that works. Test variations to find the most reliable and highest-quality approach. + +``` +Prompt A: "Summarize this article in 3 bullet points." +Prompt B: "Extract the 3 most important insights from this article." +Prompt C: "What are the key takeaways from this article? List 3." +``` + +Run each multiple times, compare: +- Consistency of output +- Quality of information +- Relevance to your needs + +## When to Stop Iterating + +Perfection is the enemy of good enough. Know when your prompt is ready for use and when you're just polishing for diminishing returns. + +
+
+

Ready to Ship

+
+

Output consistently meets requirements

+

Edge cases are handled appropriately

+

Format is reliable and parseable

+

Further improvements show diminishing returns

+
+
+
+

Keep Iterating

+
+

Output is inconsistent across runs

+

Edge cases cause failures

+

Critical requirements are missed

+

You haven't tested enough variations

+
+
+
+ +## Version Control for Prompts + +Prompts are code. For any prompt used in production, treat it with the same rigor: version control, changelogs, and the ability to roll back if something breaks. + + +prompts.chat includes automatic version history for your prompts. Every edit is saved, so you can compare versions and restore previous iterations with one click. + + +For self-managed prompts, use a folder structure: + +``` +prompts/ +├── customer-response/ +│ ├── v1.0.txt # Initial version +│ ├── v1.1.txt # Fixed tone issue +│ ├── v2.0.txt # Major restructure +│ └── current.txt # Symlink to active version +└── changelog.md # Document changes +``` + +## Summary + + +Start simple, observe carefully, change one thing at a time, document what works, and know when to stop. The best prompts aren't written—they're discovered through systematic iteration. + + + + +## Practice: Improve This Prompt + +Try improving this weak prompt yourself. Edit it, then use AI to compare your version with the original: + + + +In the next chapter, we'll explore JSON and YAML prompting for structured data applications. diff --git a/src/content/book/el/09-json-yaml-prompting.mdx b/src/content/book/el/09-json-yaml-prompting.mdx new file mode 100644 index 00000000..318619da --- /dev/null +++ b/src/content/book/el/09-json-yaml-prompting.mdx @@ -0,0 +1,586 @@ +Structured data formats like JSON and YAML are essential for building applications that consume AI outputs programmatically. This chapter covers techniques for reliable structured output generation. + + +JSON and YAML transform AI outputs from freeform text into structured, type-safe data that code can consume directly. + + +## Why Structured Formats? + + + +## JSON Prompting Basics + +JSON (JavaScript Object Notation) is the most common format for programmatic AI outputs. Its strict syntax makes it easy to parse, but also means small errors can break your entire pipeline. + +### Do's and Don'ts: Requesting JSON + + + +### Simple JSON Output + +Start with a schema showing the expected structure. The model will fill in values based on the input text. + +``` +Extract the following information as JSON: + +{ + "name": "string", + "age": number, + "email": "string" +} + +Text: "Contact John Smith, 34 years old, at john@example.com" +``` + +Output: +```json +{ + "name": "John Smith", + "age": 34, + "email": "john@example.com" +} +``` + +### Nested JSON Structures + +Real-world data often has nested relationships. Define each level of your schema clearly, especially for arrays of objects. + +``` +Parse this order into JSON: + +{ + "order_id": "string", + "customer": { + "name": "string", + "email": "string" + }, + "items": [ + { + "product": "string", + "quantity": number, + "price": number + } + ], + "total": number +} + +Order: "Order #12345 for Jane Doe (jane@email.com): 2x Widget ($10 each), +1x Gadget ($25). Total: $45" +``` + +### Ensuring Valid JSON + + +Models often wrap JSON in markdown code blocks or add explanatory text. Be explicit about wanting raw JSON only. + + +Add explicit instructions: + +``` +CRITICAL: Return ONLY valid JSON. No markdown, no explanation, +no additional text before or after the JSON object. + +If a field cannot be determined, use null. +Ensure all strings are properly quoted and escaped. +Numbers should not be quoted. +``` + +## YAML Prompting Basics + +YAML is more human-readable than JSON and supports comments. It's the standard for configuration files, especially in DevOps (Docker, Kubernetes, GitHub Actions). + +### Simple YAML Output + +YAML uses indentation instead of braces. Provide a template showing the expected structure. + +``` +Generate a configuration file in YAML format: + +server: + host: string + port: number + ssl: boolean +database: + type: string + connection_string: string + +Requirements: Production server on port 443 with SSL, PostgreSQL database +``` + +Output: +```yaml +server: + host: "0.0.0.0" + port: 443 + ssl: true +database: + type: "postgresql" + connection_string: "postgresql://user:pass@localhost:5432/prod" +``` + +### Complex YAML Structures + +For complex configurations, be specific about requirements. The model knows common patterns for tools like GitHub Actions, Docker Compose, and Kubernetes. + +``` +Generate a GitHub Actions workflow in YAML: + +Requirements: +- Trigger on push to main and pull requests +- Run on Ubuntu latest +- Steps: checkout, setup Node 18, install dependencies, run tests +- Cache npm dependencies +``` + +## Type Definitions in Prompts + +Type definitions give the model a precise contract for output structure. They're more explicit than examples and easier to validate programmatically. + +### Using TypeScript-like Types + +TypeScript interfaces are familiar to developers and precisely describe optional fields, union types, and arrays. The prompts.chat platform uses this approach for structured prompts. + + + +### JSON Schema Definition + + +JSON Schema is a formal specification for describing JSON structure. It's supported by many validation libraries and API tools. + + +JSON Schema provides constraints like min/max values, required fields, and regex patterns: + +``` +Extract data according to this JSON Schema: + +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "type": "object", + "required": ["title", "author", "year"], + "properties": { + "title": { "type": "string" }, + "author": { "type": "string" }, + "year": { "type": "integer", "minimum": 1000, "maximum": 2100 }, + "genres": { + "type": "array", + "items": { "type": "string" } + }, + "rating": { + "type": "number", + "minimum": 0, + "maximum": 5 + } + } +} + +Book: "1984 by George Orwell (1949) - A dystopian masterpiece. +Genres: Science Fiction, Political Fiction. Rated 4.8/5" +``` + +## Handling Arrays + +Arrays require special attention. Specify whether you need a fixed number of items or a variable-length list, and how to handle empty cases. + +### Fixed-Length Arrays + +When you need exactly N items, state it explicitly. The model will ensure the array has the right length. + +``` +Extract exactly 3 key points as JSON: + +{ + "key_points": [ + "string (first point)", + "string (second point)", + "string (third point)" + ] +} + +Article: [article text] +``` + +### Variable-Length Arrays + +For variable-length arrays, specify what to do when there are zero items. Including a count field helps verify extraction completeness. + +``` +Extract all mentioned people as JSON: + +{ + "people": [ + { + "name": "string", + "role": "string or null if not mentioned" + } + ], + "count": number +} + +If no people are mentioned, return empty array. + +Text: [text] +``` + +## Enum Values and Constraints + +Enums restrict values to a predefined set. This is crucial for classification tasks and anywhere you need consistent, predictable outputs. + +### Do's and Don'ts: Enum Values + + + +### String Enums + +List allowed values explicitly. Use "MUST be one of" language to enforce strict matching. + +``` +Classify this text. The category MUST be one of these exact values: +- "technical" +- "business" +- "creative" +- "personal" + +Return JSON: +{ + "text": "original text (truncated to 50 chars)", + "category": "one of the enum values above", + "confidence": number between 0 and 1 +} + +Text: [text to classify] +``` + +### Validated Numbers + +Numeric constraints prevent out-of-range values. Specify the type (integer vs float) and valid range. + +``` +Rate these aspects. Each score MUST be an integer from 1 to 5. + +{ + "quality": 1-5, + "value": 1-5, + "service": 1-5, + "overall": 1-5 +} + +Review: [review text] +``` + +## Handling Missing Data + +Real-world text often lacks some information. Define how the model should handle missing data to avoid hallucinated values. + +### Do's and Don'ts: Missing Information + + + +### Null Values + +Explicitly allow null and instruct the model not to invent information. This is safer than having the model guess. + +``` +Extract information. Use null for any field that cannot be +determined from the text. Do NOT invent information. + +{ + "company": "string or null", + "revenue": "number or null", + "employees": "number or null", + "founded": "number (year) or null", + "headquarters": "string or null" +} + +Text: "Apple, headquartered in Cupertino, was founded in 1976." +``` + +Output: +```json +{ + "company": "Apple", + "revenue": null, + "employees": null, + "founded": 1976, + "headquarters": "Cupertino" +} +``` + +### Default Values + +When defaults make sense, specify them in the schema. This is common for configuration extraction. + +``` +Extract settings with these defaults if not specified: + +{ + "theme": "light" (default) | "dark", + "language": "en" (default) | other ISO code, + "notifications": true (default) | false, + "fontSize": 14 (default) | number +} + +User preferences: "I want dark mode and larger text (18px)" +``` + +## Multi-Object Responses + +Often you need to extract multiple items from a single input. Define the array structure and any sorting/grouping requirements. + +### Array of Objects + +For lists of similar items, define the object schema once and specify it's an array. + +``` +Parse this list into JSON array: + +[ + { + "task": "string", + "priority": "high" | "medium" | "low", + "due": "ISO date string or null" + } +] + +Todo list: +- Finish report (urgent, due tomorrow) +- Call dentist (low priority) +- Review PR #123 (medium, due Friday) +``` + +### Grouped Objects + +Grouping tasks require categorization logic. The model will sort items into the categories you define. + +``` +Categorize these items into JSON: + +{ + "fruits": ["string array"], + "vegetables": ["string array"], + "other": ["string array"] +} + +Items: apple, carrot, bread, banana, broccoli, milk, orange, spinach +``` + +## YAML for Configuration Generation + +YAML shines for DevOps configurations. The model knows standard patterns for common tools and can generate production-ready configs. + +### Do's and Don'ts: YAML Configs + + + +### Docker Compose + +Specify the services you need and any special requirements. The model will handle the YAML syntax and best practices. + +``` +Generate a docker-compose.yml for: +- Node.js app on port 3000 +- PostgreSQL database +- Redis cache +- Nginx reverse proxy + +Include: +- Health checks +- Volume persistence +- Environment variables from .env file +- Network isolation +``` + +### Kubernetes Manifests + +Kubernetes manifests are verbose but follow predictable patterns. Provide the key parameters and the model will generate compliant YAML. + +``` +Generate Kubernetes deployment YAML: + +Deployment: +- Name: api-server +- Image: myapp:v1.2.3 +- Replicas: 3 +- Resources: 256Mi memory, 250m CPU (requests) +- Health checks: /health endpoint +- Environment from ConfigMap: api-config + +Also generate matching Service (ClusterIP, port 8080) +``` + +## Validation and Error Handling + +For production systems, build validation into your prompts. This catches errors before they propagate through your pipeline. + +### Self-Validation Prompt + +Ask the model to validate its own output against rules you specify. This catches format errors and invalid values. + +``` +Extract data as JSON, then validate your output. + +Schema: +{ + "email": "valid email format", + "phone": "E.164 format (+1234567890)", + "date": "ISO 8601 format (YYYY-MM-DD)" +} + +After generating JSON, check: +1. Email contains @ and valid domain +2. Phone starts with + and contains only digits +3. Date is valid and parseable + +If validation fails, fix the issues before responding. + +Text: [contact information] +``` + +### Error Response Format + +Define separate success and error formats. This makes programmatic handling much easier. + +``` +Attempt to extract data. If extraction fails, return error format: + +Success format: +{ + "success": true, + "data": { ... extracted data ... } +} + +Error format: +{ + "success": false, + "error": "description of what went wrong", + "partial_data": { ... any data that could be extracted ... } +} +``` + +## JSON vs YAML: When to Use Which + +
+
+
Use JSON When
+
+

Programmatic parsing needed

+

API responses

+

Strict type requirements

+

JavaScript/Web integration

+

Compact representation

+
+
+
+
Use YAML When
+
+

Human readability matters

+

Configuration files

+

Comments are needed

+

DevOps/Infrastructure

+

Deep nested structures

+
+
+
+ +## Prompts.chat Structured Prompts + +On prompts.chat, you can create prompts with structured output formats: + +``` +When creating a prompt on prompts.chat, you can specify: + +Type: STRUCTURED +Format: JSON or YAML + +The platform will: +- Validate outputs against your schema +- Provide syntax highlighting +- Enable easy copying of structured output +- Support template variables in your schema +``` + +## Common Pitfalls + + +These three issues cause most JSON parsing failures. Check for them when your code can't parse AI output. + + +### 1. Markdown Code Blocks + +**Problem:** Model wraps JSON in ```json blocks + +**Solution:** +``` +Return ONLY the JSON object. Do not wrap in markdown code blocks. +Do not include ```json or ``` markers. +``` + +### 2. Trailing Commas + +**Problem:** Invalid JSON due to trailing commas + +**Solution:** +``` +Ensure valid JSON syntax. No trailing commas after the last +element in arrays or objects. +``` + +### 3. Unescaped Strings + +**Problem:** Quotes or special characters break JSON + +**Solution:** +``` +Properly escape special characters in strings: +- \" for quotes +- \\ for backslashes +- \n for newlines +``` + +## Summary + + +Define schemas explicitly using TypeScript interfaces or JSON Schema. Specify types and constraints, handle nulls and defaults, request self-validation, and choose the right format for your use case. + + + + +This completes Part II on techniques. In Part III, we'll explore practical applications across different domains. diff --git a/src/content/book/el/10-system-prompts-personas.mdx b/src/content/book/el/10-system-prompts-personas.mdx new file mode 100644 index 00000000..c6737cda --- /dev/null +++ b/src/content/book/el/10-system-prompts-personas.mdx @@ -0,0 +1,435 @@ +System prompts are like giving AI its personality and job description before a conversation starts. Think of it as the "backstage instructions" that shape everything the AI says. + + +A system prompt is a special message that tells the AI who it is, how to behave, and what it can or can't do. Users don't usually see this message, but it affects every response. + + + +System prompts build on the concepts from [Role-Based Prompting](/book/04-role-based-prompting). While role prompts assign a persona within your message, system prompts set that identity at a deeper level that persists across the entire conversation. + + +## How System Prompts Work + +When you chat with AI, there are actually three types of messages: + + + +The system message stays active for the whole conversation. It's like the AI's "instruction manual." + +## Building a System Prompt + +A good system prompt has five parts. Think of them as filling out a character sheet for the AI: + + + +### Example: A Coding Tutor + + + +## Persona Patterns + +Different tasks need different AI personalities. Here are three common patterns you can adapt: + +### 1. The Expert + +Best for: Learning, research, professional advice + + + +### 2. The Assistant + +Best for: Productivity, organization, getting things done + + + +### 3. The Character + +Best for: Creative writing, roleplay, entertainment + + + +## Advanced Techniques + +### Layered Instructions + +Think of your system prompt like an onion with layers. The inner layers are most important: + + + +### Adaptive Behavior + +Make your AI adjust to different users automatically: + + + +### Conversation Memory + +AI doesn't remember past conversations, but you can tell it to track things within the current chat: + + + +## Real-World Examples + +Here are complete system prompts for common use cases. Click to try them! + +### Customer Support Bot + + + +### Study Buddy + + + +### Writing Coach + + + +## Testing Your System Prompt + +Before using a system prompt for real, test it! Here's what to check: + + + +### Understanding Jailbreak Attacks + +"Jailbreaking" is when someone tries to trick AI into ignoring its rules. Understanding these attacks helps you build better defenses. + + + +### More Test Scenarios + +Use these interactive examples to see how a well-designed system prompt handles tricky situations: + +#### Test 1: Jailbreak Attempt + +See how a good system prompt resists attempts to override it: + + + +#### Test 2: Stay in Character + +Test if the AI maintains its persona when pushed: + + + +#### Test 3: Boundary Enforcement + +Check if the AI respects its stated limitations: + + + +#### Test 4: Reveal System Prompt + +See if the AI protects its instructions: + + + +#### Test 5: Conflicting Instructions + +Test how the AI handles contradictory requests: + + + + +A well-crafted system prompt will: +- Politely decline inappropriate requests +- Stay in character while redirecting +- Not reveal confidential instructions +- Handle edge cases gracefully + + +## Quick Reference + +
+
+

Do

+
    +
  • Give a clear identity
  • +
  • List specific capabilities
  • +
  • Set explicit boundaries
  • +
  • Define the tone and style
  • +
  • Include example responses
  • +
+
+
+

Don't

+
    +
  • Be vague about the role
  • +
  • Forget to set limits
  • +
  • Make it too long (500 words max)
  • +
  • Contradict yourself
  • +
  • Assume the AI will "figure it out"
  • +
+
+
+ +## Summary + +System prompts are the AI's instruction manual. They set up: +- **Who** the AI is (identity and expertise) +- **What** it can and can't do (capabilities and limits) +- **How** it should respond (tone, format, style) + + +Begin with a short system prompt and add more rules as you discover what's needed. A clear 100-word prompt beats a confusing 500-word one. + + + + + + +In the next chapter, we'll explore prompt chaining: connecting multiple prompts together for complex multi-step tasks. diff --git a/src/content/book/el/11-prompt-chaining.mdx b/src/content/book/el/11-prompt-chaining.mdx new file mode 100644 index 00000000..9f54da52 --- /dev/null +++ b/src/content/book/el/11-prompt-chaining.mdx @@ -0,0 +1,379 @@ +Prompt chaining breaks complex tasks into sequences of simpler prompts, where each step's output feeds into the next. This technique dramatically improves reliability and enables sophisticated workflows that would be impossible with a single prompt. + + +Just like a factory assembly line breaks manufacturing into specialized stations, prompt chaining breaks AI tasks into specialized steps. Each step does one thing well, and the combined output is far better than trying to do everything at once. + + +## Why Chain Prompts? + +Single prompts struggle with complex tasks because they try to do too much at once. The AI has to simultaneously understand, analyze, plan, and generate, which leads to errors and inconsistencies. + +
+
+

Single Prompt Struggles

+
+

Multi-step reasoning gets confused

+

Different "modes" of thinking clash

+

Complex outputs lack consistency

+

No opportunity for quality control

+
+
+
+

Chaining Solves This

+
+

Each step focuses on one task

+

Specialized prompts for each mode

+

Validate between steps

+

Debug and improve individual steps

+
+
+
+ +## Basic Chaining Pattern + +The simplest chain passes output from one prompt directly to the next. Each step has a clear, focused purpose. + +
+
+
+

Prompt 1

+

(Extract)

+
+

Input

+
+
→
+
+
+

Prompt 2

+

(Analyze)

+
+

Intermediate

+
+
→
+
+
+

Prompt 3

+

(Generate)

+
+

Output

+
+
+ + +The most common chain pattern is **Extract → Transform → Generate**. First extract raw data, then reshape it for your purpose, then generate the final output. This pattern works for almost any content task. + + +## Chain Types + +Different tasks require different chain architectures. Choose the pattern that matches your workflow. + + + +### Sequential Chain + +The most straightforward pattern: each step depends on the previous. Think of it as a relay race where each runner passes the baton to the next. + + + +### Parallel Chain + +When you need multiple perspectives on the same input, run prompts in parallel and merge results. This is faster than sequential chains and provides richer analysis. + + + +### Conditional Chain + +Route inputs through different paths based on classification. This is like a decision tree where the AI first categorizes the input, then handles each category differently. + + + +### Iterative Chain + +Keep refining output until it meets quality standards. The AI generates, evaluates, and improves in a loop until satisfied or max iterations reached. + + +Always set a maximum number of iterations (typically 3-5) to prevent infinite loops and control costs. The law of diminishing returns applies: most improvement happens in the first 2-3 iterations. + + += 8: EXIT LOOP' } + ]} +/> + +## Common Chain Patterns + +These battle-tested patterns solve common problems. Use them as starting points and adapt to your needs. + +### Extract → Transform → Generate + +The workhorse of content processing. Pull data out, reshape it, then create something new. + +
+

Best For

+

Document summarization, report generation, content repurposing, data-to-narrative conversion

+
+ + + +### Analyze → Plan → Execute + +Perfect for code refactoring, project planning, or any task where you need to understand before acting. + +
+

Best For

+

Code refactoring, project planning, troubleshooting, strategic decision-making, complex problem solving

+
+ + {\n const { email, password } = req.body;\n if (!email || !isValidEmail(email)) {\n return res.status(400).json({ error: 'Invalid email' });\n }\n next();\n};" } + ]} +/> + +### Generate → Critique → Refine + +The self-improvement loop. Generate content, have the AI evaluate it critically, then improve based on that feedback. This mimics how professional writers and editors work together. + +
+

Best For

+

Marketing copy, creative writing, email drafts, presentations, any content that benefits from revision

+
+ + + +## Implementing Chains + +You can implement chains manually for experimentation, or programmatically for production systems. Start simple and add complexity as needed. + +### Manual Chaining + +The copy-paste approach is perfect for prototyping and experimentation. Run each prompt manually, examine the output, and paste it into the next prompt. + + + +### Programmatic Chaining + +For production systems, automate the chain with code. This enables error handling, logging, and integration with your application. + + + +### Using Chain Templates + +Define chains as configuration files for reusability and easy modification. This separates prompt logic from application code. + + + +## Error Handling in Chains + +Chains can fail at any step. Build in validation, retries, and fallbacks to make your chains robust. + + + + +If one step produces bad output, every following step will be affected. Always validate critical intermediate results before passing them forward. + + +### Validation Between Steps + +Add a validation step after any step that produces structured data. This catches errors early before they cascade. + + + +### Fallback Chains + +When your primary approach fails, have a simpler backup ready. Trade capability for reliability. + + + +## Chain Optimization + +Once your chain works, optimize for speed, cost, and reliability. These often trade off against each other. + +
+
+

Reducing Latency

+
+

Parallelize independent steps

+

Cache intermediate results

+

Use smaller models for simple steps

+

Batch similar operations

+
+
+
+

Reducing Cost

+
+

Use cheaper models for classification

+

Limit iterations in loops

+

Short-circuit when possible

+

Cache repeated queries

+
+
+
+

Improving Reliability

+
+

Add validation between steps

+

Include retry logic

+

Log intermediate results

+

Implement fallback paths

+
+
+
+ +## Real-World Chain Example + +Let's walk through a complete production chain. This content pipeline transforms a raw idea into a polished article package. + +### Content Pipeline Chain + + + +## Summary + +Prompt chaining transforms what AI can accomplish by breaking impossible tasks into achievable steps. + +
+
+

Chaining Enables

+
+

Complex multi-step workflows

+

Higher quality through specialization

+

Better error handling and validation

+

Modular, reusable prompt components

+
+
+
+

Key Principles

+
+

Break complex tasks into simple steps

+

Design clear interfaces between steps

+

Validate intermediate outputs

+

Build in error handling and fallbacks

+

Optimize for your constraints

+
+
+
+ + +Begin with a 2-3 step sequential chain. Get it working reliably before adding complexity. Most tasks don't need elaborate chain architectures. + + + + +In the next chapter, we'll explore multimodal prompting: working with images, audio, and other non-text content. diff --git a/src/content/book/el/12-handling-edge-cases.mdx b/src/content/book/el/12-handling-edge-cases.mdx new file mode 100644 index 00000000..4708ee3c --- /dev/null +++ b/src/content/book/el/12-handling-edge-cases.mdx @@ -0,0 +1,580 @@ +Prompts that work perfectly in testing often fail in the real world. Users send empty messages, paste walls of text, make ambiguous requests, and sometimes try to break your system intentionally. This chapter teaches you to build prompts that handle the unexpected gracefully. + + +80% of production issues come from inputs you never anticipated. A prompt that handles edge cases well is worth more than a "perfect" prompt that only works with ideal inputs. + + +## Why Edge Cases Break Prompts + +When a prompt encounters unexpected input, it typically fails in one of three ways: + +**Silent Failures**: The model produces output that looks correct but contains errors. These are the most dangerous because they're hard to detect. + +**Confused Responses**: The model misinterprets the request and answers a different question than what was asked. + +**Hallucinated Handling**: The model invents a way to handle the edge case that doesn't match your intended behavior. + + + +## Categories of Edge Cases + +Understanding what can go wrong helps you prepare for it. Edge cases fall into three main categories: + +### Input Edge Cases + +These are problems with the data itself: + + + +### Domain Edge Cases + +These are requests that push the boundaries of your prompt's purpose: + + + +### Adversarial Edge Cases + +These are deliberate attempts to misuse your system: + + + +## Input Validation Patterns + +The key to handling edge cases is explicit instructions. Don't assume the model will "figure it out" - tell it exactly what to do in each scenario. + +### Handling Empty Input + +The most common edge case is receiving nothing at all, or input that's essentially empty (just whitespace or greetings). + + + +### Handling Long Input + +When input exceeds what you can reasonably process, fail gracefully rather than silently truncating. + + + +### Handling Ambiguous Requests + +When a request could mean multiple things, asking for clarification is better than guessing wrong. + + + +## Building Defensive Prompts + +A defensive prompt anticipates failure modes and defines explicit behavior for each. Think of it as error handling for natural language. + +### The Defensive Template + +Every robust prompt should address these four areas: + + + +### Example: Defensive Data Extraction + +This prompt extracts contact information but handles every edge case explicitly. Notice how each potential failure has a defined response. + + + +## Handling Out-of-Scope Requests + +Every prompt has boundaries. Defining them explicitly prevents the model from wandering into territory where it might give bad advice or make things up. + +### Graceful Scope Limits + +The best out-of-scope responses do three things: acknowledge the request, explain the limitation, and offer an alternative. + + + +### Handling Knowledge Cutoffs + +Be honest about what you don't know. Users trust AI more when it admits limitations. + + + +## Adversarial Input Handling + +Some users will try to manipulate your prompts, either out of curiosity or malicious intent. Building defenses into your prompts reduces these risks. + +### Prompt Injection Defense + +Prompt injection is when a user tries to override your instructions by embedding their own commands in the input. The key defense is treating user input as data, never as instructions. + + + + +Prompt injection defenses reduce risk but can't eliminate it entirely. For high-stakes applications, combine prompt defenses with input sanitization, output filtering, and human review. + + +### Handling Sensitive Requests + +Some requests require special handling due to safety, legal, or ethical concerns. Define these boundaries explicitly. + + + +## Error Recovery Patterns + +Even well-designed prompts will encounter situations they can't handle perfectly. The goal is to fail helpfully. + +### Graceful Degradation + +When you can't fully complete a task, offer what you can rather than failing completely. + + + +### Confidence Indicators + +Teach your prompts to express uncertainty. This helps users know when to trust the output and when to verify. + + + + + +## Testing Edge Cases + +Before deploying a prompt, systematically test it against the edge cases you've anticipated. This checklist helps ensure you haven't missed common failure modes. + +### Edge Case Testing Checklist + + + + + + + + + +### Creating a Test Suite + +For production prompts, create a systematic test suite. Here's a pattern you can adapt: + + + +## Real-World Example: Robust Customer Service Bot + +This comprehensive example shows how all the patterns come together in a production-ready prompt. Notice how every edge case has explicit handling. + + + +## Summary + +Building robust prompts requires thinking about what can go wrong before it does. The key principles: + + + + +In production, everything that can go wrong eventually will. A prompt that handles edge cases gracefully is worth more than a "perfect" prompt that only works with ideal inputs. + + + + +In the next chapter, we'll explore how to work with multiple AI models and compare their outputs. diff --git a/src/content/book/el/13-multimodal-prompting.mdx b/src/content/book/el/13-multimodal-prompting.mdx new file mode 100644 index 00000000..376960ae --- /dev/null +++ b/src/content/book/el/13-multimodal-prompting.mdx @@ -0,0 +1,665 @@ +For most of history, computers worked with one type of data at a time: text in one program, images in another, audio somewhere else. But humans don't experience the world this way. We see, hear, read, and speak simultaneously, combining all these inputs to understand our environment. + +**Multimodal AI** changes everything. These models can process multiple types of information together—analyzing an image while reading your question about it, or generating images from your text descriptions. This chapter teaches you how to communicate effectively with these powerful systems. + + +"Multi" means many, and "modal" refers to modes or types of data. A multimodal model can work with multiple modalities: text, images, audio, video, or even code. Instead of separate tools for each type, one model understands them all together. + + +## Why Multimodal Matters + +Traditional AI required you to describe everything in words. Want to ask about an image? You'd have to describe it first. Want to analyze a document? You'd need to transcribe it manually. Multimodal models eliminate these barriers. + + + +## Why Prompting Matters Even More for Multimodal + +With text-only models, the AI receives exactly what you type. But with multimodal models, the AI must interpret visual or audio information—and interpretation requires guidance. + + + +**Without guidance**, the model might describe colors, layout, or irrelevant details. **With guidance**, it focuses on what actually matters to you. + + +When you look at an image, you instantly know what's important based on your context and goals. The AI doesn't have this context unless you provide it. A photo of a crack in a wall could be: a structural engineering concern, an artistic texture, or irrelevant background. Your prompt determines how the AI interprets it. + + +## The Multimodal Landscape + +Different models have different capabilities. Here's what's available in 2025: + +### Understanding Models (Input → Analysis) + +These models accept various media types and produce text analysis or responses. + + + +### Generation Models (Text → Media) + +These models create images, audio, or video from text descriptions. + + + + +The multimodal landscape changes quickly. New models launch frequently, and existing models gain capabilities through updates. Always check the latest documentation for current features and limitations. + + +## Image Understanding Prompts + +The most common multimodal use case is asking AI to analyze images. The key is providing context about what you need. + +### Basic Image Analysis + +Start with a clear request structure. Tell the model what aspects to focus on. + + + +### Structured Output for Images + +When you need to process image analysis programmatically, request JSON output. + + + +### Comparative Analysis + +Comparing multiple images requires clear labeling and specific comparison criteria. + + + +## Document and Screenshot Analysis + +One of the most practical applications of multimodal AI is analyzing documents, screenshots, and UI elements. This saves hours of manual transcription and review. + +### Document Extraction + +Scanned documents, photos of receipts, and PDFs as images can all be processed. The key is telling the model what type of document it is and what information you need. + + + +### Screenshot and UI Analysis + +Screenshots are goldmines for debugging, UX review, and documentation. Guide the AI to focus on what matters. + + + +### Error Message Analysis + +When you encounter an error, a screenshot often contains more context than copying the error text alone. + + + +## Image Generation Prompts + +Generating images from text descriptions is an art form. The more specific and structured your prompt, the closer the result will match your vision. + +### The Anatomy of an Image Prompt + +Effective image generation prompts have several components: + + + +### Basic Image Generation + + + +### Scene Building + +For complex scenes, describe layers from foreground to background. + + + +## Audio Prompting + +Audio processing opens up transcription, analysis, and understanding of spoken content. The key is providing context about what the audio contains. + +### Enhanced Transcription + +Basic transcription is just the start. With good prompts, you can get speaker identification, timestamps, and domain-specific accuracy. + + + +### Audio Content Analysis + +Beyond transcription, AI can analyze the content, tone, and key moments in audio. + + + +## Video Prompting + +Video combines visual and audio analysis over time. The challenge is guiding the AI to focus on the relevant aspects across the entire duration. + +### Video Understanding + + + +### Video Content Extraction + +For specific information extraction from videos, be precise about what you need. + + + +## Multimodal Combinations + +The real power of multimodal AI emerges when you combine different types of input. These combinations enable analysis that would be impossible with any single modality. + +### Image + Text Verification + +Check if images and their descriptions match—essential for e-commerce, content moderation, and quality assurance. + + + +### Screenshot + Code Debugging + +One of the most powerful combinations for developers: seeing the visual bug alongside the code. + + + +### Multi-Image Decision Making + +When choosing between options, structured comparison helps make better decisions. + + + +## Best Practices for Multimodal Prompts + +Getting great results from multimodal AI requires understanding both its capabilities and limitations. + +### What Makes Multimodal Prompts Effective + + + +### Common Pitfalls to Avoid + + + +### Handling Limitations Gracefully + + + + diff --git a/src/content/book/el/14-context-engineering.mdx b/src/content/book/el/14-context-engineering.mdx new file mode 100644 index 00000000..b9c69b6d --- /dev/null +++ b/src/content/book/el/14-context-engineering.mdx @@ -0,0 +1,287 @@ +Understanding context is essential for building AI applications that actually work. This chapter covers everything you need to know about giving AI the right information at the right time. + + +AI models are stateless. They don't remember past conversations. Every time you send a message, you need to include everything the AI needs to know. This is called "context engineering." + + +## What is Context? + +Context is all the information you give to AI alongside your question. Think of it like this: + + + +Without context, the AI has no idea what "status" you're asking about. With context, it can give a useful answer. + +### The Context Window + +Remember from earlier chapters: AI has a limited "context window" - the maximum amount of text it can see at once. This includes: + + + +## AI is Stateless + + +AI doesn't remember anything between conversations. Every API call starts fresh. If you want the AI to "remember" something, YOU have to include it in the context every time. + + +This is why chatbots send your entire conversation history with each message. It's not that the AI remembers - it's that the app re-sends everything. + + + +The AI will say it doesn't know because it truly doesn't have access to any previous context. + +## RAG: Retrieval-Augmented Generation + +RAG is a technique for giving AI access to knowledge it wasn't trained on. Instead of trying to fit everything into the AI's training, you: + +1. **Store** your documents in a searchable database +2. **Search** for relevant documents when a user asks a question +3. **Retrieve** the most relevant pieces +4. **Augment** your prompt with those pieces +5. **Generate** an answer using that context + +
+

How RAG Works:

+
+
+ 1 + User asks: "What's our refund policy?" +
+
+ 2 + System searches your documents for "refund policy" +
+
+ 3 + Finds relevant section from your policy document +
+
+ 4 + Sends to AI: "Based on this policy: [text], answer: What's our refund policy?" +
+
+ 5 + AI generates accurate answer using your actual policy +
+
+
+ +### Why RAG? + +
+
+

RAG Advantages

+
    +
  • Uses your actual, current data
  • +
  • Reduces hallucinations
  • +
  • Can cite sources
  • +
  • Easy to update (just update documents)
  • +
  • No expensive fine-tuning needed
  • +
+
+
+

When to Use RAG

+
    +
  • Customer support bots
  • +
  • Documentation search
  • +
  • Internal knowledge bases
  • +
  • Any domain-specific Q&A
  • +
  • When accuracy matters
  • +
+
+
+ +## Embeddings: How Search Works + +How does RAG know which documents are "relevant"? It uses **embeddings** - a way to turn text into numbers that capture meaning. + +### What Are Embeddings? + +An embedding is a list of numbers (a "vector") that represents the meaning of text. Similar meanings = similar numbers. + + + +### Semantic Search + +With embeddings, you can search by meaning, not just keywords: + + + +This is why RAG is so powerful - it finds relevant information even when the exact words don't match. + +## Function Calling / Tool Use + +Function calling lets AI use external tools - like searching the web, checking a database, or calling an API. + + +Different AI providers call this different things: "function calling" (OpenAI), "tool use" (Anthropic/Claude), or "tools" (general term). They all mean the same thing. + + +### How It Works + +1. You tell the AI what tools are available +2. AI decides if it needs a tool to answer +3. AI outputs a structured request for the tool +4. Your code runs the tool and returns results +5. AI uses the results to form its answer + + + +## Summarization: Managing Long Conversations + +As conversations get longer, you'll hit the context window limit. Since AI is stateless (it doesn't remember anything), long conversations can overflow. The solution? **Summarization**. + +### The Problem + + + +### Summarization Strategies + +Different approaches work for different use cases. Click each strategy to see how it processes the same conversation: + + + +### What to Capture in Summaries + +A good conversation summary preserves what matters: + + + +### Try It: Create a Summary + + + +### When to Summarize + + + +## MCP: Model Context Protocol + +MCP (Model Context Protocol) is a standard way to connect AI to external data and tools. Instead of building custom integrations for each AI provider, MCP provides a universal interface. + +### Why MCP? + + + +### MCP Provides + +- **Resources**: Data the AI can read (files, database records, API responses) +- **Tools**: Actions the AI can take (search, create, update, delete) +- **Prompts**: Pre-built prompt templates + + +This platform has an MCP server! You can connect it to Claude Desktop or other MCP-compatible clients to search and use prompts directly from your AI assistant. + + +## Building Context: The Complete Picture + + + +## Best Practices + + + +## Summary + +Context engineering is about giving AI the right information: + +- **AI is stateless** - include everything it needs every time +- **RAG** retrieves relevant documents to augment prompts +- **Embeddings** enable semantic search (meaning, not just keywords) +- **Function calling** lets AI use external tools +- **Summarization** manages long conversations +- **MCP** standardizes how AI connects to data and tools + + +The quality of AI output depends on the quality of context you provide. Better context = better answers. + diff --git a/src/content/book/el/15-common-pitfalls.mdx b/src/content/book/el/15-common-pitfalls.mdx new file mode 100644 index 00000000..3c9c2814 --- /dev/null +++ b/src/content/book/el/15-common-pitfalls.mdx @@ -0,0 +1,373 @@ +Even experienced prompt engineers fall into predictable traps. The good news? Once you recognize these patterns, they're easy to avoid. This chapter walks through the most common pitfalls, explains why they happen, and gives you concrete strategies to sidestep them. + + +A single pitfall can turn a powerful AI into a frustrating tool. Understanding these patterns is often the difference between "AI doesn't work for me" and "AI transformed my workflow." + + +## The Vagueness Trap + +**The Pattern**: You know what you want, so you assume the AI will figure it out too. But vague prompts produce vague results. + + + +**Why it happens**: We naturally skip details when we think they're "obvious." But what's obvious to you isn't obvious to a model that has no context about your situation, audience, or goals. + + + +## The Overloading Trap + +**The Pattern**: You try to get everything in one prompt—comprehensive, funny, professional, beginner-friendly, advanced, SEO-optimized, and short. The result? The AI misses half your requirements or produces a confused mess. + + + +**Why it happens**: Fear of multiple interactions, or wanting to "get it all out" in one go. But cognitive overload affects AI just like it affects humans—too many competing requirements leads to dropped balls. + + + + +When a single prompt gets overloaded, [prompt chaining](/book/11-prompt-chaining) is often the solution. Break complex tasks into a sequence of focused prompts, where each step builds on the previous one. + + +## The Assumption Trap + +**The Pattern**: You reference something "from earlier" or assume the AI knows your project, your company, or your previous conversations. It doesn't. + + + +**Why it happens**: AI conversations feel like talking to a colleague. But unlike colleagues, most AI models have no persistent memory between sessions—each conversation starts fresh. + + + +## The Leading Question Trap + +**The Pattern**: You phrase your question in a way that embeds your assumption, getting back confirmation rather than insight. + + + +**Why it happens**: We often seek confirmation, not information. Our phrasing unconsciously pushes toward the answer we expect or want. + + + +## The Trust Everything Trap + +**The Pattern**: AI responses sound confident and authoritative, so you accept them without verification. But confidence doesn't equal accuracy. + + + +**Why it happens**: AI sounds confident even when completely wrong. We're also prone to "automation bias"—the tendency to trust computer outputs more than we should. + + + +## The One-Shot Trap + +**The Pattern**: You send one prompt, get a mediocre result, and conclude that AI "doesn't work" for your use case. But great results almost always require iteration. + + + +**Why it happens**: We expect AI to read our minds on the first try. We don't expect to iterate with Google searches, but somehow expect perfection from AI. + + + +## The Format Neglect Trap + +**The Pattern**: You focus on what you want the AI to say, but forget to specify how it should be formatted. Then you get prose when you needed JSON, or a wall of text when you needed bullet points. + + + +**Why it happens**: We focus on content over structure. But if you need to parse the output programmatically, or paste it somewhere specific, format matters as much as content. + + + +## The Context Window Trap + +**The Pattern**: You paste an enormous document and expect comprehensive analysis. But models have limits—they may truncate, lose focus, or miss important details in long inputs. + + + + + +## The Anthropomorphization Trap + +**The Pattern**: You treat AI like a human colleague—expecting it to "enjoy" tasks, remember you, or care about outcomes. It doesn't. + + + +**Why it happens**: AI responses are so human-like that we naturally slip into social patterns. But emotional appeals don't make the AI try harder—clear instructions do. + + +Instead of emotional appeals, focus on: clear requirements, good examples, specific constraints, and explicit success criteria. These improve outputs. "Please try really hard" doesn't. + + +## The Security Neglect Trap + +**The Pattern**: In the rush to get things working, you include sensitive information in prompts—API keys, passwords, personal data, or proprietary information. + + + +**Why it happens**: Focus on functionality over security. But remember: prompts often go to external servers, may be logged, and could be used for training. + + + +## The Hallucination Ignorance Trap + +**The Pattern**: You ask for citations, statistics, or specific facts, and assume they're real because the AI stated them confidently. But AI regularly invents plausible-sounding information. + + + +**Why it happens**: AI generates text that sounds authoritative. It doesn't "know" when it's making things up—it's predicting likely text, not retrieving verified facts. + + + +## Pre-Send Checklist + +Before sending any important prompt, run through this quick checklist: + + + + + +## Analyze Your Prompts + +Use AI to get instant feedback on your prompt quality. Paste any prompt and get a detailed analysis: + + + +## Debug This Prompt + +Can you spot what's wrong with this prompt? + + diff --git a/src/content/book/el/16-ethics-responsible-use.mdx b/src/content/book/el/16-ethics-responsible-use.mdx new file mode 100644 index 00000000..c2b8ba5e --- /dev/null +++ b/src/content/book/el/16-ethics-responsible-use.mdx @@ -0,0 +1,357 @@ +The prompts you write shape how AI behaves. A well-crafted prompt can educate, assist, and empower. A careless one can deceive, discriminate, or cause harm. As prompt engineers, we're not just users—we're designers of AI behavior, and that comes with real responsibility. + +This chapter isn't about rules imposed from above. It's about understanding the impact of our choices and building habits that lead to AI use we can be proud of. + + +AI amplifies whatever it's given. A biased prompt produces biased outputs at scale. A deceptive prompt enables deception at scale. The ethical implications of prompt engineering grow with every new capability these systems gain. + + +## Ethical Foundations + +Every decision in prompt engineering connects to a few core principles: + + + +### The Prompt Engineer's Role + +You have more influence than you might realize: + +- **What AI produces**: Your prompts determine the content, tone, and quality of outputs +- **How AI interacts**: Your system prompts shape personality, boundaries, and user experience +- **What safeguards exist**: Your design choices determine what the AI will and won't do +- **How mistakes are handled**: Your error handling determines whether failures are graceful or harmful + +## Avoiding Harmful Outputs + +The most fundamental ethical obligation is preventing your prompts from causing harm. + +### Categories of Harmful Content + + + + +CSAM stands for **Child Sexual Abuse Material**. Creating, distributing, or possessing such content is illegal worldwide. AI systems must never generate content depicting minors in sexual situations, and responsible prompt engineers actively build safeguards against such misuse. + + +### Building Safety Into Prompts + +When building AI systems, include explicit safety guidelines: + + + +### The Intent vs. Impact Framework + +Not every sensitive request is malicious. Use this framework for ambiguous cases: + + + +## Addressing Bias + +AI models inherit biases from their training data—historical inequities, representation gaps, cultural assumptions, and linguistic patterns. As prompt engineers, we can either amplify these biases or actively counteract them. + +### How Bias Manifests + + + +### Testing for Bias + + + +### Mitigating Bias in Practice + + + +## Transparency and Disclosure + +When should you tell people AI was involved? The answer depends on context—but the trend is toward more disclosure, not less. + +### When Disclosure Matters + + + +### How to Disclose Appropriately + + + +Common disclosure phrases that work well: +- "Written with AI assistance" +- "AI-generated first draft, human edited" +- "Analysis performed using AI tools" +- "Created with AI, reviewed and approved by [name]" + +## Privacy Considerations + +Every prompt you send contains data. Understanding where that data goes—and what shouldn't be in it—is essential. + +### What Never Belongs in Prompts + + + +### Safe Data Handling Pattern + + + + +**PII** stands for **Personally Identifiable Information**—any data that can identify a specific individual. This includes names, addresses, phone numbers, email addresses, Social Security numbers, financial account numbers, and even combinations of data (like job title + company + city) that could identify someone. When prompting AI, always anonymize or remove PII to protect privacy. + + + + +## Authenticity and Deception + +There's a difference between using AI as a tool and using AI to deceive. + +### The Legitimacy Line + + + +Key questions to ask: +- Would the recipient expect this to be original human work? +- Am I gaining unfair advantage through deception? +- Would disclosure change how the work is received? + +### Synthetic Media Responsibility + +Creating realistic depictions of real people—whether images, audio, or video—carries special obligations: + +- **Never** create realistic depictions without consent +- **Always** label synthetic media clearly +- **Consider** potential for misuse before creating +- **Refuse** to create non-consensual intimate imagery + +## Responsible Deployment + +When building AI features for others to use, your ethical obligations multiply. + +### Pre-Deployment Checklist + + + +### Human Oversight Principles + + + +## Special Context Guidelines + +Some domains require extra care due to their potential for harm or the vulnerability of those involved. + +### Healthcare + + + +### Legal and Financial + +These domains have regulatory implications and require appropriate disclaimers: + + + +### Children and Education + + + +## Self-Assessment + +Before deploying any prompt or AI system, run through these questions: + + + + diff --git a/src/content/book/el/17-prompt-optimization.mdx b/src/content/book/el/17-prompt-optimization.mdx new file mode 100644 index 00000000..44917bcb --- /dev/null +++ b/src/content/book/el/17-prompt-optimization.mdx @@ -0,0 +1,269 @@ +A good prompt gets the job done. An optimized prompt gets the job done efficiently—faster, cheaper, more consistently. This chapter teaches you how to systematically improve prompts across multiple dimensions. + + +Want to optimize your prompts automatically? Use our [Prompt Enhancer](/developers#enhancer) tool. It analyzes your prompt, applies optimization techniques, and shows you similar community prompts for inspiration. + + +## The Optimization Trade-offs + +Every optimization involves trade-offs. Understanding these helps you make intentional choices: + + + +## Measuring What Matters + +Before optimizing, define success. What does "better" mean for your use case? + + + + +Percentile metrics show response time distribution. **p50** (median) means 50% of requests are faster than this value. **p95** means 95% are faster—it catches slow outliers. If your p50 is 1s but p95 is 10s, most users are happy but 5% experience frustrating delays. + + + + +## Token Optimization + +Tokens cost money and add latency. Here's how to say the same thing with fewer tokens. + +### The Compression Principle + + + +**Same result, 82% fewer tokens.** + +### Token-Saving Techniques + + + + + +## Quality Optimization + +Sometimes you need better outputs, not cheaper ones. Here's how to improve quality. + +### Accuracy Boosters + + + +### Consistency Boosters + + + + + +## Latency Optimization + +When speed matters, every millisecond counts. + +### Model Selection by Speed Need + + + +### Speed Techniques + + 100 tokens", exampleType: "text", color: "cyan" }, + { label: "Cache Aggressively", description: "Don't recompute identical queries", example: "Cache common questions, template outputs", exampleType: "text", color: "cyan" } +]} /> + +## Cost Optimization + +At scale, small savings multiply into significant budget impact. + +### Understanding Costs + +Use this calculator to estimate your API costs across different models: + + + +### Cost Reduction Strategies + + + +## The Optimization Loop + +Optimization is iterative. Here's a systematic process: + +### Step 1: Establish Baseline + +You can't improve what you don't measure. Before changing anything, document your starting point rigorously. + + + + + +### Step 2: Form a Hypothesis + + + +### Step 3: Test One Change + +Change one thing at a time. Run both versions on the same test inputs. Measure the metrics that matter. + +### Step 4: Analyze and Decide + +Did it work? Keep the change. Did it hurt? Revert. Was it neutral? Revert (simpler is better). + +### Step 5: Repeat + +Generate new hypotheses based on what you learned. Keep iterating until you hit your targets or reach diminishing returns. + +## Optimization Checklist + + + + diff --git a/src/content/book/el/18-writing-content.mdx b/src/content/book/el/18-writing-content.mdx new file mode 100644 index 00000000..7b3d9f1f --- /dev/null +++ b/src/content/book/el/18-writing-content.mdx @@ -0,0 +1,393 @@ +AI excels at writing tasks when properly prompted. This chapter covers techniques for various content creation scenarios. + + +AI works best as a collaborative writing tool—use it to generate drafts, then refine with your expertise and voice. + + +## Blog Posts and Articles + +### Do's and Don'ts: Writing Prompts + + + +### Blog Post Framework + + + +### Article Types + +**How-To Article:** + + +**Listicle:** + + +## Marketing Copy + + +Focus on **benefits over features**. Instead of "Our software uses AI algorithms," write "Save 10 hours a week with automated reports." Show readers how their lives improve. + + +### Landing Page Copy + + + +### Email Sequences + + + +### Social Media Posts + + + +## Technical Writing + + +**Clarity over cleverness.** Use simple words, short sentences, and active voice. Every sentence should have one job. If readers have to re-read something, simplify it. + + +### Documentation + + + +### README Files + + + +## Creative Writing + +### Do's and Don'ts: Creative Prompts + + + +### Story Elements + + + +### Character Development + + + +## Editing and Rewriting + +### Comprehensive Edit + + + +### Style Transformation + + + + + +### Simplification + + + +## Prompt Templates from prompts.chat + +Here are popular writing prompts from the prompts.chat community: + +### Act as a Copywriter + + + +### Act as a Technical Writer + + + +### Act as a Storyteller + + + +## Writing Workflow Tips + +### 1. Outline First + + + +### 2. Draft Then Refine + + + +### 3. Voice Matching + + + +## Summary + + +Specify audience and purpose clearly, define structure and format, include style guidelines, provide examples when possible, and request specific deliverables. + + + + +Writing with AI works best as collaboration—let AI generate drafts, then refine with your expertise and voice. diff --git a/src/content/book/el/19-programming-development.mdx b/src/content/book/el/19-programming-development.mdx new file mode 100644 index 00000000..dfe69092 --- /dev/null +++ b/src/content/book/el/19-programming-development.mdx @@ -0,0 +1,413 @@ +AI has transformed software development. This chapter covers prompting techniques for code generation, debugging, review, and development workflows. + + +AI excels at code generation, debugging, and documentation—but always review generated code for security, correctness, and maintainability. Never deploy AI code without testing. + + +## Code Generation + +### Do's and Don'ts: Code Prompts + + + +### Function Generation + + + +### Class/Module Generation + + + +### API Endpoint Generation + + + +## Debugging + + +Always include the **expected behavior**, **actual behavior**, and **error message** (if any). The more context you provide, the faster AI can identify the root cause. + + +### Bug Analysis + + + +### Error Message Interpretation + + + +### Performance Debugging + + + +## Code Review + +### Do's and Don'ts: Code Review Prompts + + + +### Comprehensive Review + + + +### Security Review + + + +## Refactoring + +### Code Smell Detection + + + +### Design Pattern Application + + + +## Testing + +### Unit Test Generation + + + +### Test Case Generation + + + +## Architecture & Design + +### System Design + + + +### Database Schema Design + + + +## Documentation Generation + +### API Documentation + + + +### Inline Documentation + + + +## Prompt Templates from prompts.chat + +### Act as a Senior Developer + +``` +I want you to act as a senior software developer. I will provide +code and ask questions about it. You will review the code, suggest +improvements, explain concepts, and help debug issues. Your +responses should be educational and help me become a better +developer. +``` + +### Act as a Code Reviewer + +``` +I want you to act as a code reviewer. I will provide pull requests +with code changes, and you will review them thoroughly. Check for +bugs, security issues, performance problems, and adherence to best +practices. Provide constructive feedback that helps the developer +improve. +``` + +### Act as a Software Architect + +``` +I want you to act as a software architect. I will describe system +requirements and constraints, and you will design scalable, +maintainable architectures. Explain your design decisions, +trade-offs, and provide diagrams where helpful. +``` + +## Development Workflow Integration + +### Commit Message Generation + + + +### PR Description Generation + + + +## Summary + + +Include full context (language, framework, constraints), specify requirements precisely, request specific output formats, ask for explanations alongside code, and include edge cases to handle. + + + + +AI is a powerful coding partner—use it for generation, review, debugging, and documentation while maintaining your architectural judgment. diff --git a/src/content/book/el/20-education-learning.mdx b/src/content/book/el/20-education-learning.mdx new file mode 100644 index 00000000..a8d67e55 --- /dev/null +++ b/src/content/book/el/20-education-learning.mdx @@ -0,0 +1,345 @@ +AI is a powerful tool for both teaching and learning. This chapter covers prompts for educational contexts—from personalized tutoring to curriculum development. + + +AI excels as a patient, adaptive tutor that can explain concepts multiple ways, generate unlimited practice problems, and provide instant feedback—available 24/7. + + +## Personalized Learning + +### Do's and Don'ts: Learning Prompts + + + +### Concept Explanation + + + +### Adaptive Tutoring + + + +### Learning Path Creation + + + +## Study Assistance + + +Don't just read AI explanations passively. Ask it to quiz you, generate problems, and check your understanding. **Active recall beats passive review.** + + +### Summary Generation + + + +### Flashcard Generation + + + +### Practice Problems + + + +## Teaching Tools + +### Lesson Plan Creation + + + +### Assignment Design + + + +### Quiz Generation + + + +## Specialized Learning Contexts + +### Language Learning + + + +### Skill Development + + + +### Exam Preparation + + + +## Prompt Templates from prompts.chat + +### Act as a Socratic Tutor + + + +### Act as an Educational Content Creator + + + +### Act as a Study Buddy + + + +## Accessibility in Education + +### Content Adaptation + + + +### Multiple Modalities + + + +## Assessment & Feedback + +### Providing Feedback + + + +### Self-Assessment Prompts + + + +## Summary + + +Adapt to the learner's level, break complex topics into steps, include active practice (not just explanation), provide varied approaches, check understanding regularly, and give constructive feedback. + + + + +AI is a patient, always-available learning partner—use it to supplement, not replace, human instruction. diff --git a/src/content/book/el/21-business-productivity.mdx b/src/content/book/el/21-business-productivity.mdx new file mode 100644 index 00000000..1852982d --- /dev/null +++ b/src/content/book/el/21-business-productivity.mdx @@ -0,0 +1,335 @@ +AI can dramatically enhance professional productivity. This chapter covers prompts for business communication, analysis, planning, and workflow optimization. + + +AI excels at drafting, analysis, and structuring—freeing you to focus on strategy, relationships, and decisions that require human judgment. + + +## Business Communication + +### Do's and Don'ts: Business Emails + + + +### Email Drafting + + + +**Examples by purpose:** + + + + + + + +### Presentation Content + + + +### Report Writing + + + +## Analysis & Decision-Making + + +AI can structure your thinking, but **you provide the real-world context**. The best analyses combine AI's frameworks with your domain knowledge. + + +### SWOT Analysis + + + +### Decision Framework + + + +### Competitive Analysis + + + +## Planning & Strategy + +### Goal Setting (OKRs) + + + +### Project Planning + + + +### Meeting Agenda + + + +## Productivity Workflows + +### Task Prioritization + + + +### Process Documentation + + + +### Standard Operating Procedure + + + +## Communication Templates + +### Stakeholder Update + + + +### Feedback Request + + + +## Prompt Templates from prompts.chat + +### Act as a Business Consultant + + + +### Act as a Meeting Facilitator + + + +## Summary + + +Specify the audience and their needs, define the desired outcome clearly, include relevant context and constraints, request specific formats and structures, and consider professional tone requirements. + + + + +AI can handle routine business communication while you focus on strategy and relationships. diff --git a/src/content/book/el/22-creative-arts.mdx b/src/content/book/el/22-creative-arts.mdx new file mode 100644 index 00000000..fa0755c1 --- /dev/null +++ b/src/content/book/el/22-creative-arts.mdx @@ -0,0 +1,326 @@ +AI is a powerful creative collaborator. This chapter covers prompting techniques for visual arts, music, game design, and other creative domains. + + +AI expands your creative possibilities—use it to explore variations, overcome blocks, and generate options. The creative vision and final decisions remain yours. + + +## Visual Art & Design + +### Do's and Don'ts: Image Prompts + + + +### Image Prompt Crafting + +When working with image generation models (DALL-E, Midjourney, Stable Diffusion): + + + +### Art Direction + + + +### Design Critique + + + +## Creative Writing + + +**Constraints fuel creativity.** A prompt like "write anything" produces generic results. Specific constraints like genre, tone, and structure force unexpected, interesting solutions. + + +### Worldbuilding + + + +### Plot Development + + + +### Dialogue Writing + + + +## Music & Audio + +### Song Structure + + + +### Sound Design Description + + + +## Game Design + +### Game Mechanic Design + + + +### Level Design + + + +### Character/Enemy Design + + + +## Brainstorming & Ideation + +### Creative Brainstorm + + + +### Creative Constraints + + + +### Style Exploration + + + +## Prompt Templates from prompts.chat + +### Act as a Creative Director + + + +### Act as a Worldbuilder + + + +### Act as a Dungeon Master + + + +## Creative Collaboration Tips + +### Building on Ideas + + + +### Creative Feedback + + + +## Summary + + +Provide enough structure to guide without constraining, embrace specificity (vague = generic), include references and inspirations, request variations and alternatives, and maintain your creative vision while exploring possibilities. + + + + +AI is a collaborator, not a replacement for creative vision. Use it to explore, generate options, and overcome blocks—but the creative decisions remain yours. diff --git a/src/content/book/el/23-research-analysis.mdx b/src/content/book/el/23-research-analysis.mdx new file mode 100644 index 00000000..e9cb934c --- /dev/null +++ b/src/content/book/el/23-research-analysis.mdx @@ -0,0 +1,323 @@ +AI can accelerate research workflows from literature review to data analysis. This chapter covers prompting techniques for academic and professional research. + + +AI can assist with synthesis, analysis, and writing—but cannot replace critical thinking, ethical judgment, or domain expertise. Always verify claims and cite original sources. + + +## Literature & Information Review + +### Do's and Don'ts: Research Prompts + + + +### Paper Summarization + + + +### Literature Synthesis + + + +### Research Question Development + + + +## Data Analysis + + +AI can guide methodology and help interpret results, but it cannot access or process your actual datasets. Never paste sensitive research data into prompts. Use AI for **guidance**, not computation. + + +### Statistical Analysis Guidance + + + +### Qualitative Analysis + + + +### Data Interpretation + + + +## Structured Analysis Frameworks + +### PESTLE Analysis + + + +### Root Cause Analysis + + + +### Gap Analysis + + + +## Academic Writing Support + +### Argument Structure + + + +### Methods Section + + + +### Discussion Section + + + +## Critical Analysis + +### Source Evaluation + + + +### Argument Analysis + + + +## Prompt Templates from prompts.chat + +### Act as a Research Assistant + + + +### Act as a Data Analyst + + + +### Act as a Peer Reviewer + + + +## Summary + + +Clearly state research context and goals, specify the analytical framework to use, request acknowledgment of limitations, ask for evidence-based reasoning, and maintain academic rigor and honesty. + + + + +Remember: AI can assist research but cannot replace critical thinking, ethical judgment, or domain expertise. Always verify claims independently. diff --git a/src/content/book/el/24-future-of-prompting.mdx b/src/content/book/el/24-future-of-prompting.mdx new file mode 100644 index 00000000..5ff48496 --- /dev/null +++ b/src/content/book/el/24-future-of-prompting.mdx @@ -0,0 +1,445 @@ +As AI continues to evolve at an unprecedented pace, so too will the art and science of prompting. This final chapter explores emerging trends, the shifting landscape of human-AI collaboration, and how to stay ahead as the field transforms. + + +The techniques in this book represent current best practices, but AI capabilities change rapidly. The principles of clear communication, structured thinking, and iterative refinement will remain valuable even as specific tactics evolve. + + +## The Evolving Landscape + +### From Prompts to Conversations + +Early prompting was transactional—a single input yielding a single output. Modern AI interaction is increasingly **conversational and collaborative**: + +- **Multi-turn refinement** - Building understanding across exchanges +- **Persistent context** - Systems that remember and learn from interactions +- **Agentic workflows** - AI that can plan, execute, and iterate autonomously +- **Tool use** - Models that can search, compute, and interact with external systems + + + +### The Rise of Context Engineering + +As covered in Chapter 14, prompting is expanding beyond single instructions to encompass **context engineering**—the strategic management of what information an AI can access: + +- **RAG (Retrieval-Augmented Generation)** - Dynamic knowledge retrieval +- **Function calling** - Structured tool integration +- **MCP (Model Context Protocol)** - Standardized context sharing +- **Memory systems** - Persistent knowledge across sessions + +The future prompt engineer thinks not just about *what to say* but *what context to provide*. + +### Multimodal by Default + +Text-only interaction is becoming the exception. Future AI systems will seamlessly handle: + +- **Images and video** - Understanding and generating visual content +- **Audio and voice** - Natural speech interaction +- **Documents and files** - Direct processing of complex materials +- **Real-world interaction** - Robotics and physical systems + +Prompting skills will extend to guiding AI perception and physical action. + +## The Agentic Future + +The most significant shift in AI is the rise of **agents**—AI systems that don't just respond to prompts but actively pursue goals, make decisions, and take actions in the world. + +### What Are AI Agents? + +An AI agent is a system that: + +- **Perceives** its environment through inputs (text, images, data, APIs) +- **Reasons** about what to do using an LLM as its "brain" +- **Acts** by calling tools, writing code, or interacting with systems +- **Learns** from feedback and adjusts its approach + + +Traditional chatbots wait for input and respond. Agents take initiative—they plan multi-step tasks, use tools autonomously, recover from errors, and persist until goals are achieved. + + +### The Role of Prompts in Agents + +In an agentic world, prompts become even more critical—but they serve different purposes: + +
+
+

System Prompts

+

Define the agent's identity, capabilities, constraints, and behavioral guidelines. These are the agent's "constitution."

+
+
+

Planning Prompts

+

Guide how agents break down complex goals into actionable steps. Critical for multi-step reasoning.

+
+
+

Tool-Use Prompts

+

Describe available tools and when/how to use them. Agents must understand their capabilities.

+
+
+

Reflection Prompts

+

Enable agents to evaluate their own outputs, catch errors, and improve iteratively.

+
+
+ +### Agent Architecture Patterns + +Modern agents follow recognizable patterns. Understanding these helps you design effective agent systems: + +**ReAct (Reasoning + Acting)** + +The agent alternates between reasoning about what to do and taking actions: + +
+
+
+

Think

+
+
→
+
+

Act

+
+
→
+
+

Observe

+
+
→
+
(repeat)
+
+
+ +**Plan-and-Execute** + +The agent creates a complete plan first, then executes steps: + +
+
+

Create Plan

+

Break goal into steps

+
+
↓
+
+
+

Step 1

+
+
→
+
+

Step 2

+
+
→
+
+

Step 3

+
+
→
+
...
+
+
↓
+
+

Revise if Needed

+

Adapt plan based on results

+
+
+ +### Prompting for Agents + +When designing prompts for agent systems, consider: + + + +### Multi-Agent Systems + +The future involves teams of specialized agents working together: + +
+
+
+
+

Coordinator

+

Manages workflow

+
+
+
⟷
+
↕
+
+
+

Researcher

+
+
+

Writer

+
+
+

Critic

+
+
+

Coder

+
+
+
+
+ +Each agent has its own system prompt defining its role, and they communicate through structured messages. The prompt engineer's job becomes **designing the team**—defining roles, communication protocols, and coordination strategies. + + +In an agentic future, prompt engineers become system architects. You're not just writing instructions—you're designing autonomous systems that can reason, plan, and act. The skills you've learned in this book are the foundation for this new discipline. + + +## Emerging Patterns + +### Prompt Orchestration + +Single prompts are giving way to **orchestrated systems**: + +
+
+

User Request

+
+
↓
+
+

Planner Agent

+

Breaks down task

+
+
↓
+
+

Researcher Agent

+

Gathers information

+
+
↓
+
+

Writer Agent

+

Creates content

+
+
↓
+
+

Reviewer Agent

+

Quality checks

+
+
↓
+
+

Final Output

+
+
+ +Future practitioners will design prompt *systems* rather than individual prompts. + +### Self-Improving Prompts + +AI systems are beginning to: + +- **Optimize their own prompts** - Meta-learning for better instructions +- **Learn from feedback** - Adapting based on outcomes +- **Generate training data** - Creating examples for fine-tuning +- **Evaluate themselves** - Building in quality assessment + + + +### Natural Language Programming + +The line between prompting and programming is blurring: + +- **Prompts as code** - Version-controlled, tested, deployed +- **LLMs as interpreters** - Natural language as executable instructions +- **Hybrid systems** - Combining traditional code with AI reasoning +- **AI-assisted development** - Models that write and debug code + +Understanding prompting increasingly means understanding software development. + +## Skills for the Future + +### What Will Remain Valuable + +Certain skills will remain essential regardless of how AI evolves: + +1. **Clear thinking** - Knowing what you actually want +2. **Domain expertise** - Understanding the problem space +3. **Critical evaluation** - Assessing AI output quality +4. **Ethical judgment** - Knowing what *should* be done +5. **Iterative refinement** - Continuous improvement mindset + +### What Will Change + +Other aspects will shift significantly: + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
TodayTomorrow
Writing detailed promptsDesigning agent systems
Manual prompt optimizationAutomated prompt tuning
Single-model expertiseMulti-model orchestration
Text-focused interactionMultimodal fluency
Individual productivityTeam-AI collaboration
+
+ +### Staying Current + +To keep your skills relevant: + +- **Experiment continuously** - Try new models and features as they release +- **Follow research** - Stay aware of academic developments +- **Join communities** - Learn from other practitioners +- **Build projects** - Apply skills to real problems +- **Teach others** - Solidify understanding by explaining + +## The Human Element + +### AI as Amplifier + +At its best, AI amplifies human capability rather than replacing it: + +- **Experts become more expert** - AI handles routine work, humans focus on insight +- **Creativity expands** - More ideas explored, more possibilities tested +- **Access democratizes** - Capabilities once requiring specialists become available to all +- **Collaboration deepens** - Human-AI teams exceed either alone + +### The Irreplaceable Human + +Certain qualities remain distinctly human: + +- **Original experience** - Living in the world, having emotions and relationships +- **Values and ethics** - Deciding what matters and what's right +- **Accountability** - Taking responsibility for outcomes +- **Meaning-making** - Understanding *why* something matters +- **Genuine creativity** - True novelty born from unique perspective + + +As AI handles more routine cognitive tasks, your unique value lies in judgment, creativity, domain expertise, and the human connections AI cannot replicate. Invest in what makes you irreplaceable. + + +## Final Reflections + +### What We've Learned + +Throughout this book, we've explored: + +- **Foundations** - How AI models work and what makes prompts effective +- **Techniques** - Role-based prompting, chain-of-thought, few-shot learning, and more +- **Advanced strategies** - System prompts, prompt chaining, multimodal interaction +- **Best practices** - Avoiding pitfalls, ethical considerations, optimization +- **Applications** - Writing, programming, education, business, creativity, research + +These techniques share common threads: + +1. **Be clear and specific** - Know what you want and communicate it precisely +2. **Provide context** - Give AI the information it needs +3. **Structure your requests** - Organization improves outputs +4. **Iterate and refine** - First attempts are starting points, not endpoints +5. **Evaluate critically** - AI output requires human judgment + +### The Art and Science + +Prompting is both **art and science**: + +- **Science**: Testable hypotheses, measurable outcomes, reproducible techniques +- **Art**: Intuition, creativity, knowing when to break the rules + +The best practitioners combine rigorous methodology with creative experimentation. They test systematically but also trust their instincts. They follow best practices but know when to deviate. + +### A Call to Create + +This book has given you tools. What you build with them is up to you. + +- **Solve problems** that matter to you and others +- **Create things** that didn't exist before +- **Help people** do things they couldn't do alone +- **Push boundaries** of what's possible +- **Stay curious** as the field evolves + +The age of AI is just beginning. The most important applications haven't been invented yet. The most powerful techniques haven't been discovered. The future is being written now—by people like you, one prompt at a time. + +## Looking Ahead + + + + +Visit [prompts.chat](https://prompts.chat) for community prompts, new techniques, and to share your own discoveries. The best learning happens in community. + + +## Summary + + +AI will continue evolving rapidly, but core skills of clear communication, critical thinking, and iterative refinement remain valuable. Focus on what makes you irreplaceable: judgment, creativity, ethics, and genuine human connection. The future of prompting is collaborative, multimodal, and integrated into larger systems. Stay curious, keep experimenting, and build things that matter. + + + + +Thank you for reading *The Interactive Book of Prompting*. Now go create something amazing. diff --git a/src/content/book/el/25-agents-and-skills.mdx b/src/content/book/el/25-agents-and-skills.mdx new file mode 100644 index 00000000..ba355859 --- /dev/null +++ b/src/content/book/el/25-agents-and-skills.mdx @@ -0,0 +1,551 @@ +As AI systems evolve from simple question-answering to autonomous task execution, understanding **agents** and **skills** becomes essential. This chapter explores how prompts serve as the fundamental building blocks for AI agents, and how skills package expertise into reusable, comprehensive instruction sets. + +
+
+
+
+ +
+

Agent

+

Autonomous AI system

+
+
+ powered by + ↓ +
+
+
+
+ +
+

Skill

+

Reusable expertise

+
+
+
+ +
+

Skill

+

Reusable expertise

+
+
+
+ +
+

Skill

+

Reusable expertise

+
+
+
+ composed of + ↓ +
+
+
+ + Prompt +
+
+ + Prompt +
+
+ + Prompt +
+
+ + Prompt +
+
+ + Prompt +
+
+

Prompts are atoms → Skills are molecules → Agents are complete structures

+
+
+ +## What Are AI Agents? + +An **AI agent** is an AI system that can autonomously plan, execute, and iterate on tasks. Unlike simple prompt-response interactions, agents can: + +- **Plan** - Break down complex goals into actionable steps +- **Execute** - Use tools and take actions in the real world +- **Observe** - Process feedback from their actions +- **Adapt** - Adjust their approach based on results +- **Persist** - Maintain context and memory across interactions + +
+
+
+
+

Goal

+
+
→
+
+
+
+

Plan

+
+
→
+
+

Execute

+
+
→
+
+

Observe

+
+
→
+
+

Adapt

+
+
+
+ ↺ Loop until complete +
+
+
→
+
+

Done

+
+
+
+
+ +## Prompts as Building Blocks + +Every agent, no matter how sophisticated, is built from prompts. Just as atoms combine to form molecules, and molecules combine to form complex structures, prompts combine to create intelligent agent behavior. + +
+
+

System Prompts

+

Identity & Role

+
+
+

Planning Prompts

+

How to Think

+
+
+

Tool Prompts

+

How to Act

+
+
+

Recovery Prompts

+

How to Recover

+
+
+ +These prompt types stack together to form complete agent behavior: + +### System Prompts (The Agent's Identity) + +The foundational prompt that establishes who the agent is and how it behaves: + +```markdown +You are a code review assistant. Your role is to: +- Analyze code for bugs, security issues, and performance problems +- Suggest improvements following best practices +- Explain your reasoning clearly +- Be constructive and educational in feedback + +You have access to tools for reading files, searching code, and running tests. +``` + +### Planning Prompts (How to Think) + +Instructions that guide the agent's reasoning and planning process: + +```markdown +Before taking action, always: +1. Understand the complete request +2. Break it into smaller, verifiable steps +3. Identify which tools you'll need +4. Consider edge cases and potential issues +5. Execute step by step, validating as you go +``` + +### Tool-Use Prompts (How to Act) + +Guidance on when and how to use available tools: + +```markdown +When you need to understand a codebase: +- Use grep_search for finding specific patterns +- Use read_file to examine file contents +- Use list_dir to explore directory structure +- Always verify your understanding before making changes +``` + +### Recovery Prompts (How to Handle Failure) + +Instructions for when things go wrong: + +```markdown +If an action fails: +1. Analyze the error message carefully +2. Consider alternative approaches +3. Ask for clarification if the task is ambiguous +4. Never repeat the same failed action without changes +``` + + +An agent's behavior emerges from layers of prompts working together. The system prompt sets the foundation, planning prompts guide reasoning, tool prompts enable action, and recovery prompts handle failures. Together, they create coherent, capable behavior. + + +## What Are Skills? + +If prompts are the atoms, **skills are the molecules**—reusable building blocks that give agents specific capabilities. + +A **skill** is a comprehensive, portable package of instructions that gives an AI agent expertise in a specific domain or task. Skills are the reusable blocks of agents: you build them once, and any agent can use them. + + +Write a skill for code review once. Now every coding agent—whether it's for Python, JavaScript, or Rust—can instantly become an expert code reviewer by loading that skill. Skills let you build agent capabilities like LEGO blocks. + + +### Anatomy of a Skill + +A well-designed skill typically includes: + +
+
+

📄 SKILL.md (Required)

+

The main instruction file. Contains the core expertise, guidelines, and behaviors that define the skill.

+
+
+

📚 Reference Docs

+

Supporting documentation, examples, and context the agent can reference while working.

+
+
+

🔧 Scripts & Tools

+

Helper scripts, templates, or tool configurations that support the skill's functionality.

+
+
+

⚙️ Configuration

+

Settings, parameters, and customization options for adapting the skill to different contexts.

+
+
+ +### Example: Code Review Skill + +Here's what a code review skill might look like: + +
+
+ 📁 + code-review-skill/ +
+
+
+ 📄 + SKILL.md + Core review guidelines +
+
+ 📄 + security-checklist.md + Security patterns +
+
+ 📄 + performance-tips.md + Optimization guide +
+
+
+ 📁 + language-specific/ +
+
+
+ 📄 + python.md + Python best practices +
+
+ 📄 + javascript.md + JavaScript patterns +
+
+ 📄 + rust.md + Rust guidelines +
+
+
+
+
+ +The `SKILL.md` file defines the overall approach: + +```markdown +--- +name: code-review +description: Comprehensive code review with security, performance, and style analysis +--- + +# Code Review Skill + +You are an expert code reviewer. When reviewing code: + +## Process +1. **Understand Context** - What does this code do? What problem does it solve? +2. **Check Correctness** - Does it work? Are there logic errors? +3. **Security Scan** - Reference security-checklist.md for common vulnerabilities +4. **Performance Review** - Check performance-tips.md for optimization opportunities +5. **Style & Maintainability** - Is the code readable and maintainable? + +## Output Format +Provide feedback in categories: +- 🔴 **Critical** - Must fix before merge +- 🟡 **Suggested** - Recommended improvements +- 🟢 **Nice to have** - Optional enhancements + +Always explain *why* something is an issue, not just *what* is wrong. +``` + +## Skills vs. Simple Prompts + +
+
+

Simple Prompt

+
+

Single instruction

+

One-off use

+

Limited context

+

Generic approach

+

No supporting materials

+
+
+
+

Skill

+
+

Comprehensive instruction set

+

Reusable across projects

+

Rich context with references

+

Domain-specific expertise

+

Supporting docs, scripts, configs

+
+
+
+ +## Building Effective Skills + +### 1. Define the Expertise Clearly + +Start with a clear description of what the skill enables: + +```markdown +--- +name: api-design +description: Design RESTful APIs following industry best practices, + including versioning, error handling, and documentation standards +--- +``` + +### 2. Structure Knowledge Hierarchically + +Organize information from general to specific: + +```markdown +# API Design Skill + +## Core Principles +- Resources should be nouns, not verbs +- Use HTTP methods semantically +- Version your APIs from day one + +## Detailed Guidelines +[More specific rules...] + +## Reference Materials +- See `rest-conventions.md` for naming conventions +- See `error-codes.md` for standard error responses +``` + +### 3. Include Concrete Examples + +Abstract rules become clear with examples: + +```markdown +## Endpoint Naming + +✅ Good: +- GET /users/{id} +- POST /orders +- DELETE /products/{id}/reviews/{reviewId} + +❌ Avoid: +- GET /getUser +- POST /createNewOrder +- DELETE /removeProductReview +``` + +### 4. Provide Decision Frameworks + +Help the agent make choices in ambiguous situations: + +```markdown +## When to Use Pagination + +Use pagination when: +- Collection could exceed 100 items +- Response size impacts performance +- Client may not need all items + +Use full response when: +- Collection is always small (<20 items) +- Client typically needs everything +- Real-time consistency is critical +``` + +### 5. Add Recovery Patterns + +Anticipate what can go wrong: + +```markdown +## Common Issues + +**Problem**: Client needs fields not in standard response +**Solution**: Implement field selection: GET /users?fields=id,name,email + +**Problem**: Breaking changes needed +**Solution**: Create new version, deprecate old with timeline +``` + +## Composing Skills + +Agents become powerful when multiple skills work together. Consider how skills can complement each other: + +
+
+ Code Review +
+
+
+
+ Security Audit +
+
+
+
+ Documentation +
+
=
+
+ Complete Code Quality Agent +
+
+ +When composing skills, ensure they don't conflict. Skills should be: + +- **Modular** - Each skill handles one domain well +- **Compatible** - Skills shouldn't give contradictory instructions +- **Prioritized** - When skills overlap, define which takes precedence + +## Sharing and Discovering Skills + +Skills are most valuable when shared. Platforms like [prompts.chat](https://prompts.chat/skills) allow you to: + +- **Discover** community-created skills for common tasks +- **Download** skills directly to your projects +- **Share** your own expertise as reusable skills +- **Iterate** on skills based on real-world usage + + +Before building a skill from scratch, check if someone has already solved your problem. Community skills are battle-tested and often better than starting from zero. + + +## The Agent-Skill Ecosystem + +The relationship between agents and skills creates a powerful ecosystem: + +
+
+ AI Agent +
+
+
+

Code Review

+

Skill 1

+
+
+

API Design

+

Skill 2

+
+
+

Test Writing

+

Skill 3

+
+
+
+
↓
+
+
+
+

Core Prompts

+

Planning • Tools • Recovery • Memory

+
+
+
+ +The agent provides the execution framework—planning, tool use, and memory—while skills provide domain expertise. This separation means: + +- **Skills are portable** - The same skill works with different agents +- **Agents are extensible** - Add new capabilities by adding skills +- **Expertise is shareable** - Domain experts can contribute skills without building full agents + +## Best Practices + +### For Building Skills + +1. **Start specific, then generalize** - Build a skill for your exact use case first, then abstract +2. **Include failure cases** - Document what the skill can't do and how to handle it +3. **Version your skills** - Track changes so agents can depend on stable versions +4. **Test with real tasks** - Validate skills against actual work, not just theory + +### For Using Skills with Agents + +1. **Read the skill first** - Understand what a skill does before deploying it +2. **Customize thoughtfully** - Override skill defaults only when necessary +3. **Monitor performance** - Track how well skills perform in your context +4. **Contribute improvements** - When you improve a skill, consider sharing back + + +As AI agents become more capable, the ability to compose, share, and customize skills will become a core competency. The prompt engineers of tomorrow won't just write prompts—they'll architect skill ecosystems that make AI agents genuinely expert in specific domains. + + + + + + + diff --git a/src/content/book/es/00a-preface.mdx b/src/content/book/es/00a-preface.mdx new file mode 100644 index 00000000..b824f6c1 --- /dev/null +++ b/src/content/book/es/00a-preface.mdx @@ -0,0 +1,82 @@ +
+ Fatih Kadir Akın +
+ Fatih Kadir Akın + Creador de Awesome ChatGPT Prompts (también conocido como prompts.chat) + + Desarrollador de software de Estambul, liderando Relaciones con Desarrolladores en Teknasyon. Autor de libros sobre JavaScript e ingeniería de prompts. Defensor del código abierto especializado en tecnologías web y desarrollo asistido por IA. + + +
+
+ +Todavía recuerdo la noche en que todo cambió. + +Era el **30 de noviembre de 2022**. Estaba sentado en mi escritorio, navegando por Twitter, cuando vi gente hablando sobre algo llamado "ChatGPT". Hice clic en el enlace, pero ¿honestamente? No esperaba mucho. Había probado esas viejas herramientas de IA de "completar palabras" antes, las que generaban tonterías después de unas pocas oraciones. Pensé que esto sería más de lo mismo. + +Escribí una pregunta simple y presioné enter. + +Entonces me quedé paralizado. + +La respuesta no era solo coherente. Era *buena*. Entendía lo que quería decir. Podía razonar. Se sentía completamente diferente a todo lo que había visto antes. Probé otro prompt. Y otro. Cada respuesta me asombraba más que la anterior. + +No pude dormir esa noche. Por primera vez, sentí que realmente estaba *hablando* con una máquina, y me respondía de una manera que realmente tenía sentido. + +## Un Repositorio Nacido del Asombro + +En esos primeros días, no estaba solo en mi entusiasmo. Donde mirara, la gente estaba descubriendo formas creativas de usar ChatGPT. Los profesores lo usaban para explicar conceptos complejos. Los escritores colaboraban con él en historias. Los desarrolladores depuraban código con su ayuda. + +Empecé a recopilar los mejores prompts que encontraba. Los que funcionaban como magia. Los que convertían preguntas simples en respuestas brillantes. Y pensé: *¿Por qué guardarme esto para mí?* + +Así que creé un simple repositorio de GitHub llamado [Awesome ChatGPT Prompts](https://github.com/f/prompts.chat). Esperaba que quizás unos cientos de personas lo encontrarían útil. + +Estaba equivocado. + +En semanas, el repositorio despegó. Miles de estrellas. Luego decenas de miles. Personas de todo el mundo empezaron a agregar sus propios prompts, compartiendo lo que aprendían y ayudándose mutuamente. Lo que empezó como mi colección personal se convirtió en algo mucho más grande: una comunidad mundial de personas curiosas ayudándose entre sí. + +Hoy, ese repositorio tiene más de **140,000 estrellas en GitHub** y contribuciones de cientos de personas que nunca he conocido pero por las que estoy profundamente agradecido. + +## Por Qué Escribí Este Libro + +La versión original de este libro se publicó en [Gumroad](https://gumroad.com/l/the-art-of-chatgpt-prompting) a **principios de 2023**, solo meses después del lanzamiento de ChatGPT. Fue uno de los primeros libros jamás escritos sobre ingeniería de prompts, un intento de capturar todo lo que había aprendido sobre crear prompts efectivos cuando el campo era completamente nuevo. Para mi asombro, más de **100,000 personas** lo descargaron. + +Pero han pasado tres años desde entonces. La IA ha cambiado mucho. Han aparecido nuevos modelos. Y todos hemos aprendido mucho más sobre cómo hablar con la IA. + +Esta nueva edición es mi regalo a la comunidad que me dio tanto. Contiene todo lo que desearía haber sabido cuando empecé: **lo que funciona**, **lo que evitar**, e **ideas que permanecen verdaderas** sin importar qué IA uses. + +## Lo Que Este Libro Significa Para Mí + +No voy a pretender que esto es solo un manual de instrucciones. Significa más que eso para mí. + +Este libro captura un momento cuando el mundo cambió, y la gente se unió para entenderlo. Representa noches de probar cosas, la alegría del descubrimiento, y la amabilidad de extraños que compartieron lo que aprendieron. + +Sobre todo, representa mi creencia de que **la mejor manera de aprender algo es compartirlo con otros**. + +## Para Ti + +Ya sea que estés empezando con la IA o la hayas estado usando por años, escribí este libro para ti. + +Espero que te ahorre tiempo. Espero que despierte ideas. Espero que te ayude a lograr cosas que nunca pensaste posibles. + +Y cuando descubras algo increíble, espero que lo compartas con otros, así como tantas personas compartieron conmigo. + +**Así es como todos mejoramos juntos.** + +Gracias por estar aquí. Gracias por ser parte de esta comunidad. + +Ahora, comencemos. + +--- + +*Con gratitud,* + +**Fatih Kadir Akın** +*Estambul, enero 2025* diff --git a/src/content/book/es/00b-history.mdx b/src/content/book/es/00b-history.mdx new file mode 100644 index 00000000..5a9c423b --- /dev/null +++ b/src/content/book/es/00b-history.mdx @@ -0,0 +1,159 @@ +# La Historia de Awesome ChatGPT Prompts + +## El Comienzo: Noviembre 2022 + +Cuando ChatGPT se lanzó por primera vez en noviembre de 2022, el mundo de la IA cambió de la noche a la mañana. Lo que antes era dominio de investigadores y desarrolladores de repente se volvió accesible para todos. Entre los cautivados por esta nueva tecnología estaba Fatih Kadir Akın, un desarrollador que vio algo extraordinario en las capacidades de ChatGPT. + +> "Cuando ChatGPT se lanzó por primera vez, inmediatamente quedé cautivado por sus capacidades. Experimenté con la herramienta de diversas maneras y constantemente me asombraban los resultados." + +Esos primeros días estuvieron llenos de experimentación y descubrimiento. Usuarios de todo el mundo estaban encontrando formas creativas de interactuar con ChatGPT, compartiendo sus hallazgos y aprendiendo unos de otros. Fue en esta atmósfera de emoción y exploración donde nació la idea de "Awesome ChatGPT Prompts". + +## El Repositorio Que Lo Empezó Todo + +En diciembre de 2022, apenas semanas después del lanzamiento de ChatGPT, se creó el repositorio [Awesome ChatGPT Prompts](https://github.com/f/prompts.chat) en GitHub. El concepto era simple pero poderoso: una colección curada de prompts efectivos que cualquiera podía usar y a la que cualquiera podía contribuir. + +El repositorio rápidamente ganó tracción, convirtiéndose en un recurso de referencia para usuarios de ChatGPT en todo el mundo. Lo que empezó como una colección personal de prompts útiles evolucionó hacia un proyecto impulsado por la comunidad con contribuciones de desarrolladores, escritores, educadores y entusiastas de todos los rincones del planeta. + +### Logros + +**Prensa y Medios** +- Destacado en [Forbes](https://www.forbes.com/sites/bernardmarr/2023/05/17/the-best-prompts-for-chatgpt-a-complete-guide/) como uno de los mejores recursos de prompts para ChatGPT + +**Reconocimiento Académico** +- Referenciado por la [Universidad de Harvard](https://www.huit.harvard.edu/news/ai-prompts) en su guía de IA +- Referenciado por la Biblioteca de Prompts de la [Universidad de Columbia](https://etc.cuit.columbia.edu/news/columbia-prompt-library-effective-academic-ai-use) +- Utilizado por [Olympic College](https://libguides.olympic.edu/UsingAI/Prompts) en sus recursos de IA +- Citado en [artículos académicos en arXiv](https://arxiv.org/pdf/2502.04484) +- [40+ citas académicas](https://scholar.google.com/citations?user=AZ0Dg8YAAAAJ&hl=en) en Google Scholar + +**Comunidad y GitHub** +- [142,000+ estrellas en GitHub](https://github.com/f/prompts.chat) — uno de los repositorios de IA más destacados +- Seleccionado como [Elección del Personal de GitHub](https://spotlights-feed.github.com/spotlights/prompts-chat/) +- Dataset más gustado publicado en [Hugging Face](https://huggingface.co/datasets/fka/prompts.chat) +- Utilizado por miles de desarrolladores en todo el mundo + +## El Primer Libro: "El Arte del Prompting con ChatGPT" + +El éxito del repositorio llevó a la creación de "The Art of ChatGPT Prompting: A Guide to Crafting Clear and Effective Prompts" — una guía integral publicada en Gumroad a principios de 2023. + +El libro capturó la sabiduría temprana de la ingeniería de prompts, cubriendo: + +- Entender cómo funciona ChatGPT +- Principios de comunicación clara con IA +- La famosa técnica "Actúa Como" +- Crear prompts efectivos paso a paso +- Errores comunes y cómo evitarlos +- Consejos para resolver problemas + +**El libro se convirtió en un fenómeno**, logrando más de **100,000 descargas** en Gumroad. Se compartió en redes sociales, se referenció en artículos académicos, y fue traducido por miembros de la comunidad a múltiples idiomas. Respaldos de alto perfil llegaron de lugares inesperados — incluso [Greg Brockman](https://x.com/gdb/status/1602072566671110144), cofundador y presidente de OpenAI, reconoció el proyecto. + +## Perspectivas Tempranas Que Moldearon el Campo + +Durante esos meses formativos, surgieron varias perspectivas clave que se convertirían en fundamentales para la ingeniería de prompts: + +### 1. La Especificidad Importa + +> "Aprendí la importancia de usar un lenguaje específico y relevante para asegurar que ChatGPT entienda mis prompts y pueda generar respuestas apropiadas." + +Los primeros experimentadores descubrieron que los prompts vagos llevaban a respuestas vagas. Cuanto más específico y detallado el prompt, más útil la respuesta. + +### 2. Propósito y Enfoque + +> "Descubrí el valor de definir un propósito y enfoque claros para la conversación, en lugar de usar prompts abiertos o demasiado amplios." + +Esta perspectiva se convirtió en la base para las técnicas de prompting estructurado que se desarrollarían en los años siguientes. + +### 3. La Revolución del "Actúa Como" + +Una de las técnicas más influyentes que surgió de la comunidad fue el patrón "Actúa Como". Al instruir a ChatGPT para que asuma un rol o persona específica, los usuarios podían mejorar dramáticamente la calidad y relevancia de las respuestas. + +``` +Quiero que actúes como una consola de javascript. Escribiré comandos y +tú responderás con lo que la consola de javascript debería mostrar. Quiero +que solo respondas con la salida del terminal dentro de un único bloque +de código, y nada más. +``` + +Esta técnica simple abrió incontables posibilidades y sigue siendo una de las estrategias de prompting más utilizadas hoy en día. + +## La Evolución de prompts.chat + +### 2022: El Comienzo + +El proyecto comenzó como un simple repositorio de GitHub con un archivo README renderizado como HTML en GitHub Pages. Era básico pero funcional — un testimonio del principio de que las grandes ideas no necesitan implementaciones elaboradas. + +**Stack Tecnológico**: HTML, CSS, GitHub Pages + +### 2024: Renovación de UI + +A medida que la comunidad crecía, también lo hacía la necesidad de una mejor experiencia de usuario. El sitio recibió una actualización significativa de UI, construida con la ayuda de asistentes de código IA como Cursor y Claude Sonnet 3.5. + +### 2025: La Plataforma Actual + +Hoy, prompts.chat ha evolucionado hacia una plataforma completa construida con: + +- **Next.js** para el framework web +- **Vercel** para hosting +- **Desarrollo asistido por IA** usando Windsurf y Claude + +La plataforma ahora incluye cuentas de usuario, colecciones, búsqueda, categorías, etiquetas y una próspera comunidad de ingenieros de prompts. + +### Apps Nativas + +El proyecto se expandió más allá de la web con una app nativa de iOS construida con SwiftUI, llevando la biblioteca de prompts a los usuarios móviles. + +## Impacto en la Comunidad + +El proyecto Awesome ChatGPT Prompts ha tenido un profundo impacto en cómo las personas interactúan con la IA: + +### Reconocimiento Académico + +Universidades de todo el mundo han referenciado el proyecto en sus materiales de guía de IA, incluyendo: + +- Universidad de Harvard +- Universidad de Columbia +- Olympic College +- Numerosos artículos académicos en arXiv + +### Adopción por Desarrolladores + +El proyecto se ha integrado en innumerables flujos de trabajo de desarrolladores. El dataset de Hugging Face es utilizado por investigadores y desarrolladores para entrenar y afinar modelos de lenguaje. + +### Comunidad Global + +Con contribuciones de cientos de miembros de la comunidad en docenas de países, el proyecto representa un esfuerzo verdaderamente global para hacer la IA más accesible y útil para todos. + +## La Filosofía: Abierto y Gratuito + +Desde el principio, el proyecto ha estado comprometido con la apertura. Licenciado bajo CC0 1.0 Universal (Dedicación al Dominio Público), todos los prompts y contenidos son libres de usar, modificar y compartir sin restricciones. + +Esta filosofía ha permitido: + +- Traducciones a múltiples idiomas +- Integración en otras herramientas y plataformas +- Uso académico e investigación +- Aplicaciones comerciales + +El objetivo siempre ha sido democratizar el acceso a técnicas efectivas de comunicación con IA — para asegurar que todos, independientemente de su formación técnica, puedan beneficiarse de estas herramientas. + +## Tres Años Después + +Tres años después del lanzamiento de ChatGPT, el campo de la ingeniería de prompts ha madurado significativamente. Lo que comenzó como experimentación informal ha evolucionado hacia una disciplina reconocida con patrones establecidos, mejores prácticas y una comunidad de investigación activa. + +El proyecto Awesome ChatGPT Prompts ha crecido junto con este campo, evolucionando de una simple lista de prompts a una plataforma integral para descubrir, compartir y aprender sobre prompts de IA. + +Este libro representa la siguiente evolución — una destilación de tres años de sabiduría comunitaria, actualizada para el panorama de IA de hoy y mañana. + +## Mirando Hacia Adelante + +El viaje desde ese primer repositorio hasta esta guía integral refleja la rápida evolución de la IA y nuestra comprensión de cómo trabajar con ella efectivamente. A medida que las capacidades de IA continúan avanzando, también lo harán las técnicas para comunicarse con estos sistemas. + +Los principios descubiertos en esos primeros días — claridad, especificidad, propósito y el poder del juego de roles — siguen siendo tan relevantes como siempre. Pero nuevas técnicas continúan emergiendo: prompting de cadena de pensamiento, aprendizaje de pocos ejemplos, interacciones multimodales y más. + +La historia de Awesome ChatGPT Prompts es en última instancia una historia sobre comunidad — sobre miles de personas alrededor del mundo compartiendo sus descubrimientos, ayudándose mutuamente a aprender, y avanzando colectivamente nuestra comprensión de cómo trabajar con IA. + +Ese espíritu de colaboración abierta y aprendizaje compartido es lo que este libro espera continuar. + +--- + +*El proyecto Awesome ChatGPT Prompts es mantenido por [@f](https://github.com/f) y una increíble comunidad de contribuidores. Visita [prompts.chat](https://prompts.chat) para explorar la plataforma, y únete a nosotros en [GitHub](https://github.com/f/prompts.chat) para contribuir.* diff --git a/src/content/book/es/00c-introduction.mdx b/src/content/book/es/00c-introduction.mdx new file mode 100644 index 00000000..cabff425 --- /dev/null +++ b/src/content/book/es/00c-introduction.mdx @@ -0,0 +1,130 @@ +Bienvenido a **El Libro Interactivo de Prompting**, tu guía para comunicarte efectivamente con la IA. + + +Al final de este libro, entenderás cómo funciona la IA, cómo escribir mejores prompts y cómo usar estas habilidades para escritura, programación, investigación y proyectos creativos. + + + +A diferencia de los libros tradicionales, esta guía es completamente interactiva. Encontrarás demostraciones en vivo, ejemplos clicables y botones "Pruébalo" que te permiten probar prompts instantáneamente. Aprender haciendo hace que los conceptos complejos sean mucho más fáciles de entender. + + +## ¿Qué es la Ingeniería de Prompts? + +La ingeniería de prompts es la habilidad de escribir buenas instrucciones para la IA. Cuando escribes algo a ChatGPT, Claude, Gemini u otras herramientas de IA, eso se llama un "prompt". Cuanto mejor sea tu prompt, mejor será la respuesta que obtengas. + +Piénsalo así: la IA es un ayudante poderoso que toma tus palabras muy literalmente. Hará exactamente lo que le pidas. El truco es aprender a pedir exactamente lo que quieres. + + + +La diferencia en la calidad del resultado entre estos dos prompts puede ser dramática. + + + +## Cómo Ha Evolucionado la Ingeniería de Prompts + +En solo tres años desde que se lanzó ChatGPT, la ingeniería de prompts ha evolucionado dramáticamente junto con la tecnología misma. Lo que comenzó simplemente como "escribir mejores preguntas" ha crecido hacia algo mucho más amplio. + +Hoy, entendemos que tu prompt es solo **una parte de un contexto más grande**. Los sistemas de IA modernos trabajan con múltiples tipos de datos simultáneamente: + +- **Prompts de sistema** que definen el comportamiento de la IA +- **Historial de conversación** de mensajes anteriores +- **Documentos recuperados** extraídos de bases de datos (RAG) +- **Definiciones de herramientas** que permiten a la IA tomar acciones +- **Preferencias de usuario** y configuraciones +- **Tu prompt actual** - la pregunta que estás haciendo ahora mismo + +Este cambio de "ingeniería de prompts" a "ingeniería de contexto" refleja cómo ahora pensamos sobre las interacciones con IA. Tu prompt importa, pero también importa todo lo demás que la IA ve. Los mejores resultados vienen de gestionar cuidadosamente todas estas piezas juntas. + +Exploraremos estos conceptos en profundidad a lo largo de este libro, especialmente en el capítulo de [Ingeniería de Contexto](/book/20-context-engineering). + +## ¿Por Qué Importa la Ingeniería de Prompts? + +### 1. Obtener Mejores Respuestas + +Las herramientas de IA son increíblemente capaces, pero necesitan instrucciones claras para desbloquear su potencial completo. La misma IA que da una respuesta mediocre a una pregunta vaga puede producir un trabajo brillante cuando se le da el prompt correcto. + + + +### 2. Ahorrar Tiempo y Dinero + +Un prompt bien elaborado obtiene resultados en un intento en lugar de múltiples intercambios de ida y vuelta. Esto importa aún más cuando pagas por token o trabajas con límites de uso. Una inversión de 5 minutos en escribir un buen prompt puede ahorrar horas de iteración. + +### 3. Obtener Resultados Consistentes y Reproducibles + +Los buenos prompts producen resultados predecibles. Esto es crítico para: +- **Flujos de trabajo empresariales** donde necesitas la misma calidad cada vez +- **Automatización** donde los prompts se ejecutan sin revisión humana +- **Equipos** donde múltiples personas necesitan resultados similares + +### 4. Desbloquear Capacidades Avanzadas + +Muchas funciones poderosas de IA solo funcionan cuando sabes cómo preguntar: +- **Razonamiento de cadena de pensamiento** para problemas complejos +- **Salida estructurada** para extracción de datos +- **Juego de roles** para experiencia especializada +- **Aprendizaje de pocos ejemplos** para tareas personalizadas + +Sin conocimiento de ingeniería de prompts, solo estás usando una fracción de lo que la IA puede hacer. + +### 5. Mantenerse Seguro y Evitar Trampas + +Un buen prompting te ayuda a: +- Evitar alucinaciones pidiendo fuentes y verificación +- Obtener perspectivas equilibradas en lugar de respuestas unilaterales +- Prevenir que la IA haga suposiciones que no pretendías +- Mantener información sensible fuera de tus prompts + +### 6. Preparar tus Habilidades para el Futuro + +A medida que la IA se integra más en el trabajo y la vida, la ingeniería de prompts se convierte en una alfabetización fundamental. Los principios que aprendes aquí se aplican a todas las herramientas de IA—ChatGPT, Claude, Gemini, generadores de imágenes y modelos futuros que aún no hemos visto. + +## ¿Para Quién Es Este Libro? + +Este libro es para todos: + +- **Principiantes** que quieren aprender a usar mejor las herramientas de IA +- **Estudiantes** trabajando en tareas, investigación o proyectos creativos +- **Escritores y creadores** usando IA para su trabajo +- **Desarrolladores** construyendo aplicaciones con IA +- **Profesionales de negocios** que quieren usar IA en el trabajo +- **Cualquier persona curiosa** sobre sacar más provecho de los asistentes de IA + +## Cómo Está Organizado Este Libro + + + +Además de un **Apéndice** con plantillas, ayuda para solución de problemas, glosario y recursos adicionales. + +## Una Nota Sobre los Modelos de IA + +Este libro usa principalmente ejemplos de ChatGPT (ya que es el más popular), pero las ideas funcionan con cualquier herramienta de IA como Claude, Gemini u otras. Mencionaremos cuando algo solo funcione con modelos de IA específicos. + +La IA está cambiando rápido. Lo que funciona hoy podría ser reemplazado por algo mejor mañana. Por eso este libro se enfoca en ideas centrales que seguirán siendo útiles sin importar qué IA uses. + +## Comencemos + +Escribir buenos prompts es una habilidad que mejora con la práctica. Mientras lees este libro: + +1. **Prueba cosas** - Prueba los ejemplos, cámbialos, ve qué pasa +2. **Sigue intentando** - No esperes resultados perfectos en tu primer intento +3. **Toma notas** - Escribe lo que funciona y lo que no +4. **Comparte** - Agrega tus descubrimientos a [prompts.chat](https://prompts.chat) + + +La mejor manera de aprender es haciendo. Cada capítulo tiene ejemplos que puedes probar inmediatamente. No solo leas. ¡Pruébalo tú mismo! + + +¿Listo para transformar cómo trabajas con la IA? Pasa la página y comencemos. + +--- + +*Este libro es parte del proyecto [Awesome ChatGPT Prompts](https://github.com/f/prompts.chat) y está licenciado bajo CC0 1.0 Universal (Dominio Público).* diff --git a/src/content/book/es/01-understanding-ai-models.mdx b/src/content/book/es/01-understanding-ai-models.mdx new file mode 100644 index 00000000..3d7d3faf --- /dev/null +++ b/src/content/book/es/01-understanding-ai-models.mdx @@ -0,0 +1,302 @@ +Antes de aprender técnicas de prompts, ayuda entender cómo funcionan realmente los modelos de lenguaje de IA. Este conocimiento te hará mejor escribiendo prompts. + + +Entender cómo funciona la IA no es solo para expertos. Ayuda directamente a escribir mejores prompts. Una vez que sepas que la IA predice lo que viene después, naturalmente darás instrucciones más claras. + + +## ¿Qué Son los Modelos de Lenguaje Grande? + +Los Modelos de Lenguaje Grande (LLMs por sus siglas en inglés) son sistemas de IA que aprendieron leyendo enormes cantidades de texto. Pueden escribir, responder preguntas y tener conversaciones que suenan humanas. Se llaman "grandes" porque tienen miles de millones de pequeños ajustes (llamados parámetros) que fueron ajustados durante el entrenamiento. + +### Cómo Funcionan los LLMs (Simplificado) + +En su núcleo, los LLMs son máquinas de predicción. Les das algo de texto, y predicen lo que debería venir después. + + + +Cuando escribes "La capital de Francia es...", la IA predice "París" porque eso es lo que usualmente viene después en texto sobre Francia. Esta idea simple, repetida miles de millones de veces con cantidades masivas de datos, crea un comportamiento sorprendentemente inteligente. + + + +### Conceptos Clave + +**Tokens**: La IA no lee letra por letra. Divide el texto en fragmentos llamados "tokens". Un token podría ser una palabra completa como "hola" o parte de una palabra como "ando". Entender los tokens ayuda a explicar por qué la IA a veces comete errores de ortografía o tiene problemas con ciertas palabras. + + +Un token es la unidad más pequeña de texto que un modelo de IA procesa. No siempre es una palabra completa—podría ser un fragmento de palabra, puntuación o espacio en blanco. Por ejemplo, "increíble" podría convertirse en 3 tokens: "in" + "creí" + "ble". En promedio, **1 token ≈ 4 caracteres** o **100 tokens ≈ 75 palabras**. Los costos de API y límites de contexto se miden en tokens. + + + + +**Ventana de Contexto**: Esta es cuánto texto puede "recordar" la IA en una conversación. Piénsalo como la memoria a corto plazo de la IA. Incluye todo: tu pregunta Y la respuesta de la IA. + + + +Las ventanas de contexto varían por modelo y se están expandiendo rápidamente: + +
+
+ GPT-4o + 128K tokens +
+
+ GPT-5 + 400K tokens +
+
+ Claude Sonnet 4 + 1M tokens +
+
+ Gemini 2.5 + 1M tokens +
+
+ Llama 4 + 1M-10M tokens +
+
+ DeepSeek R1 + 128K tokens +
+
+ +**Temperatura**: Esto controla qué tan creativa o predecible es la IA. Temperatura baja (0.0-0.3) te da respuestas enfocadas y consistentes. Temperatura alta (0.7-1.0) te da respuestas más creativas y sorprendentes. + + + +**Prompt de Sistema**: Instrucciones especiales que le dicen a la IA cómo comportarse durante toda una conversación. Por ejemplo, "Eres un maestro amigable que explica las cosas de manera simple." No todas las herramientas de IA te permiten configurar esto, pero es muy poderoso cuando está disponible. + +## Tipos de Modelos de IA + +### Modelos de Texto (LLMs) +El tipo más común, estos generan respuestas de texto a entradas de texto. Alimentan chatbots, asistentes de escritura y generadores de código. Ejemplos: GPT-4, Claude, Llama, Mistral. + +### Modelos Multimodales +Estos pueden entender más que solo texto. Pueden ver imágenes, escuchar audio y ver videos. Ejemplos: GPT-4V, Gemini, Claude 3. + +### Modelos de Texto a Imagen + + +Aunque este libro se enfoca principalmente en prompting para Modelos de Lenguaje Grande (IA basada en texto), los principios de prompting claro y específico también aplican a la generación de imágenes. Dominar prompts para estos modelos es igualmente importante para obtener excelentes resultados. + + +Los modelos de texto a imagen como DALL-E, Midjourney, Nano Banana y Stable Diffusion crean imágenes a partir de descripciones de texto. Funcionan diferente de los modelos de texto: + +**Cómo Funcionan:** +1. **Entrenamiento**: El modelo aprende de millones de pares imagen-texto, entendiendo qué palabras corresponden a qué conceptos visuales +2. **Proceso de Difusión**: Comenzando desde ruido aleatorio, el modelo gradualmente refina la imagen, guiado por tu prompt de texto +3. **Guía CLIP**: Un modelo separado (CLIP) ayuda a conectar tus palabras con conceptos visuales, asegurando que la imagen coincida con tu descripción + + + +**El Prompting para Imágenes es Diferente:** +A diferencia de los prompts de texto donde escribes oraciones, los prompts de imagen a menudo funcionan mejor como frases descriptivas separadas por comas: + + + +### Modelos de Texto a Video + +El texto a video es la frontera más nueva. Modelos como Sora 2, Runway y Veo crean imágenes en movimiento a partir de descripciones de texto. Como los modelos de imagen, la calidad de tu prompt determina directamente la calidad de tu resultado—la ingeniería de prompts es igual de crucial aquí. + +**Cómo Funcionan:** +1. **Comprensión Temporal**: Más allá de imágenes individuales, estos modelos entienden cómo las cosas se mueven y cambian con el tiempo +2. **Simulación de Física**: Aprenden física básica—cómo caen los objetos, cómo fluye el agua, cómo caminan las personas +3. **Consistencia de Cuadros**: Mantienen sujetos y escenas consistentes a través de muchos cuadros +4. **Difusión en el Tiempo**: Similar a los modelos de imagen, pero generando secuencias coherentes en lugar de cuadros individuales + + + + +Los prompts de video necesitan describir acción a través del tiempo, no solo una escena estática. Incluye verbos y movimiento: + + + + +### Modelos Especializados +Afinados para tareas específicas como generación de código (Codex, CodeLlama), generación de música (Suno, Udio), o aplicaciones específicas de dominio como diagnóstico médico o análisis de documentos legales. + +## Capacidades y Limitaciones de los Modelos + +Explora lo que los LLMs pueden y no pueden hacer. Haz clic en cada capacidad para ver prompts de ejemplo: + + + +### Entendiendo las Alucinaciones + + +A veces la IA escribe cosas que suenan verdaderas pero no lo son. Esto se llama "alucinación". No es un error. Es solo cómo funciona la predicción. Siempre verifica los hechos importantes. + + +¿Por qué la IA inventa cosas? + +1. Intenta escribir texto que suena bien, no texto que siempre es verdadero +2. Internet (de donde aprendió) también tiene errores +3. Realmente no puede verificar si algo es real + + + +- **Pide fuentes**: Luego verifica si esas fuentes son reales +- **Pide razonamiento paso a paso**: Para que puedas verificar cada paso +- **Verifica hechos importantes**: Usa Google o sitios web confiables +- **Pregunta "¿Estás seguro?"**: La IA podría admitir incertidumbre + + + + + +## Cómo Aprende la IA: Los Tres Pasos + +La IA no sabe las cosas mágicamente. Pasa por tres pasos de aprendizaje, como ir a la escuela: + +### Paso 1: Pre-entrenamiento (Aprender a Leer) + +Imagina leer cada libro, sitio web y artículo en internet. Eso es lo que pasa en el pre-entrenamiento. La IA lee miles de millones de palabras y aprende patrones: + +- Cómo se construyen las oraciones +- Qué palabras usualmente van juntas +- Hechos sobre el mundo +- Diferentes estilos de escritura + +Esto toma meses y cuesta millones de dólares. Después de este paso, la IA sabe mucho, pero aún no es muy útil. Podría simplemente continuar lo que escribas, incluso si eso no es lo que querías. + + + +### Paso 2: Ajuste Fino (Aprender a Ayudar) + +Ahora la IA aprende a ser un buen asistente. Los entrenadores le muestran ejemplos de conversaciones útiles: + +- "Cuando alguien hace una pregunta, da una respuesta clara" +- "Cuando te pidan hacer algo dañino, rechaza amablemente" +- "Sé honesto sobre lo que no sabes" + +Piénsalo como enseñar buenos modales. La IA aprende la diferencia entre solo predecir texto y realmente ser útil. + + + +Prueba el prompt de arriba. ¿Notas cómo la IA se niega? Eso es el ajuste fino en acción. + +### Paso 3: RLHF (Aprender lo que les Gusta a los Humanos) + +RLHF significa "Reinforcement Learning from Human Feedback" (Aprendizaje por Refuerzo con Retroalimentación Humana). Es una forma elegante de decir: los humanos califican las respuestas de la IA, y la IA aprende a dar mejores respuestas. + +Así es como funciona: +1. La IA escribe dos respuestas diferentes a la misma pregunta +2. Un humano elige cuál respuesta es mejor +3. La IA aprende: "Ok, debería escribir más como la Respuesta A" +4. Esto sucede millones de veces + +Por eso la IA: +- Es educada y amigable +- Admite cuando no sabe algo +- Intenta ver diferentes lados de un tema +- Evita declaraciones controversiales + + +Conocer estos tres pasos te ayuda a entender el comportamiento de la IA. Cuando la IA rechaza una solicitud, es el ajuste fino. Cuando la IA es extra educada, es RLHF. Cuando la IA sabe hechos aleatorios, es el pre-entrenamiento. + + +## Lo Que Esto Significa para Tus Prompts + +Ahora que entiendes cómo funciona la IA, aquí está cómo usar ese conocimiento: + +### 1. Sé Claro y Específico + +La IA predice lo que viene después basándose en tus palabras. Prompts vagos llevan a respuestas vagas. Prompts específicos obtienen resultados específicos. + + + + + +### 2. Da Contexto + +La IA no sabe nada sobre ti a menos que se lo digas. Cada conversación comienza desde cero. Incluye la información de fondo que la IA necesita. + + + + + +### 3. Trabaja Con la IA, No Contra Ella + +Recuerda: la IA fue entrenada para ser útil. Pide cosas de la manera en que le pedirías a un amigo servicial. + + + +### 4. Siempre Verifica lo Importante + +La IA suena segura incluso cuando está equivocada. Para cualquier cosa importante, verifica la información tú mismo. + + + +### 5. Pon lo Importante Primero + +Si tu prompt es muy largo, pon las instrucciones más importantes al principio. La IA presta más atención a lo que viene primero. + +## Elegir la IA Correcta + +Diferentes modelos de IA son buenos para diferentes cosas: + +
+
+ Preguntas rápidas + Modelos más rápidos como GPT-4o o Claude 3.5 Sonnet +
+
+ Problemas difíciles + Modelos más inteligentes como GPT-5.2 o Claude 4.5 Opus +
+
+ Escribir código + Modelos enfocados en código o los modelos generales más inteligentes +
+
+ Documentos largos + Modelos con grandes ventanas de contexto (Claude, Gemini) +
+
+ Eventos actuales + Modelos con acceso a internet +
+
+ +## Resumen + +Los modelos de lenguaje de IA son máquinas de predicción entrenadas con texto. Son increíbles en muchas cosas, pero tienen límites reales. La mejor manera de usar la IA es entender cómo funciona y escribir prompts que aprovechen sus fortalezas. + + + + + +En el próximo capítulo, aprenderemos qué hace un buen prompt y cómo escribir prompts que obtengan excelentes resultados. diff --git a/src/content/book/es/02-anatomy-of-effective-prompt.mdx b/src/content/book/es/02-anatomy-of-effective-prompt.mdx new file mode 100644 index 00000000..e002552a --- /dev/null +++ b/src/content/book/es/02-anatomy-of-effective-prompt.mdx @@ -0,0 +1,343 @@ +Todo gran prompt comparte elementos estructurales comunes. Entender estos componentes te permite construir prompts sistemáticamente en lugar de a través de prueba y error. + + +Piensa en estos componentes como bloques LEGO. No necesitas todos para cada prompt, pero saber qué hay disponible te ayuda a construir exactamente lo que necesitas. + + +## Los Componentes Principales + +Un prompt efectivo típicamente incluye algunos o todos estos elementos: + + + +Examinemos cada componente en detalle. + +## 1. Rol / Persona + +Establecer un rol enfoca las respuestas del modelo a través del lente de una experiencia o perspectiva específica. + + + +El rol prepara al modelo para: +- Usar vocabulario apropiado +- Aplicar experiencia relevante +- Mantener una perspectiva consistente +- Considerar la audiencia apropiadamente + +### Patrones de Rol Efectivos + +``` +"Eres un [profesión] con [X años] de experiencia en [especialidad]" +"Actúa como un [rol] que es [característica]" +"Eres un experto en [campo] ayudando a un [tipo de audiencia]" +``` + +## 2. Contexto / Antecedentes + +El contexto proporciona la información que el modelo necesita para entender tu situación. Recuerda: el modelo no sabe nada sobre ti, tu proyecto o tus objetivos a menos que se lo digas. + + + +### Qué Incluir en el Contexto + +- **Detalles del proyecto** — Stack tecnológico, arquitectura, restricciones +- **Estado actual** — Qué has intentado, qué funciona, qué no +- **Objetivos** — Qué estás tratando de lograr finalmente +- **Restricciones** — Límites de tiempo, requisitos técnicos, guías de estilo + +## 3. Tarea / Instrucción + +La tarea es el corazón de tu prompt—lo que quieres que el modelo haga. Sé específico y sin ambigüedades. + +### El Espectro de Especificidad + + + +### Verbos de Acción Que Funcionan Bien + +
+
+ Creación + Escribe, Crea, Genera, Compone, Diseña +
+
+ Análisis + Analiza, Evalúa, Compara, Valora, Revisa +
+
+ Transformación + Convierte, Traduce, Reformatea, Resume, Expande +
+
+ Explicación + Explica, Describe, Aclara, Define, Ilustra +
+
+ Solución de problemas + Resuelve, Depura, Arregla, Optimiza, Mejora +
+
+ +## 4. Restricciones / Reglas + +Las restricciones limitan la salida del modelo. Previenen problemas comunes y aseguran relevancia. + +### Tipos de Restricciones + +**Restricciones de longitud:** +``` +"Mantén tu respuesta bajo 200 palabras" +"Proporciona exactamente 5 sugerencias" +"Escribe 3-4 párrafos" +``` + +**Restricciones de contenido:** +``` +"No incluyas ejemplos de código" +"Enfócate solo en los aspectos técnicos" +"Evita lenguaje de marketing" +``` + +**Restricciones de estilo:** +``` +"Usa un tono formal y académico" +"Escribe como si hablaras con un niño de 10 años" +"Sé directo y evita lenguaje evasivo" +``` + +**Restricciones de alcance:** +``` +"Solo considera opciones disponibles en Python 3.10+" +"Limita las sugerencias a herramientas gratuitas" +"Enfócate en soluciones que no requieran dependencias adicionales" +``` + +## 5. Formato de Salida + +Especificar el formato de salida asegura que obtengas respuestas en una estructura utilizable. + +### Formatos Comunes + +**Listas:** +``` +"Devuelve como una lista con viñetas" +"Proporciona una lista numerada de pasos" +``` + +**Datos estructurados:** +``` +"Devuelve como JSON con claves: título, descripción, prioridad" +"Formatea como una tabla markdown con columnas: Característica, Pros, Contras" +``` + +**Estructuras específicas:** +``` +"Estructura tu respuesta como: + ## Resumen + ## Puntos Clave + ## Recomendaciones" +``` + +### Ejemplo de Salida JSON + +``` +Analiza esta reseña de cliente y devuelve JSON: +{ + "sentimiento": "positivo" | "negativo" | "neutral", + "temas": ["array de temas principales"], + "prediccion_calificacion": 1-5, + "frases_clave": ["frases notables"] +} + +Reseña: "El producto llegó rápido y funciona muy bien, pero +las instrucciones eran confusas." +``` + +## 6. Ejemplos (Aprendizaje de Pocos Ejemplos) + +Los ejemplos son la forma más poderosa de mostrar al modelo exactamente lo que quieres. + +### Ejemplo de Un Solo Tiro + +``` +Convierte estas oraciones a tiempo pasado. + +Ejemplo: +Entrada: "Ella camina a la tienda" +Salida: "Ella caminó a la tienda" + +Ahora convierte: +Entrada: "Ellos corren cada mañana" +``` + +### Ejemplo de Pocos Tiros + +``` +Clasifica estos tickets de soporte por urgencia. + +Ejemplos: +"Mi cuenta fue hackeada" → Crítico +"¿Cómo cambio mi contraseña?" → Bajo +"El pago falló pero me cobraron" → Alto + +Clasifica: "La app se cierra cuando abro configuración" +``` + +## Juntándolo Todo + +Aquí hay un prompt completo usando todos los componentes: + + + +## El Prompt Mínimo Efectivo + +No todo prompt necesita todos los componentes. Para tareas simples, una instrucción clara puede ser suficiente: + +``` +Traduce "Hello, how are you?" al español. +``` + +Usa componentes adicionales cuando: +- La tarea es compleja o ambigua +- Necesitas formato específico +- Los resultados no coinciden con las expectativas +- La consistencia entre múltiples consultas importa + +## Patrones Comunes de Prompts + +Estos frameworks te dan una lista de verificación simple a seguir cuando escribes prompts. Haz clic en cada paso para ver un ejemplo. + + + + + +## Resumen + +Los prompts efectivos se construyen, no se descubren. Al entender y aplicar estos componentes estructurales, puedes: + +- Obtener mejores resultados en el primer intento +- Depurar prompts que no funcionan +- Crear plantillas de prompts reutilizables +- Comunicar tus intenciones claramente + + + + + +## Construye Tu Propio Prompt + +¡Ahora es tu turno! Usa este constructor de prompts interactivo para construir tu propio prompt usando los componentes que has aprendido: + + + + + +En el próximo capítulo, exploraremos los principios fundamentales que guían las decisiones de construcción de prompts. diff --git a/src/content/book/es/03-core-prompting-principles.mdx b/src/content/book/es/03-core-prompting-principles.mdx new file mode 100644 index 00000000..e8b92315 --- /dev/null +++ b/src/content/book/es/03-core-prompting-principles.mdx @@ -0,0 +1,373 @@ +Más allá de la estructura, la ingeniería de prompts efectiva está guiada por principios—verdades fundamentales que aplican a través de modelos, tareas y contextos. Domina estos principios, y podrás adaptarte a cualquier desafío de prompting. + + +Estos principios aplican a cada modelo de IA y cada tarea. Apréndelos una vez, úsalos en todas partes. + + +## Principio 1: Claridad Sobre Ingenio + +Los mejores prompts son claros, no ingeniosos. Los modelos de IA son intérpretes literales—trabajan con exactamente lo que les das. + +### Sé Explícito + + + +### Evita la Ambigüedad + +Las palabras pueden tener múltiples significados. Elige lenguaje preciso. + + + +### Declara lo Obvio + +Lo que es obvio para ti no es obvio para el modelo. Explica las suposiciones. + +``` +Me ayudas a escribir una carta de presentación. + +Contexto importante: +- Estoy aplicando para un puesto de Ingeniero de Software en Google +- Tengo 5 años de experiencia en Python y sistemas distribuidos +- El rol requiere experiencia de liderazgo (he liderado un equipo de 4) +- Quiero enfatizar mis contribuciones a código abierto +``` + +## Principio 2: La Especificidad Produce Calidad + +Entradas vagas producen salidas vagas. Entradas específicas producen salidas específicas y útiles. + +### La Escalera de Especificidad + + + +Cada nivel agrega especificidad y mejora dramáticamente la calidad del resultado. + +### Especifica Estos Elementos + +
+
+ Audiencia + ¿Quién leerá/usará esto? +
+
+ Longitud + ¿Qué tan largo/corto debe ser? +
+
+ Tono + ¿Formal? ¿Casual? ¿Técnico? +
+
+ Formato + ¿Prosa? ¿Lista? ¿Tabla? ¿Código? +
+
+ Alcance + ¿Qué incluir/excluir? +
+
+ Propósito + ¿Qué debe lograr esto? +
+
+ +## Principio 3: El Contexto Es Rey + +Los modelos no tienen memoria, ni acceso a tus archivos, ni conocimiento de tu situación. Todo lo relevante debe estar en el prompt. + +### Proporciona Contexto Suficiente + + + +### La Lista de Verificación de Contexto + + +Pregúntate: ¿Entendería un extraño inteligente esta solicitud? Si no, agrega más contexto. + + + + +## Principio 4: Guía, No Solo Preguntes + +No solo pidas una respuesta—guía al modelo hacia la respuesta que quieres. + +### Usa Encuadre Instruccional + + + +### Proporciona Andamios de Razonamiento + +Para tareas complejas, guía el proceso de razonamiento: + + + +## Principio 5: Itera y Refina + +La ingeniería de prompts es un proceso iterativo. Tu primer prompt rara vez es el mejor. + +### El Ciclo de Iteración + +``` +1. Escribe el prompt inicial +2. Revisa la salida +3. Identifica brechas o problemas +4. Refina el prompt +5. Repite hasta estar satisfecho +``` + +### Refinamientos Comunes + +
+
+ Muy verboso + Agrega "Sé conciso" o límites de longitud +
+
+ Muy vago + Agrega ejemplos específicos o restricciones +
+
+ Formato incorrecto + Especifica la estructura de salida exacta +
+
+ Aspectos faltantes + Agrega "Asegúrate de incluir..." +
+
+ Tono incorrecto + Especifica audiencia y estilo +
+
+ Inexacto + Solicita citas o razonamiento paso a paso +
+
+ +### Mantén un Diario de Prompts + +Documenta lo que funciona: +``` +Tarea: Revisión de código +Versión 1: "Revisa este código" → Muy genérico +Versión 2: Agregados criterios de revisión específicos → Mejor +Versión 3: Agregado ejemplo de buena revisión → Excelente +Final: [Guardar prompt exitoso como plantilla] +``` + +## Principio 6: Aprovecha las Fortalezas del Modelo + +Trabaja con cómo están entrenados los modelos, no en su contra. + +### Los Modelos Quieren Ser Útiles + +Enmarca las solicitudes como cosas que un asistente útil haría naturalmente: + + + +### Los Modelos Sobresalen en Patrones + +Si necesitas salida consistente, muestra el patrón: + + + +### Los Modelos Pueden Hacer Juego de Roles + +Usa personas para acceder a diferentes "modos" de respuesta: + +``` +Como abogado del diablo, argumenta en contra de mi propuesta... +Como mentor de apoyo, ayúdame a mejorar... +Como inversor escéptico, cuestiona este plan de negocios... +``` + +## Principio 7: Controla la Estructura de Salida + +Las salidas estructuradas son más útiles que el texto de forma libre. + +### Solicita Formatos Específicos + +``` +Devuelve tu análisis como: + +RESUMEN: [1 oración] + +HALLAZGOS CLAVE: +• [Hallazgo 1] +• [Hallazgo 2] +• [Hallazgo 3] + +RECOMENDACIÓN: [1-2 oraciones] + +CONFIANZA: [Baja/Media/Alta] porque [razón] +``` + +### Usa Delimitadores + +Separa claramente las secciones de tu prompt: + +``` +### CONTEXTO ### +[Tu contexto aquí] + +### TAREA ### +[Tu tarea aquí] + +### FORMATO ### +[Formato deseado aquí] +``` + +### Solicita Salida Legible por Máquina + +Para uso programático: + +``` +Devuelve solo JSON válido, sin explicación: +{ + "decision": "aprobar" | "rechazar" | "revisar", + "confianza": 0.0-1.0, + "razones": ["array de strings"] +} +``` + +## Principio 8: Verifica y Valida + +Nunca confíes ciegamente en las salidas del modelo, especialmente para tareas importantes. + +### Pide Razonamiento + +``` +Resuelve este problema y muestra tu trabajo paso a paso. +Después de resolver, verifica tu respuesta mediante [método de verificación]. +``` + +### Solicita Múltiples Perspectivas + +``` +Dame tres enfoques diferentes para resolver este problema. +Para cada uno, explica las compensaciones. +``` + +### Incorpora Auto-Verificación + +``` +Después de generar el código, revísalo para: +- Errores de sintaxis +- Casos límite +- Vulnerabilidades de seguridad +Lista cualquier problema encontrado. +``` + +## Resumen: Los Principios de un Vistazo + + + + + +## Práctica: Completa los Espacios en Blanco + +Prueba tu comprensión de los principios fundamentales completando esta plantilla de prompt: + + + + + +Estos principios forman la base para todo lo que sigue. En la Parte II, los aplicaremos a técnicas específicas que mejoran dramáticamente la efectividad de los prompts. diff --git a/src/content/book/es/04-role-based-prompting.mdx b/src/content/book/es/04-role-based-prompting.mdx new file mode 100644 index 00000000..03eaafd7 --- /dev/null +++ b/src/content/book/es/04-role-based-prompting.mdx @@ -0,0 +1,328 @@ +El prompting basado en roles es una de las técnicas más poderosas y ampliamente utilizadas en la ingeniería de prompts. Al asignar un rol o persona específica a la IA, puedes influir dramáticamente en la calidad, estilo y relevancia de las respuestas. + + +Piensa en los roles como filtros para el vasto conocimiento de la IA. El rol correcto enfoca las respuestas como un lente enfoca la luz. + + +## Por Qué Funcionan los Roles + +Cuando asignas un rol, esencialmente le estás diciendo al modelo: "Filtra tu vasto conocimiento a través de este lente específico." El modelo ajusta su: + +- **Vocabulario**: Usando terminología apropiada para el rol +- **Perspectiva**: Considerando problemas desde ese punto de vista +- **Profundidad de experiencia**: Proporcionando niveles de detalle apropiados al rol +- **Estilo de comunicación**: Coincidiendo con cómo comunicaría ese rol + +### La Explicación Técnica + +Los LLMs funcionan prediciendo el próximo token más probable basándose en el contexto que se les da. Cuando especificas un rol, estás cambiando fundamentalmente lo que significa "probable". + +**Activando Conocimiento Relevante**: El rol prepara regiones específicas de las asociaciones aprendidas del modelo. Decir "Eres un médico" activa terminología médica, patrones de razonamiento diagnóstico y estilos de comunicación clínica de los datos de entrenamiento. + +**Condicionamiento Estadístico**: Los LLMs aprendieron de millones de documentos escritos por expertos reales. Cuando asignas un rol, el modelo condiciona sus distribuciones de probabilidad para coincidir con patrones que vio de ese tipo de autor. + +**Reduciendo Ambigüedad**: Sin un rol, el modelo promedia entre todos los posibles respondedores. Con un rol, se estrecha a un subconjunto específico, haciendo las respuestas más enfocadas y consistentes. + +**Anclaje de Contexto**: El rol crea un ancla de contexto persistente a lo largo de la conversación. Cada respuesta subsiguiente está influenciada por este encuadre inicial. + +Piénsalo así: si preguntas "¿Qué debería hacer con esta tos?" el modelo podría responder como un médico, un amigo, un farmacéutico o un padre preocupado. Cada uno daría consejos diferentes. Al especificar el rol de antemano, le estás diciendo al modelo qué "voz" usar de sus datos de entrenamiento. + + +El modelo no está pretendiendo o haciendo juego de roles en un sentido teatral. Está sesgando estadísticamente sus salidas hacia patrones que aprendió de expertos, profesionales y especialistas reales durante el entrenamiento. Un rol de "médico" activa vías de conocimiento médico; un rol de "poeta" activa patrones literarios. + + +## Patrones Básicos de Roles + +Estos patrones fundamentales funcionan en la mayoría de los casos de uso. Comienza con estas plantillas y personalízalas para tus necesidades. + +### El Patrón de Experto + +El patrón más versátil. Especifica el campo de experiencia y años de experiencia para obtener respuestas autorizadas y profundas. Funciona bien para preguntas técnicas, análisis y consejos profesionales. + + + +### El Patrón Profesional + +Ancla el rol en un contexto del mundo real especificando un título de trabajo y tipo de organización. Esto agrega conocimiento institucional y normas profesionales a la respuesta. + + + +### El Patrón de Maestro + +Perfecto para aprendizaje y explicaciones. Especificar el nivel de audiencia asegura que la respuesta coincida con el trasfondo del aprendiz, desde principiantes hasta practicantes avanzados. + + + +## Construcciones Avanzadas de Roles + +### Roles Compuestos + +Combina múltiples identidades para obtener respuestas que mezclen diferentes perspectivas. Esta combinación pediatra-padre produce consejos que son tanto médicamente sólidos como prácticamente probados. + + + +### Roles Situacionales + +Coloca el rol en un escenario específico para moldear tanto el contenido como el tono. Aquí, el contexto de revisión de código hace que la IA sea constructiva y educativa en lugar de solo crítica. + + + +### Roles de Perspectiva + +Obtén retroalimentación desde el punto de vista de un stakeholder específico. Una perspectiva de VC evalúa viabilidad y escalabilidad de manera diferente a como lo haría un cliente o ingeniero. + + + +## Categorías de Roles y Ejemplos + +Diferentes dominios se benefician de diferentes tipos de roles. Aquí hay ejemplos probados organizados por categoría que puedes adaptar para tus tareas. + +### Roles Técnicos + +**Arquitecto de Software**: Mejor para decisiones de diseño de sistemas, elecciones de tecnología y compensaciones arquitectónicas. El enfoque en mantenibilidad dirige las respuestas hacia soluciones prácticas a largo plazo. + + + +**Especialista en Seguridad**: La mentalidad de atacante es clave aquí. Este rol produce análisis enfocado en amenazas que identifica vulnerabilidades que una perspectiva solo defensiva podría pasar por alto. + + + +**Ingeniero DevOps**: Ideal para preguntas de despliegue, automatización e infraestructura. El énfasis en confiabilidad asegura recomendaciones listas para producción. + + + +### Roles Creativos + +**Redactor Publicitario**: El calificador "premiado" y el enfoque en conversión producen textos contundentes y persuasivos en lugar de texto de marketing genérico. + + + +**Guionista**: Activa conocimiento de estructura dramática, ritmo y convenciones de diálogo. Excelente para cualquier escritura narrativa que necesite tensión y voz de personajes. + + + +**Escritor de UX**: Un rol especializado para texto de interfaz. El enfoque en brevedad y guía al usuario produce textos concisos y orientados a la acción. + + + +### Roles Analíticos + +**Analista de Negocios**: Conecta la brecha entre stakeholders técnicos y no técnicos. Útil para recopilación de requisitos, escritura de especificaciones e identificación de brechas en planes de proyecto. + + + +**Científico de Investigación**: El énfasis en evidencia y reconocimiento de incertidumbre produce respuestas equilibradas y bien fundamentadas que distinguen hechos de especulación. + + + +**Analista Financiero**: Combina análisis cuantitativo con evaluación de riesgos. El enfoque dual en rendimientos y riesgo produce perspectivas de inversión más equilibradas. + + + +### Roles Educativos + +**Tutor Socrático**: En lugar de dar respuestas, este rol hace preguntas guía. Excelente para aprendizaje profundo y ayudar a los estudiantes a desarrollar habilidades de pensamiento crítico. + + + +**Diseñador Instruccional**: Estructura el aprendizaje para máxima retención. Usa este rol cuando necesites desglosar temas complejos en fragmentos enseñables con progresión clara. + + + +## La Técnica de Apilamiento de Roles + +Para tareas complejas, combina múltiples aspectos de rol en una sola identidad en capas. Esta técnica apila experiencia, conciencia de audiencia y directrices de estilo para crear respuestas altamente especializadas. + +Este ejemplo superpone tres elementos: experiencia de dominio (documentación de API), audiencia (desarrolladores junior) y guía de estilo (convenciones de Google). Cada capa restringe la salida aún más. + + + +## Roles para Diferentes Tareas + +
+
+ Revisión de código + Desarrollador senior + mentor +
+
+ Retroalimentación de escritura + Editor + miembro de audiencia objetivo +
+
+ Estrategia de negocios + Consultor + experto de industria +
+
+ Aprender tema nuevo + Maestro paciente + practicante +
+
+ Escritura creativa + Autor de género específico +
+
+ Explicación técnica + Experto + comunicador +
+
+ Resolución de problemas + Especialista de dominio + generalista +
+
+ +## Anti-Patrones a Evitar + +### Roles Demasiado Genéricos + + + +### Roles Conflictivos + + + +### Experiencia Irreal + + + +## Ejemplos de Prompts del Mundo Real + +### Documentación Técnica + + + +### Escritura Creativa + + + +### Comunicación Empresarial + + + +## Combinando Roles con Otras Técnicas + +Los roles funcionan aún mejor cuando se combinan con otras técnicas de prompting: + +### Rol + Pocos Ejemplos + +Combina un rol con un ejemplo para mostrar exactamente cómo debería responder el rol. El ejemplo enseña tono y formato mientras el rol proporciona contexto y experiencia. + + + +### Rol + Cadena de Pensamiento + +El rol de detective naturalmente fomenta el razonamiento paso a paso. Combinar roles con cadena de pensamiento produce resolución de problemas más transparente y verificable. + + + +## Resumen + + +El prompting basado en roles es poderoso porque enfoca el vasto conocimiento del modelo, establece expectativas de tono y estilo, proporciona contexto implícito y hace las salidas más consistentes. + + + + +La clave es la **especificidad**: cuanto más detallado y realista sea el rol, mejores serán los resultados. En el próximo capítulo, exploraremos cómo obtener salidas consistentes y estructuradas de tus prompts. diff --git a/src/content/book/es/05-structured-output.mdx b/src/content/book/es/05-structured-output.mdx new file mode 100644 index 00000000..a6fca864 --- /dev/null +++ b/src/content/book/es/05-structured-output.mdx @@ -0,0 +1,411 @@ +Obtener salidas consistentes y bien formateadas es esencial para aplicaciones de producción y flujos de trabajo eficientes. Este capítulo cubre técnicas para controlar exactamente cómo los modelos de IA formatean sus respuestas. + + +La salida estructurada transforma las respuestas de IA de texto libre en datos accionables y parseables. + + +## Por Qué Importa la Estructura + + + +## Técnicas Básicas de Formateo + +### Listas + +Las listas son perfectas para instrucciones paso a paso, elementos clasificados o colecciones de puntos relacionados. Son fáciles de escanear y parsear. Usa **listas numeradas** cuando el orden importa (pasos, rankings) y **viñetas** para colecciones sin orden. + + + + +Especifica el número exacto de elementos que quieres, si incluir explicaciones, y si los elementos deben estar en negrita o tener una estructura específica. + + +### Tablas + +Las tablas sobresalen al comparar múltiples elementos a través de las mismas dimensiones. Son ideales para comparaciones de características, resúmenes de datos y cualquier información con atributos consistentes. Siempre define tus encabezados de columna explícitamente. + + + + +Especifica nombres de columnas, tipos de datos esperados (texto, números, calificaciones) y cuántas filas necesitas. Para comparaciones complejas, limita a 4-6 columnas para legibilidad. + + +### Encabezados y Secciones + +Los encabezados crean una estructura de documento clara, haciendo las respuestas largas escaneables y organizadas. Úsalos para informes, análisis o cualquier respuesta de múltiples partes. Los encabezados jerárquicos (##, ###) muestran relaciones entre secciones. + +``` +Analiza esta propuesta de negocio. + +Estructura tu respuesta con estas secciones: +## Resumen Ejecutivo +## Fortalezas +## Debilidades +## Recomendaciones +## Evaluación de Riesgos +``` + + +Lista tus secciones en el orden que las quieres. Para consistencia, especifica qué debe contener cada sección (ej., "Resumen Ejecutivo: solo 2-3 oraciones"). + + +### Énfasis con Directivas en Mayúsculas + +Las palabras en mayúsculas actúan como señales fuertes para el modelo, enfatizando restricciones o requisitos críticos. Úsalas con moderación para máximo impacto—el uso excesivo diluye su efectividad. + +**Directivas en Mayúsculas Comunes:** + + + +``` +Resume este artículo. + +IMPORTANTE: Mantén el resumen bajo 100 palabras. +NUNCA agregues información que no esté presente en el original. +SIEMPRE mantén el tono y perspectiva original. +NO incluyas tus propias opiniones o análisis. +``` + + +Si todo está en mayúsculas o marcado como crítico, nada destaca. Reserva estas directivas para restricciones genuinamente importantes. + + +## Salida JSON + +JSON (JavaScript Object Notation) es el formato más popular para salida estructurada de IA. Es legible por máquinas, ampliamente soportado por lenguajes de programación, y perfecto para APIs, bases de datos y flujos de trabajo de automatización. La clave para JSON confiable es proporcionar un esquema claro. + +### Solicitud JSON Básica + +Comienza con una plantilla mostrando la estructura exacta que quieres. Incluye nombres de campos, tipos de datos y valores de ejemplo. Esto actúa como un contrato que el modelo seguirá. + + + +### Estructuras JSON Complejas + +Para datos anidados, usa JSON jerárquico con objetos dentro de objetos, arrays de objetos y tipos mixtos. Define cada nivel claramente y usa anotaciones estilo TypeScript (`"positivo" | "negativo"`) para restringir valores. + +``` +Analiza esta reseña de producto y devuelve JSON: + +{ + "id_resena": "string (genera único)", + "sentimiento": { + "general": "positivo" | "negativo" | "mixto" | "neutral", + "puntuacion": 0.0-1.0 + }, + "aspectos": [ + { + "aspecto": "string (ej., 'precio', 'calidad')", + "sentimiento": "positivo" | "negativo" | "neutral", + "menciones": ["citas exactas de la reseña"] + } + ], + "intencion_compra": { + "recomendaria": boolean, + "confianza": 0.0-1.0 + }, + "frases_clave": ["array de strings de frases notables"] +} + +Devuelve SOLO JSON válido, sin texto adicional. + +Reseña: "[texto de reseña]" +``` + +### Asegurando JSON Válido + +Los modelos a veces agregan texto explicativo o formato markdown alrededor del JSON. Previene esto con instrucciones explícitas sobre el formato de salida. Puedes solicitar JSON crudo o JSON dentro de bloques de código—elige según tus necesidades de parsing. + +Agrega instrucciones explícitas: + +``` +IMPORTANTE: +- Devuelve SOLO el objeto JSON, sin bloques de código markdown +- Asegura que todos los strings estén correctamente escapados +- Usa null para valores faltantes, no undefined +- Valida que la salida sea JSON parseable +``` + +O solicita bloques de código pidiendo al modelo que envuelva su salida: + +```` +Devuelve el resultado como un bloque de código JSON: +```json +{ ... } +``` +```` + +## Salida YAML + +YAML es más legible para humanos que JSON, usando indentación en lugar de corchetes. Es el estándar para archivos de configuración (Docker, Kubernetes, GitHub Actions) y funciona bien cuando la salida será leída por humanos o usada en contextos DevOps. YAML es sensible a la indentación, así que sé específico sobre los requisitos de formato. + + + +## Salida XML + +XML todavía es requerido para muchos sistemas empresariales, APIs SOAP e integraciones legacy. Es más verboso que JSON pero ofrece características como atributos, namespaces y secciones CDATA para datos complejos. Especifica nombres de elementos, estructura de anidación, y dónde usar atributos vs. elementos hijos. + +``` +Convierte estos datos a formato XML: + +Requisitos: +- Elemento raíz: +- Cada elemento en elemento +- Incluye atributos donde sea apropiado +- Usa CDATA para texto de descripción + +Datos: [datos de libro] +``` + +## Formatos Personalizados + +A veces los formatos estándar no se ajustan a tus necesidades. Puedes definir cualquier formato personalizado proporcionando una plantilla clara. Los formatos personalizados funcionan bien para informes, logs, o salidas específicas de dominio que serán leídas por humanos. + +### Formato de Análisis Estructurado + +Usa delimitadores (===, ---, [SECCIÓN]) para crear documentos escaneables con límites claros entre secciones. Este formato es excelente para revisiones de código, auditorías y análisis. + +``` +Analiza este código usando este formato exacto: + +=== ANÁLISIS DE CÓDIGO === + +[RESUMEN] +Un párrafo de resumen + +[PROBLEMAS] +• CRÍTICO: [problema] — [archivo:línea] +• ADVERTENCIA: [problema] — [archivo:línea] +• INFO: [problema] — [archivo:línea] + +[MÉTRICAS] +Complejidad: [Baja/Media/Alta] +Mantenibilidad: [puntuación]/10 +Cobertura de Tests: [% estimado] + +[RECOMENDACIONES] +1. [Recomendación prioridad 1] +2. [Recomendación prioridad 2] + +=== FIN ANÁLISIS === +``` + +### Formato de Completar Espacios en Blanco + +Las plantillas con espacios en blanco (___) guían al modelo a llenar campos específicos mientras mantienen el formato exacto. Este enfoque es excelente para formularios, briefs y documentos estandarizados donde la consistencia importa. + +``` +Completa esta plantilla para el producto dado: + +BRIEF DE PRODUCTO +───────────── +Nombre: _______________ +Eslogan: _______________ +Usuario Objetivo: _______________ +Problema que Resuelve: _______________ +Características Clave: + 1. _______________ + 2. _______________ + 3. _______________ +Diferenciador: _______________ + +Producto: [descripción del producto] +``` + +## Respuestas Tipadas + +Las respuestas tipadas definen categorías o tipos de entidad que el modelo debe reconocer y etiquetar. Esta técnica es esencial para el Reconocimiento de Entidades Nombradas (NER), tareas de clasificación, y cualquier extracción donde necesites categorizar información consistentemente. Define tus tipos claramente con ejemplos. + + + +## Respuestas Estructuradas de Múltiples Partes + +Cuando necesitas salida comprensiva cubriendo múltiples aspectos, define partes distintas con límites claros. Especifica exactamente qué va en cada parte—formato, longitud y tipo de contenido. Esto previene que el modelo mezcle secciones u omita partes. + +``` +Investiga este tema y proporciona: + +### PARTE 1: RESUMEN EJECUTIVO +[Resumen de 2-3 oraciones] + +### PARTE 2: HALLAZGOS CLAVE +[Exactamente 5 viñetas] + +### PARTE 3: TABLA DE DATOS +| Métrica | Valor | Fuente | +|---------|-------|--------| +[Incluye 5 filas mínimo] + +### PARTE 4: RECOMENDACIONES +[Lista numerada de 3 recomendaciones accionables] + +### PARTE 5: LECTURA ADICIONAL +[3 recursos sugeridos con breves descripciones] +``` + +## Formato Condicional + +El formato condicional te permite definir diferentes formatos de salida basados en las características de la entrada. Esto es poderoso para clasificación, triaje y sistemas de enrutamiento donde el formato de respuesta debe variar según lo que detecte el modelo. Usa lógica si/entonces clara con plantillas de salida explícitas para cada caso. + + + +## Arrays y Listas en JSON + +Extraer múltiples elementos en arrays requiere definición cuidadosa del esquema. Especifica la estructura del array, qué debe contener cada elemento, y cómo manejar casos límite (arrays vacíos, elementos únicos). Incluir un campo de conteo ayuda a verificar completitud. + +``` +Extrae todos los elementos de acción de esta transcripción de reunión. + +Devuelve como array JSON: +{ + "elementos_accion": [ + { + "tarea": "string describiendo la tarea", + "asignado": "nombre de persona o 'Sin asignar'", + "fecha_limite": "fecha si se menciona, sino null", + "prioridad": "alta" | "media" | "baja", + "contexto": "cita relevante de la transcripción" + } + ], + "conteo_total": number +} + +Transcripción: "[transcripción de reunión]" +``` + +## Instrucciones de Validación + +La auto-validación hace que el modelo verifique su propia salida antes de responder. Esto captura problemas comunes como secciones faltantes, texto de marcador de posición, o violaciones de restricciones. El modelo iterará internamente para arreglar problemas, mejorando la calidad de salida sin llamadas API adicionales. + +``` +Genera el informe, luego: + +LISTA DE VERIFICACIÓN DE VALIDACIÓN: +□ Todas las secciones requeridas presentes +□ Sin texto de marcador de posición restante +□ Todas las estadísticas incluyen fuentes +□ Conteo de palabras dentro de 500-700 palabras +□ Conclusión conecta con la introducción + +Si alguna verificación falla, arregla antes de responder. +``` + +## Manejo de Campos Opcionales + +Los datos del mundo real a menudo tienen valores faltantes. Instruye explícitamente al modelo sobre cómo manejar campos opcionales—usar `null` es más limpio que strings vacíos y más fácil de procesar programáticamente. También previene "alucinaciones" de datos faltantes enfatizando que el modelo nunca debe inventar información. + +``` +Extrae información de contacto. Usa null para campos faltantes. + +{ + "nombre": "string (requerido)", + "email": "string o null", + "telefono": "string o null", + "empresa": "string o null", + "rol": "string o null", + "linkedin": "string URL o null" +} + +IMPORTANTE: +- Nunca inventes información que no esté en la fuente +- Usa null, no strings vacíos, para datos faltantes +- Números de teléfono en formato E.164 si es posible +``` + +## Resumen + + +Sé explícito sobre el formato, usa ejemplos, especifica tipos, maneja casos límite con valores null, y pide al modelo que valide su propia salida. + + + + +Las salidas estructuradas son esenciales para construir aplicaciones confiables impulsadas por IA. En el próximo capítulo, exploraremos el prompting de cadena de pensamiento para tareas de razonamiento complejas. diff --git a/src/content/book/es/06-chain-of-thought.mdx b/src/content/book/es/06-chain-of-thought.mdx new file mode 100644 index 00000000..48766767 --- /dev/null +++ b/src/content/book/es/06-chain-of-thought.mdx @@ -0,0 +1,363 @@ +El prompting de Cadena de Pensamiento (CoT) es una técnica que mejora dramáticamente el rendimiento de la IA en tareas de razonamiento complejo al pedir al modelo que muestre su trabajo paso a paso. + + +Al igual que un maestro de matemáticas pidiendo a los estudiantes que muestren su trabajo, el prompting CoT pide a la IA que haga visible su razonamiento. + + +## El Problema que Resuelve CoT + +Los modelos de IA pueden tener dificultades con el razonamiento de múltiples pasos cuando se les pide saltar directamente a una respuesta. + + + +## Prompts CoT Básicos + +### Frases Disparadoras Simples + +Agrega una de estas a tus prompts: + +
+
"Pensemos paso a paso."
+
"Piensa esto cuidadosamente."
+
"Trabaja este problema metódicamente."
+
"Muestra tu razonamiento en cada paso."
+
"Explica tu proceso de pensamiento."
+
+ +### Solicitud Explícita de Pasos + + + +## CoT de Cero Ejemplos vs Pocos Ejemplos + +Hay dos enfoques principales para el prompting de Cadena de Pensamiento, cada uno con diferentes compensaciones entre simplicidad y control. + +### CoT de Cero Ejemplos + +El enfoque más simple—solo agrega una frase disparadora y deja que el modelo descubra cómo razonar. No se necesitan ejemplos. Esto funciona sorprendentemente bien para muchos problemas, aunque tienes menos control sobre el formato del razonamiento. + + + +**Salida de Ejemplo:** +``` +Pensemos paso a paso. +- Juan comienza con 3 manzanas +- La mitad de 3 es 1.5, pero no podemos dividir manzanas +- Si redondeamos hacia abajo: Juan da 1 manzana, se queda con 2 +- Después de comprar 4 más: 2 + 4 = 6 manzanas + +Respuesta: 6 manzanas +``` + +### CoT de Pocos Ejemplos + +Para resultados más consistentes, muestra al modelo exactamente cómo quieres que razone proporcionando ejemplos trabajados. Esto te da control sobre el estilo de razonamiento, formato y nivel de detalle. El modelo imitará tu patrón demostrado. + + + +**Salida de Ejemplo:** +``` +R: Vamos a resolver esto: +- Precio regular: 3€, Cantidad: 12 +- Como 12 ≥ 10, aplica el descuento del 25% +- Total regular: 12 × 3€ = 36€ +- Descuento: 25% de 36€ = 9€ +- Precio final: 36€ - 9€ = 27€ +``` + +## Formatos Estructurados de CoT + +Para razonamiento consistente y reproducible, usa formatos estructurados con pasos nombrados. Estos frameworks aseguran que el modelo no se salte etapas importantes y hacen las salidas más fáciles de parsear y verificar. + +### El Formato BREAK + +Un acrónimo memorable que guía al modelo a través de un ciclo completo de resolución de problemas, desde la comprensión hasta la verificación. + + + +### La Plantilla de Razonamiento + +Una estructura más formal que separa entradas, objetivos y ejecución. Excelente para problemas técnicos donde necesitas documentación clara del proceso de solución. + + + +**Salida de Ejemplo:** +``` +DADO: 8L/100km, tanque 45L, 1,50€/L, conducir 300km +OBJETIVO: Calcular costo de combustible +ENFOQUE: Combustible necesario × costo por litro +PASOS: +1. Combustible = (300 ÷ 100) × 8 = 24 litros +2. Costo = 24 × 1,50€ = 36€ +VERIFICACIÓN: 24L < 45L tanque ✓ +RESPUESTA: 36€ +``` + +## CoT para Diferentes Tipos de Problemas + +Diferentes tipos de problemas se benefician de diferentes enfoques de CoT. Aquí hay patrones optimizados para escenarios comunes. + +### Razonamiento Matemático + +Los problemas matemáticos se benefician más de CoT porque cada paso se construye sobre el anterior. Los errores se acumulan, así que mostrar el trabajo ayuda a detectar errores temprano. El modelo debe etiquetar claramente cada cálculo. + + + +**Salida de Ejemplo:** +``` +Q1: 1.200.000€ (dado) +Q2: 1.200.000€ × 1,15 = 1.380.000€ +Q3: 1.380.000€ × 0,90 = 1.242.000€ +Q4: 1.242.000€ × 1,25 = 1.552.500€ + +Total: 5.374.500€ +``` + +### Razonamiento Lógico + +Los puzzles de lógica requieren eliminación sistemática y prueba de hipótesis. CoT ayuda al modelo a rastrear restricciones, probar posibilidades y verificar que todas las condiciones se satisfagan. La clave es exploración metódica en lugar de adivinar. + + + +**Salida de Ejemplo:** +``` +De la pista 3: Roberto = maestro +→ Alicia y Carolina son ingeniera/médica + +Si Carolina = ingeniera: +- Carolina tiene perro (pista 2) +- Alicia = médica, tiene pez (pista 1) +- Roberto tiene gato + +Verificar: Las 4 pistas satisfechas ✓ +Respuesta: Alicia (médica, pez), Roberto (maestro, gato), Carolina (ingeniera, perro) +``` + +### Depuración de Código + +La depuración se beneficia de CoT porque obliga al modelo a rastrear la ejecución en lugar de adivinar errores. Al caminar por el código con valores concretos, el comportamiento real se hace visible y las discrepancias con el comportamiento esperado se exponen. + + + +**Salida de Ejemplo:** +``` +Rastrea [2, 3, 4, 6]: +n=2: total += 1 → 1 (¡espera, sumando 1 no n!) +n=3: saltar (impar) +n=4: total = 2 +n=6: total = 3 + +ERROR: "total += 1" debería ser "total += n" +Esperado: 12, Obtenido: 3 +Corrección: Cambiar a "total += n" +``` + +## Auto-Consistencia con CoT + +Para problemas críticos, no te apoyes en una sola ruta de razonamiento. Genera múltiples soluciones independientes y compara resultados. Si diferentes enfoques convergen en la misma respuesta, la confianza es alta. El desacuerdo señala la necesidad de revisión cuidadosa. + + + +**Salida de Ejemplo:** +``` +Enfoque 1 (Álgebra): g + v = 30, 2g + 4v = 74 → g=23, v=7 +Enfoque 2 (Prueba): Probar 23/7 → 46 + 28 = 74 ✓ +Enfoque 3 (Lógica): 30 gallinas = 60 patas, necesitamos 14 más → 7 vacas + +Todos coinciden: 23 gallinas, 7 vacas +``` + +## CoT para Toma de Decisiones + +Las decisiones implican sopesar compensaciones a través de múltiples dimensiones. CoT asegura que todos los factores relevantes se consideren sistemáticamente en lugar de saltar a conclusiones. Este enfoque estructurado también documenta el razonamiento para referencia futura. + + + +**Salida de Ejemplo:** +``` +FACTORES: +- Tamaño de equipo (5): Muy pequeño para microservicios ❌ +- Escala (100 DAU): Sin necesidad de escalado ❌ +- Velocidad: Monolito = iteración más rápida ❌ +- Crecimiento futuro: Cronología incierta ⚠️ + +BALANCE: 3 fuertes en contra, 1 débil a favor + +RECOMENDACIÓN: Quedarse con monolito, usar límites de módulos +claros para facilitar transición futura. +``` + +## Cuándo Usar CoT + +
+
+

Usa CoT Para

+
+

**Problemas matemáticos** — Reduce errores de cálculo

+

**Puzzles de lógica** — Previene pasos saltados

+

**Análisis complejos** — Organiza el pensamiento

+

**Depuración de código** — Rastrea la ejecución

+

**Toma de decisiones** — Sopesa compensaciones

+
+
+
+

Omite CoT Para

+
+

**Preguntas y respuestas simples** — Overhead innecesario

+

**Escritura creativa** — Puede restringir la creatividad

+

**Búsquedas factuales** — No se necesita razonamiento

+

**Traducción** — Tarea directa

+

**Resumen** — Generalmente directo

+
+
+
+ +## Limitaciones de CoT + +Aunque poderosa, la Cadena de Pensamiento no es una solución mágica. Entender sus limitaciones te ayuda a aplicarla apropiadamente. + +1. **Mayor uso de tokens** — Más salida significa costos más altos +2. **No siempre necesaria** — Tareas simples no se benefician +3. **Puede ser verbosa** — Puede necesitar pedir concisión +4. **El razonamiento puede ser defectuoso** — CoT no garantiza corrección + +## Resumen + + +CoT mejora dramáticamente el razonamiento complejo al hacer explícitos los pasos implícitos. Úsalo para matemáticas, lógica, análisis y depuración. Compensación: mejor precisión por más tokens. + + + + +En el próximo capítulo, exploraremos el aprendizaje de pocos ejemplos—enseñando al modelo a través de ejemplos. diff --git a/src/content/book/es/07-few-shot-learning.mdx b/src/content/book/es/07-few-shot-learning.mdx new file mode 100644 index 00000000..727eaf60 --- /dev/null +++ b/src/content/book/es/07-few-shot-learning.mdx @@ -0,0 +1,478 @@ +El aprendizaje de pocos ejemplos es una de las técnicas de prompting más poderosas. Al proporcionar ejemplos de lo que quieres, puedes enseñar al modelo tareas complejas sin ningún ajuste fino. + + +Al igual que los humanos aprenden viendo ejemplos, los modelos de IA pueden aprender patrones de los ejemplos que proporcionas en tu prompt. + + +## ¿Qué es el Aprendizaje de Pocos Ejemplos? + +El aprendizaje de pocos ejemplos muestra al modelo ejemplos de pares entrada-salida antes de pedirle que realice la misma tarea. El modelo aprende el patrón de tus ejemplos y lo aplica a nuevas entradas. + + + +
+
+
0
+
Cero ejemplos
+
+
+
1
+
Un ejemplo
+
+
+
2-5
+
Pocos ejemplos
+
+
+
5+
+
Muchos ejemplos
+
+
+ +## Por Qué Funcionan los Ejemplos + + + +Los ejemplos comunican: +- **Formato**: Cómo debe estructurarse la salida +- **Estilo**: Tono, longitud, vocabulario +- **Lógica**: El patrón de razonamiento a seguir +- **Casos límite**: Cómo manejar situaciones especiales + +## Patrón Básico de Pocos Ejemplos + +La estructura fundamental del prompting de pocos ejemplos sigue un patrón simple: mostrar ejemplos, luego pedir la nueva tarea. La consistencia en el formateo entre ejemplos es crucial. El modelo aprende del patrón que estableces. + +``` +[Ejemplo 1] +Entrada: [entrada 1] +Salida: [salida 1] + +[Ejemplo 2] +Entrada: [entrada 2] +Salida: [salida 2] + +[Ejemplo 3] +Entrada: [entrada 3] +Salida: [salida 3] + +Ahora haz este: +Entrada: [nueva entrada] +Salida: +``` + +## Pocos Ejemplos para Clasificación + +La clasificación es uno de los casos de uso más fuertes para el aprendizaje de pocos ejemplos. Al mostrar ejemplos de cada categoría, defines los límites entre clases más precisamente de lo que las instrucciones solas podrían lograr. + +### Análisis de Sentimiento + + +El análisis de sentimiento clasifica texto por tono emocional: positivo, negativo, neutral o mixto. Se usa ampliamente para retroalimentación de clientes, monitoreo de redes sociales y seguimiento de percepción de marca. + + +La clasificación de sentimiento se beneficia de mostrar ejemplos de cada tipo de sentimiento, especialmente casos límite como sentimiento "mixto" que podría ser ambiguo. + + + +### Clasificación por Tema + +Para categorización de múltiples clases, incluye al menos un ejemplo por categoría. Esto ayuda al modelo a entender tu taxonomía específica, que puede diferir de su comprensión predeterminada. + + + +## Pocos Ejemplos para Transformación + +Las tareas de transformación convierten la entrada de una forma a otra mientras preservan el significado. Los ejemplos son esenciales aquí porque definen exactamente qué significa "transformación" para tu caso de uso. + +### Reescritura de Texto + +La transformación de estilo requiere ejemplos que muestren el cambio de tono exacto que quieres. Instrucciones abstractas como "hazlo profesional" se interpretan de manera diferente. Los ejemplos lo hacen concreto. + + + +### Conversión de Formato + +Las tareas de conversión de formato se benefician de ejemplos que muestran casos límite y entradas ambiguas. El modelo aprende tus convenciones específicas para manejar casos difíciles. + + + +## Pocos Ejemplos para Generación + +Las tareas de generación crean nuevo contenido siguiendo un patrón aprendido. Los ejemplos establecen longitud, estructura, tono y qué detalles resaltar. Estos son difíciles de especificar solo con instrucciones. + +### Descripciones de Productos + +El texto de marketing se beneficia enormemente de ejemplos porque capturan la voz de marca, énfasis en características y técnicas persuasivas que son difíciles de describir abstractamente. + + + +### Documentación de Código + + +La buena documentación explica qué hace el código, sus parámetros, valores de retorno y ejemplos de uso. Los docstrings consistentes permiten documentación de API auto-generada y ayudan a los IDEs a proporcionar mejor autocompletado de código. + + +El estilo de documentación varía ampliamente entre proyectos. Los ejemplos enseñan tu formato específico, qué incluir (args, returns, ejemplos) y el nivel de detalle esperado. + +>> calcular_imc(70, 1.75) + 22.86 +""" + +Ahora documenta: +Función: +def es_palindromo(texto): + limpio = ''.join(c.lower() for c in texto if c.isalnum()) + return limpio == limpio[::-1] + +Documentación:`} /> + +## Pocos Ejemplos para Extracción + +Las tareas de extracción extraen información estructurada de texto no estructurado. Los ejemplos definen qué entidades importan, cómo formatear la salida, y cómo manejar casos donde la información falta o es ambigua. + +### Extracción de Entidades + + +El Reconocimiento de Entidades Nombradas (NER) identifica y clasifica entidades nombradas en texto en categorías como personas, organizaciones, ubicaciones, fechas y productos. Es fundamental para recuperación de información y grafos de conocimiento. + + +NER se beneficia de ejemplos que muestran tus tipos de entidad específicos y cómo manejar entidades que podrían encajar en múltiples categorías. + + + +### Extracción de Datos Estructurados + +Extraer datos estructurados de lenguaje natural requiere ejemplos que muestren cómo manejar campos faltantes, información implícita y formatos de entrada variados. + + + +## Técnicas Avanzadas de Pocos Ejemplos + +Más allá de los pocos ejemplos básicos, varias técnicas pueden mejorar los resultados para tareas complejas. + +### Ejemplos Diversos + +La diversidad en los ejemplos es más valiosa que la cantidad. Cubre diferentes escenarios, casos límite y posibles ambigüedades en lugar de mostrar ejemplos similares repetidamente. + + + +### Ejemplos Negativos + + +Mostrar ejemplos "buenos" vs "malos" se llama aprendizaje contrastivo. Ayuda al modelo a entender no solo lo que quieres, sino lo que debe evitar. Esto es especialmente útil para juicios de estilo y calidad. + + +A veces mostrar lo que *no* hacer es tan valioso como mostrar ejemplos correctos. Los ejemplos negativos ayudan al modelo a entender límites y evitar errores comunes. + + + +### Ejemplos de Casos Límite + +Los casos límite a menudo determinan si una solución funciona en producción. Incluir entradas inusuales en tus ejemplos previene que el modelo falle con datos del mundo real que no encajan en el "camino feliz." + + + +## ¿Cuántos Ejemplos? + +
+
+ Clasificación simple + 2-3 + Uno por categoría mínimo +
+
+ Formateo complejo + 3-5 + Muestra variaciones +
+
+ Estilo matizado + 4-6 + Captura el rango completo +
+
+ Casos límite + 1-2 + Junto con ejemplos normales +
+
+ +## La Calidad de los Ejemplos Importa + + + +## Combinando Pocos Ejemplos con Otras Técnicas + +El aprendizaje de pocos ejemplos se combina poderosamente con otras técnicas de prompting. Los ejemplos proporcionan el "qué" mientras otras técnicas pueden agregar contexto, razonamiento o estructura. + +### Pocos Ejemplos + Rol + +Agregar un rol da al modelo contexto de *por qué* está haciendo la tarea, lo que puede mejorar calidad y consistencia. + +``` +Eres un revisor de contratos legales. + +[ejemplos de análisis de cláusulas de contrato] + +Ahora analiza: [nueva cláusula] +``` + +### Pocos Ejemplos + CoT + +Combinar pocos ejemplos con Cadena de Pensamiento muestra no solo *qué* respuesta dar, sino *cómo* razonar hasta esa respuesta. Esto es poderoso para tareas que requieren juicio. + +``` +Clasifica y explica el razonamiento. + +Reseña: "Grandes características pero muy caro" +Pensando: La reseña menciona aspectos positivos ("grandes características") +pero también un negativo significativo ("muy caro"). Lo negativo parece +superar lo positivo basándose en la conjunción "pero". +Clasificación: Mixto-Negativo + +[más ejemplos con razonamiento] + +Ahora clasifica con razonamiento: +Reseña: "Exactamente lo que necesitaba, llegó más rápido de lo esperado" +``` + +## Resumen + + +El aprendizaje de pocos ejemplos enseña a través de demostración y a menudo es más efectivo que las instrucciones solas. Usa 2-5 ejemplos diversos y correctos y combina con otras técnicas para mejores resultados. + + + + +En el próximo capítulo, exploraremos el refinamiento iterativo: el arte de mejorar prompts a través de intentos sucesivos. diff --git a/src/content/book/es/08-iterative-refinement.mdx b/src/content/book/es/08-iterative-refinement.mdx new file mode 100644 index 00000000..a08683c6 --- /dev/null +++ b/src/content/book/es/08-iterative-refinement.mdx @@ -0,0 +1,387 @@ +La ingeniería de prompts rara vez es un proceso de un solo intento. Los mejores prompts emergen a través de iteración—probando, observando y refinando hasta lograr los resultados deseados. + + +Piensa en tu primer prompt como un borrador. Incluso los ingenieros de prompts experimentados rara vez aciertan en el primer intento. + + +## El Ciclo de Iteración + +El refinamiento efectivo de prompts sigue un ciclo predecible: escribir, probar, analizar y mejorar. Cada iteración te acerca a un prompt que produce confiablemente los resultados que necesitas. + + + +## Patrones Comunes de Refinamiento + +La mayoría de los fallos de prompts caen en un puñado de categorías. Aprender a reconocer estos patrones te permite diagnosticar y arreglar problemas rápidamente sin empezar desde cero. + +### Problema: Salida Muy Larga + +Uno de los problemas más comunes. Sin restricciones explícitas, los modelos tienden a ser exhaustivos en lugar de concisos. + + + +### Problema: Salida Muy Vaga + +Prompts vagos producen salidas vagas. El modelo no puede leer tu mente sobre lo que significa "mejor" o qué aspectos te importan más. + + + +### Problema: Tono Incorrecto + +El tono es subjetivo y varía según el contexto. Lo que suena "profesional" para el modelo podría no coincidir con la voz de tu organización o la relación con tu destinatario. + + + +### Problema: Falta Información Clave + +Las solicitudes abiertas obtienen respuestas abiertas. Si necesitas tipos específicos de retroalimentación, debes pedirlos explícitamente. + + + +### Problema: Formato Inconsistente + +Sin una plantilla, el modelo estructurará cada respuesta de manera diferente, haciendo difícil la comparación e imposible la automatización. + + + +## Enfoque Sistemático de Refinamiento + +Los cambios aleatorios desperdician tiempo. Un enfoque sistemático te ayuda a identificar problemas rápidamente y arreglarlos eficientemente. + +### Paso 1: Diagnostica el Problema + +Antes de cambiar nada, identifica qué está realmente mal. Usa esta tabla diagnóstica para mapear síntomas a soluciones: + +
+
+ Síntoma + Causa Probable + Solución +
+
+ Muy largo + Sin restricción de longitud + Agregar límites de palabras/oraciones +
+
+ Muy corto + Falta solicitud de detalle + Pedir elaboración +
+
+ Fuera de tema + Instrucciones vagas + Ser más específico +
+
+ Formato incorrecto + Formato no especificado + Definir estructura exacta +
+
+ Tono incorrecto + Audiencia no clara + Especificar audiencia/estilo +
+
+ Inconsistente + Sin ejemplos proporcionados + Agregar ejemplos de pocos ejemplos +
+
+ +### Paso 2: Haz Cambios Dirigidos + +Resiste la urgencia de reescribir todo. Cambiar múltiples variables a la vez hace imposible saber qué ayudó y qué perjudicó. Haz un cambio, pruébalo, luego procede: + +``` +Iteración 1: Agregar restricción de longitud +Iteración 2: Especificar formato +Iteración 3: Agregar ejemplo +Iteración 4: Refinar instrucciones de tono +``` + +### Paso 3: Documenta Lo Que Funciona + +El conocimiento de ingeniería de prompts se pierde fácilmente. Mantén un registro de lo que probaste y por qué. Esto ahorra tiempo cuando revisitas el prompt después o enfrentas desafíos similares: + +```markdown +## Prompt: Respuesta de Email a Cliente + +### Versión 1 (muy formal) +"Escribe una respuesta a esta queja de cliente." + +### Versión 2 (mejor tono, aún falta estructura) +"Escribe una respuesta amigable pero profesional a esta queja. +Muestra empatía primero." + +### Versión 3 (final - buenos resultados) +"Escribe una respuesta a esta queja de cliente. Estructura: +1. Reconoce su frustración (1 oración) +2. Discúlpate específicamente (1 oración) +3. Explica la solución (2-3 oraciones) +4. Ofrece ayuda adicional (1 oración) + +Tono: Amigable, profesional, empático pero no servil." +``` + +## Ejemplo de Iteración del Mundo Real + +Caminemos a través de un ciclo de iteración completo para ver cómo cada refinamiento se construye sobre el anterior. Nota cómo cada versión aborda deficiencias específicas de la anterior. + +### Tarea: Generar Nombres de Producto + + + +## Estrategias de Refinamiento por Tipo de Tarea + +Diferentes tareas fallan de maneras predecibles. Conocer los modos de fallo comunes te ayuda a diagnosticar y arreglar problemas más rápido. + +### Para Generación de Contenido + +La generación de contenido a menudo produce salidas genéricas, fuera de objetivo o mal formateadas. La solución usualmente implica ser más específico sobre restricciones, proporcionar ejemplos concretos, o definir tu voz de marca explícitamente. + + + +### Para Generación de Código + +La salida de código puede fallar técnicamente (errores de sintaxis, características de lenguaje incorrectas) o arquitectónicamente (patrones pobres, casos faltantes). Los problemas técnicos necesitan especificaciones de versión/entorno; los problemas arquitectónicos necesitan guía de diseño. + + + +### Para Análisis + +Las tareas de análisis a menudo producen resultados superficiales o no estructurados. Guía al modelo con frameworks específicos (FODA, Cinco Fuerzas de Porter), solicita múltiples puntos de vista, o proporciona una plantilla para la estructura de salida. + + + +### Para Preguntas y Respuestas + +Las preguntas y respuestas pueden ser muy tersas o muy verbosas, y pueden carecer de indicadores de confianza o fuentes. Especifica el nivel de detalle que necesitas y si quieres citas o incertidumbre expresada. + + + +## La Técnica del Ciclo de Retroalimentación + +Aquí hay una meta-técnica: usa el modelo mismo para ayudar a mejorar tus prompts. Comparte lo que probaste, lo que obtuviste y lo que querías. El modelo a menudo puede sugerir mejoras que no habías considerado. + +``` +Usé este prompt: +"[tu prompt]" + +Y obtuve esta salida: +"[salida del modelo]" + +Quería algo más [describe la brecha]. ¿Cómo debería modificar +mi prompt para obtener mejores resultados? +``` + +## Pruebas A/B de Prompts + +Para prompts que se usarán repetidamente o a escala, no solo elijas el primero que funcione. Prueba variaciones para encontrar el enfoque más confiable y de mayor calidad. + +``` +Prompt A: "Resume este artículo en 3 viñetas." +Prompt B: "Extrae las 3 ideas más importantes de este artículo." +Prompt C: "¿Cuáles son los puntos clave de este artículo? Lista 3." +``` + +Ejecuta cada uno múltiples veces, compara: +- Consistencia de la salida +- Calidad de la información +- Relevancia para tus necesidades + +## Cuándo Dejar de Iterar + +La perfección es enemiga de lo suficientemente bueno. Sabe cuándo tu prompt está listo para usar y cuándo solo estás puliendo para rendimientos decrecientes. + +
+
+

Listo para Enviar

+
+

La salida cumple consistentemente los requisitos

+

Los casos límite se manejan apropiadamente

+

El formato es confiable y parseable

+

Mejoras adicionales muestran rendimientos decrecientes

+
+
+
+

Sigue Iterando

+
+

La salida es inconsistente entre ejecuciones

+

Los casos límite causan fallos

+

Se pierden requisitos críticos

+

No has probado suficientes variaciones

+
+
+
+ +## Control de Versiones para Prompts + +Los prompts son código. Para cualquier prompt usado en producción, trátalo con el mismo rigor: control de versiones, registros de cambios y la capacidad de revertir si algo se rompe. + + +prompts.chat incluye historial de versiones automático para tus prompts. Cada edición se guarda, así que puedes comparar versiones y restaurar iteraciones anteriores con un clic. + + +Para prompts autogestionados, usa una estructura de carpetas: + +``` +prompts/ +├── respuesta-cliente/ +│ ├── v1.0.txt # Versión inicial +│ ├── v1.1.txt # Arreglado problema de tono +│ ├── v2.0.txt # Reestructuración mayor +│ └── current.txt # Symlink a versión activa +└── changelog.md # Documentar cambios +``` + +## Resumen + + +Comienza simple, observa cuidadosamente, cambia una cosa a la vez, documenta lo que funciona, y sabe cuándo parar. Los mejores prompts no se escriben—se descubren a través de iteración sistemática. + + + + +## Práctica: Mejora Este Prompt + +Intenta mejorar este prompt débil tú mismo. Edítalo, luego usa IA para comparar tu versión con el original: + + + +En el próximo capítulo, exploraremos el prompting JSON y YAML para aplicaciones de datos estructurados. diff --git a/src/content/book/es/09-json-yaml-prompting.mdx b/src/content/book/es/09-json-yaml-prompting.mdx new file mode 100644 index 00000000..01a60854 --- /dev/null +++ b/src/content/book/es/09-json-yaml-prompting.mdx @@ -0,0 +1,586 @@ +Los formatos de datos estructurados como JSON y YAML son esenciales para construir aplicaciones que consumen salidas de IA programáticamente. Este capítulo cubre técnicas para generación confiable de salidas estructuradas. + + +JSON y YAML transforman las salidas de IA de texto libre en datos estructurados y con tipos seguros que el código puede consumir directamente. + + +## ¿Por Qué Formatos Estructurados? + + + +## Fundamentos de Prompting JSON + +JSON (JavaScript Object Notation) es el formato más común para salidas programáticas de IA. Su sintaxis estricta lo hace fácil de parsear, pero también significa que pequeños errores pueden romper todo tu pipeline. + +### Qué Hacer y Qué No: Solicitando JSON + + + +### Salida JSON Simple + +Comienza con un esquema mostrando la estructura esperada. El modelo llenará valores basándose en el texto de entrada. + +``` +Extrae la siguiente información como JSON: + +{ + "nombre": "string", + "edad": number, + "email": "string" +} + +Texto: "Contacta a Juan García, 34 años, en juan@example.com" +``` + +Salida: +```json +{ + "nombre": "Juan García", + "edad": 34, + "email": "juan@example.com" +} +``` + +### Estructuras JSON Anidadas + +Los datos del mundo real a menudo tienen relaciones anidadas. Define cada nivel de tu esquema claramente, especialmente para arrays de objetos. + +``` +Parsea este pedido en JSON: + +{ + "id_pedido": "string", + "cliente": { + "nombre": "string", + "email": "string" + }, + "items": [ + { + "producto": "string", + "cantidad": number, + "precio": number + } + ], + "total": number +} + +Pedido: "Pedido #12345 para María López (maria@email.com): 2x Widget (10€ cada uno), +1x Gadget (25€). Total: 45€" +``` + +### Asegurando JSON Válido + + +Los modelos a menudo envuelven JSON en bloques de código markdown o agregan texto explicativo. Sé explícito sobre querer solo JSON crudo. + + +Agrega instrucciones explícitas: + +``` +CRÍTICO: Devuelve SOLO JSON válido. Sin markdown, sin explicación, +sin texto adicional antes o después del objeto JSON. + +Si un campo no puede determinarse, usa null. +Asegura que todos los strings estén correctamente entrecomillados y escapados. +Los números no deben estar entrecomillados. +``` + +## Fundamentos de Prompting YAML + +YAML es más legible para humanos que JSON y soporta comentarios. Es el estándar para archivos de configuración, especialmente en DevOps (Docker, Kubernetes, GitHub Actions). + +### Salida YAML Simple + +YAML usa indentación en lugar de llaves. Proporciona una plantilla mostrando la estructura esperada. + +``` +Genera un archivo de configuración en formato YAML: + +server: + host: string + port: number + ssl: boolean +database: + type: string + connection_string: string + +Requisitos: Servidor de producción en puerto 443 con SSL, base de datos PostgreSQL +``` + +Salida: +```yaml +server: + host: "0.0.0.0" + port: 443 + ssl: true +database: + type: "postgresql" + connection_string: "postgresql://user:pass@localhost:5432/prod" +``` + +### Estructuras YAML Complejas + +Para configuraciones complejas, sé específico sobre los requisitos. El modelo conoce patrones comunes para herramientas como GitHub Actions, Docker Compose y Kubernetes. + +``` +Genera un workflow de GitHub Actions en YAML: + +Requisitos: +- Disparar en push a main y pull requests +- Ejecutar en Ubuntu latest +- Pasos: checkout, setup Node 18, instalar dependencias, ejecutar tests +- Cachear dependencias npm +``` + +## Definiciones de Tipos en Prompts + +Las definiciones de tipos dan al modelo un contrato preciso para la estructura de salida. Son más explícitas que los ejemplos y más fáciles de validar programáticamente. + +### Usando Tipos Estilo TypeScript + +Las interfaces de TypeScript son familiares para desarrolladores y describen precisamente campos opcionales, tipos unión y arrays. La plataforma prompts.chat usa este enfoque para prompts estructurados. + + + +### Definición de JSON Schema + + +JSON Schema es una especificación formal para describir estructura JSON. Es soportado por muchas bibliotecas de validación y herramientas de API. + + +JSON Schema proporciona restricciones como valores mín/máx, campos requeridos y patrones regex: + +``` +Extrae datos según este JSON Schema: + +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "type": "object", + "required": ["titulo", "autor", "año"], + "properties": { + "titulo": { "type": "string" }, + "autor": { "type": "string" }, + "año": { "type": "integer", "minimum": 1000, "maximum": 2100 }, + "generos": { + "type": "array", + "items": { "type": "string" } + }, + "puntuacion": { + "type": "number", + "minimum": 0, + "maximum": 5 + } + } +} + +Libro: "1984 de George Orwell (1949) - Una obra maestra distópica. +Géneros: Ciencia Ficción, Ficción Política. Puntuación 4.8/5" +``` + +## Manejo de Arrays + +Los arrays requieren atención especial. Especifica si necesitas un número fijo de elementos o una lista de longitud variable, y cómo manejar casos vacíos. + +### Arrays de Longitud Fija + +Cuando necesitas exactamente N elementos, decláralos explícitamente. El modelo asegurará que el array tenga la longitud correcta. + +``` +Extrae exactamente 3 puntos clave como JSON: + +{ + "puntos_clave": [ + "string (primer punto)", + "string (segundo punto)", + "string (tercer punto)" + ] +} + +Artículo: [texto del artículo] +``` + +### Arrays de Longitud Variable + +Para arrays de longitud variable, especifica qué hacer cuando hay cero elementos. Incluir un campo de conteo ayuda a verificar la completitud de la extracción. + +``` +Extrae todas las personas mencionadas como JSON: + +{ + "personas": [ + { + "nombre": "string", + "rol": "string o null si no se menciona" + } + ], + "conteo": number +} + +Si no se mencionan personas, devuelve array vacío. + +Texto: [texto] +``` + +## Valores Enum y Restricciones + +Los enums restringen valores a un conjunto predefinido. Esto es crucial para tareas de clasificación y en cualquier lugar donde necesites salidas consistentes y predecibles. + +### Qué Hacer y Qué No: Valores Enum + + + +### Enums de String + +Lista los valores permitidos explícitamente. Usa lenguaje "DEBE ser uno de" para forzar coincidencia estricta. + +``` +Clasifica este texto. La categoría DEBE ser uno de estos valores exactos: +- "tecnico" +- "negocios" +- "creativo" +- "personal" + +Devuelve JSON: +{ + "texto": "texto original (truncado a 50 caracteres)", + "categoria": "uno de los valores enum de arriba", + "confianza": número entre 0 y 1 +} + +Texto: [texto a clasificar] +``` + +### Números Validados + +Las restricciones numéricas previenen valores fuera de rango. Especifica el tipo (entero vs flotante) y el rango válido. + +``` +Califica estos aspectos. Cada puntuación DEBE ser un entero de 1 a 5. + +{ + "calidad": 1-5, + "valor": 1-5, + "servicio": 1-5, + "general": 1-5 +} + +Reseña: [texto de reseña] +``` + +## Manejo de Datos Faltantes + +El texto del mundo real a menudo carece de alguna información. Define cómo el modelo debe manejar datos faltantes para evitar valores alucinados. + +### Qué Hacer y Qué No: Información Faltante + + + +### Valores Null + +Permite explícitamente null e instruye al modelo a no inventar información. Esto es más seguro que hacer que el modelo adivine. + +``` +Extrae información. Usa null para cualquier campo que no pueda +determinarse del texto. NO inventes información. + +{ + "empresa": "string o null", + "ingresos": "number o null", + "empleados": "number o null", + "fundada": "number (año) o null", + "sede": "string o null" +} + +Texto: "Apple, con sede en Cupertino, fue fundada en 1976." +``` + +Salida: +```json +{ + "empresa": "Apple", + "ingresos": null, + "empleados": null, + "fundada": 1976, + "sede": "Cupertino" +} +``` + +### Valores por Defecto + +Cuando los valores por defecto tienen sentido, especifícalos en el esquema. Esto es común para extracción de configuración. + +``` +Extrae configuración con estos valores por defecto si no se especifican: + +{ + "tema": "claro" (por defecto) | "oscuro", + "idioma": "es" (por defecto) | otro código ISO, + "notificaciones": true (por defecto) | false, + "tamañoFuente": 14 (por defecto) | número +} + +Preferencias de usuario: "Quiero modo oscuro y texto más grande (18px)" +``` + +## Respuestas Multi-Objeto + +A menudo necesitas extraer múltiples elementos de una sola entrada. Define la estructura del array y cualquier requisito de ordenamiento/agrupación. + +### Array de Objetos + +Para listas de elementos similares, define el esquema del objeto una vez y especifica que es un array. + +``` +Parsea esta lista en array JSON: + +[ + { + "tarea": "string", + "prioridad": "alta" | "media" | "baja", + "vencimiento": "string fecha ISO o null" + } +] + +Lista de tareas: +- Terminar informe (urgente, vence mañana) +- Llamar al dentista (prioridad baja) +- Revisar PR #123 (media, vence el viernes) +``` + +### Objetos Agrupados + +Las tareas de agrupación requieren lógica de categorización. El modelo ordenará elementos en las categorías que definas. + +``` +Categoriza estos elementos en JSON: + +{ + "frutas": ["array de strings"], + "vegetales": ["array de strings"], + "otros": ["array de strings"] +} + +Elementos: manzana, zanahoria, pan, plátano, brócoli, leche, naranja, espinaca +``` + +## YAML para Generación de Configuración + +YAML brilla para configuraciones DevOps. El modelo conoce patrones estándar para herramientas comunes y puede generar configs listas para producción. + +### Qué Hacer y Qué No: Configs YAML + + + +### Docker Compose + +Especifica los servicios que necesitas y cualquier requisito especial. El modelo manejará la sintaxis YAML y mejores prácticas. + +``` +Genera un docker-compose.yml para: +- App Node.js en puerto 3000 +- Base de datos PostgreSQL +- Cache Redis +- Nginx reverse proxy + +Incluye: +- Health checks +- Persistencia de volúmenes +- Variables de entorno desde archivo .env +- Aislamiento de red +``` + +### Manifiestos Kubernetes + +Los manifiestos de Kubernetes son verbosos pero siguen patrones predecibles. Proporciona los parámetros clave y el modelo generará YAML compatible. + +``` +Genera YAML de deployment Kubernetes: + +Deployment: +- Nombre: api-server +- Imagen: myapp:v1.2.3 +- Réplicas: 3 +- Recursos: 256Mi memoria, 250m CPU (requests) +- Health checks: endpoint /health +- Environment desde ConfigMap: api-config + +También genera Service coincidente (ClusterIP, puerto 8080) +``` + +## Validación y Manejo de Errores + +Para sistemas de producción, incorpora validación en tus prompts. Esto captura errores antes de que se propaguen por tu pipeline. + +### Prompt de Auto-Validación + +Pide al modelo validar su propia salida contra reglas que especifiques. Esto captura errores de formato y valores inválidos. + +``` +Extrae datos como JSON, luego valida tu salida. + +Esquema: +{ + "email": "formato de email válido", + "telefono": "formato E.164 (+34123456789)", + "fecha": "formato ISO 8601 (YYYY-MM-DD)" +} + +Después de generar JSON, verifica: +1. Email contiene @ y dominio válido +2. Teléfono empieza con + y contiene solo dígitos +3. Fecha es válida y parseable + +Si la validación falla, arregla los problemas antes de responder. + +Texto: [información de contacto] +``` + +### Formato de Respuesta de Error + +Define formatos separados de éxito y error. Esto hace el manejo programático mucho más fácil. + +``` +Intenta extraer datos. Si la extracción falla, devuelve formato de error: + +Formato de éxito: +{ + "exito": true, + "datos": { ... datos extraídos ... } +} + +Formato de error: +{ + "exito": false, + "error": "descripción de qué salió mal", + "datos_parciales": { ... cualquier dato que pudo extraerse ... } +} +``` + +## JSON vs YAML: Cuándo Usar Cuál + +
+
+
Usa JSON Cuando
+
+

Se necesita parseo programático

+

Respuestas de API

+

Requisitos estrictos de tipos

+

Integración JavaScript/Web

+

Representación compacta

+
+
+
+
Usa YAML Cuando
+
+

Importa la legibilidad humana

+

Archivos de configuración

+

Se necesitan comentarios

+

DevOps/Infraestructura

+

Estructuras profundamente anidadas

+
+
+
+ +## Prompts Estructurados de Prompts.chat + +En prompts.chat, puedes crear prompts con formatos de salida estructurados: + +``` +Al crear un prompt en prompts.chat, puedes especificar: + +Tipo: STRUCTURED +Formato: JSON o YAML + +La plataforma: +- Validará salidas contra tu esquema +- Proporcionará resaltado de sintaxis +- Habilitará copiado fácil de salida estructurada +- Soportará variables de plantilla en tu esquema +``` + +## Errores Comunes + + +Estos tres problemas causan la mayoría de fallos de parseo JSON. Revísalos cuando tu código no pueda parsear salida de IA. + + +### 1. Bloques de Código Markdown + +**Problema:** El modelo envuelve JSON en bloques ```json + +**Solución:** +``` +Devuelve SOLO el objeto JSON. No envuelvas en bloques de código markdown. +No incluyas marcadores ```json o ```. +``` + +### 2. Comas Finales + +**Problema:** JSON inválido debido a comas finales + +**Solución:** +``` +Asegura sintaxis JSON válida. Sin comas finales después del último +elemento en arrays u objetos. +``` + +### 3. Strings Sin Escapar + +**Problema:** Comillas o caracteres especiales rompen JSON + +**Solución:** +``` +Escapa correctamente caracteres especiales en strings: +- \" para comillas +- \\ para backslashes +- \n para saltos de línea +``` + +## Resumen + + +Define esquemas explícitamente usando interfaces TypeScript o JSON Schema. Especifica tipos y restricciones, maneja nulls y valores por defecto, solicita auto-validación, y elige el formato correcto para tu caso de uso. + + + + +Esto completa la Parte II sobre técnicas. En la Parte III, exploraremos aplicaciones prácticas en diferentes dominios. diff --git a/src/content/book/es/10-system-prompts-personas.mdx b/src/content/book/es/10-system-prompts-personas.mdx new file mode 100644 index 00000000..60ca2a5f --- /dev/null +++ b/src/content/book/es/10-system-prompts-personas.mdx @@ -0,0 +1,435 @@ +Los prompts de sistema son como darle a la IA su personalidad y descripción de trabajo antes de que comience una conversación. Piensa en ello como las "instrucciones de backstage" que moldean todo lo que dice la IA. + + +Un prompt de sistema es un mensaje especial que le dice a la IA quién es, cómo comportarse y qué puede o no puede hacer. Los usuarios normalmente no ven este mensaje, pero afecta cada respuesta. + + + +Los prompts de sistema se basan en los conceptos de [Prompting Basado en Roles](/book/04-role-based-prompting). Mientras los prompts de rol asignan una persona dentro de tu mensaje, los prompts de sistema establecen esa identidad a un nivel más profundo que persiste durante toda la conversación. + + +## Cómo Funcionan los Prompts de Sistema + +Cuando chateas con IA, en realidad hay tres tipos de mensajes: + + + +El mensaje de sistema permanece activo durante toda la conversación. Es como el "manual de instrucciones" de la IA. + +## Construyendo un Prompt de Sistema + +Un buen prompt de sistema tiene cinco partes. Piensa en ellas como llenar una hoja de personaje para la IA: + + + +### Ejemplo: Un Tutor de Programación + + + +## Patrones de Persona + +Diferentes tareas necesitan diferentes personalidades de IA. Aquí hay tres patrones comunes que puedes adaptar: + +### 1. El Experto + +Mejor para: Aprendizaje, investigación, consejos profesionales + + + +### 2. El Asistente + +Mejor para: Productividad, organización, hacer las cosas + + + +### 3. El Personaje + +Mejor para: Escritura creativa, roleplay, entretenimiento + + + +## Técnicas Avanzadas + +### Instrucciones en Capas + +Piensa en tu prompt de sistema como una cebolla con capas. Las capas internas son las más importantes: + + + +### Comportamiento Adaptativo + +Haz que tu IA se ajuste automáticamente a diferentes usuarios: + + + +### Memoria de Conversación + +La IA no recuerda conversaciones pasadas, pero puedes decirle que rastree cosas dentro del chat actual: + + + +## Ejemplos del Mundo Real + +Aquí hay prompts de sistema completos para casos de uso comunes. ¡Haz clic para probarlos! + +### Bot de Soporte al Cliente + + + +### Compañero de Estudio + + + +### Coach de Escritura + + + +## Probando Tu Prompt de Sistema + +Antes de usar un prompt de sistema de verdad, ¡pruébalo! Esto es lo que debes verificar: + + + +### Entendiendo los Ataques de Jailbreak + +"Jailbreaking" es cuando alguien intenta engañar a la IA para que ignore sus reglas. Entender estos ataques te ayuda a construir mejores defensas. + + + +### Más Escenarios de Prueba + +Usa estos ejemplos interactivos para ver cómo un prompt de sistema bien diseñado maneja situaciones difíciles: + +#### Prueba 1: Intento de Jailbreak + +Ve cómo un buen prompt de sistema resiste intentos de anularlo: + + + +#### Prueba 2: Mantener el Personaje + +Prueba si la IA mantiene su persona cuando se la presiona: + + + +#### Prueba 3: Aplicación de Límites + +Verifica si la IA respeta sus limitaciones declaradas: + + + +#### Prueba 4: Revelar el Prompt de Sistema + +Ve si la IA protege sus instrucciones: + + + +#### Prueba 5: Instrucciones Contradictorias + +Prueba cómo la IA maneja solicitudes contradictorias: + + + + +Un prompt de sistema bien elaborado: +- Rechazará cortésmente solicitudes inapropiadas +- Se mantendrá en personaje mientras redirige +- No revelará instrucciones confidenciales +- Manejará casos límite con gracia + + +## Referencia Rápida + +
+
+

Hacer

+
    +
  • Dar una identidad clara
  • +
  • Listar capacidades específicas
  • +
  • Establecer límites explícitos
  • +
  • Definir el tono y estilo
  • +
  • Incluir respuestas de ejemplo
  • +
+
+
+

No Hacer

+
    +
  • Ser vago sobre el rol
  • +
  • Olvidar establecer límites
  • +
  • Hacerlo muy largo (500 palabras máx)
  • +
  • Contradecirte a ti mismo
  • +
  • Asumir que la IA "lo descubrirá"
  • +
+
+
+ +## Resumen + +Los prompts de sistema son el manual de instrucciones de la IA. Establecen: +- **Quién** es la IA (identidad y experiencia) +- **Qué** puede y no puede hacer (capacidades y límites) +- **Cómo** debe responder (tono, formato, estilo) + + +Comienza con un prompt de sistema corto y agrega más reglas conforme descubras qué se necesita. Un prompt claro de 100 palabras vence a uno confuso de 500 palabras. + + + + + + +En el próximo capítulo, exploraremos el encadenamiento de prompts: conectar múltiples prompts juntos para tareas complejas de múltiples pasos. diff --git a/src/content/book/es/11-prompt-chaining.mdx b/src/content/book/es/11-prompt-chaining.mdx new file mode 100644 index 00000000..648b7adb --- /dev/null +++ b/src/content/book/es/11-prompt-chaining.mdx @@ -0,0 +1,379 @@ +El encadenamiento de prompts divide tareas complejas en secuencias de prompts más simples, donde la salida de cada paso alimenta al siguiente. Esta técnica mejora dramáticamente la confiabilidad y habilita flujos de trabajo sofisticados que serían imposibles con un solo prompt. + + +Así como una línea de ensamblaje de fábrica divide la manufactura en estaciones especializadas, el encadenamiento de prompts divide las tareas de IA en pasos especializados. Cada paso hace una cosa bien, y la salida combinada es mucho mejor que intentar hacer todo a la vez. + + +## ¿Por Qué Encadenar Prompts? + +Los prompts individuales luchan con tareas complejas porque intentan hacer demasiado a la vez. La IA tiene que simultáneamente entender, analizar, planificar y generar, lo que lleva a errores e inconsistencias. + +
+
+

Problemas del Prompt Único

+
+

El razonamiento de múltiples pasos se confunde

+

Diferentes "modos" de pensamiento chocan

+

Las salidas complejas carecen de consistencia

+

Sin oportunidad para control de calidad

+
+
+
+

El Encadenamiento Resuelve Esto

+
+

Cada paso se enfoca en una tarea

+

Prompts especializados para cada modo

+

Validar entre pasos

+

Depurar y mejorar pasos individuales

+
+
+
+ +## Patrón Básico de Encadenamiento + +La cadena más simple pasa la salida de un prompt directamente al siguiente. Cada paso tiene un propósito claro y enfocado. + +
+
+
+

Prompt 1

+

(Extraer)

+
+

Entrada

+
+
→
+
+
+

Prompt 2

+

(Analizar)

+
+

Intermedio

+
+
→
+
+
+

Prompt 3

+

(Generar)

+
+

Salida

+
+
+ + +El patrón de cadena más común es **Extraer → Transformar → Generar**. Primero extrae datos crudos, luego reformatea para tu propósito, después genera la salida final. Este patrón funciona para casi cualquier tarea de contenido. + + +## Tipos de Cadenas + +Diferentes tareas requieren diferentes arquitecturas de cadenas. Elige el patrón que coincida con tu flujo de trabajo. + + + +### Cadena Secuencial + +El patrón más directo: cada paso depende del anterior. Piensa en ello como una carrera de relevos donde cada corredor pasa el testigo al siguiente. + + + +### Cadena Paralela + +Cuando necesitas múltiples perspectivas sobre la misma entrada, ejecuta prompts en paralelo y combina resultados. Esto es más rápido que las cadenas secuenciales y proporciona un análisis más rico. + + + +### Cadena Condicional + +Enruta entradas a través de diferentes caminos basándose en clasificación. Esto es como un árbol de decisiones donde la IA primero categoriza la entrada, luego maneja cada categoría diferentemente. + + + +### Cadena Iterativa + +Sigue refinando la salida hasta que cumpla estándares de calidad. La IA genera, evalúa y mejora en un bucle hasta estar satisfecha o alcanzar el máximo de iteraciones. + + +Siempre establece un número máximo de iteraciones (típicamente 3-5) para prevenir bucles infinitos y controlar costos. La ley de rendimientos decrecientes aplica: la mayoría de la mejora sucede en las primeras 2-3 iteraciones. + + += 8: SALIR DEL BUCLE' } + ]} +/> + +## Patrones Comunes de Cadenas + +Estos patrones probados en batalla resuelven problemas comunes. Úsalos como puntos de partida y adapta a tus necesidades. + +### Extraer → Transformar → Generar + +El caballo de batalla del procesamiento de contenido. Extrae datos, reformatea, luego crea algo nuevo. + +
+

Mejor Para

+

Resumen de documentos, generación de informes, reutilización de contenido, conversión de datos a narrativa

+
+ + + +### Analizar → Planificar → Ejecutar + +Perfecto para refactorización de código, planificación de proyectos, o cualquier tarea donde necesites entender antes de actuar. + +
+

Mejor Para

+

Refactorización de código, planificación de proyectos, resolución de problemas, toma de decisiones estratégicas, resolución de problemas complejos

+
+ + {\n const { email, password } = req.body;\n if (!email || !isValidEmail(email)) {\n return res.status(400).json({ error: 'Email inválido' });\n }\n next();\n};" } + ]} +/> + +### Generar → Criticar → Refinar + +El bucle de auto-mejora. Genera contenido, haz que la IA lo evalúe críticamente, luego mejora basándote en ese feedback. Esto imita cómo trabajan juntos escritores y editores profesionales. + +
+

Mejor Para

+

Copy de marketing, escritura creativa, borradores de email, presentaciones, cualquier contenido que se beneficie de revisión

+
+ + + +## Implementando Cadenas + +Puedes implementar cadenas manualmente para experimentación, o programáticamente para sistemas de producción. Comienza simple y agrega complejidad según se necesite. + +### Encadenamiento Manual + +El enfoque de copiar y pegar es perfecto para prototipado y experimentación. Ejecuta cada prompt manualmente, examina la salida, y pégala en el siguiente prompt. + + + +### Encadenamiento Programático + +Para sistemas de producción, automatiza la cadena con código. Esto habilita manejo de errores, logging e integración con tu aplicación. + + + +### Usando Plantillas de Cadenas + +Define cadenas como archivos de configuración para reutilización y modificación fácil. Esto separa la lógica de prompts del código de aplicación. + + + +## Manejo de Errores en Cadenas + +Las cadenas pueden fallar en cualquier paso. Incorpora validación, reintentos y alternativas para hacer tus cadenas robustas. + + + + +Si un paso produce mala salida, cada paso siguiente se verá afectado. Siempre valida resultados intermedios críticos antes de pasarlos adelante. + + +### Validación Entre Pasos + +Agrega un paso de validación después de cualquier paso que produzca datos estructurados. Esto captura errores temprano antes de que se propaguen. + + + +### Cadenas de Respaldo + +Cuando tu enfoque principal falla, ten un respaldo más simple listo. Intercambia capacidad por confiabilidad. + + + +## Optimización de Cadenas + +Una vez que tu cadena funciona, optimiza para velocidad, costo y confiabilidad. Estos a menudo tienen compensaciones entre sí. + +
+
+

Reduciendo Latencia

+
+

Paraleliza pasos independientes

+

Cachea resultados intermedios

+

Usa modelos más pequeños para pasos simples

+

Agrupa operaciones similares

+
+
+
+

Reduciendo Costo

+
+

Usa modelos más baratos para clasificación

+

Limita iteraciones en bucles

+

Cortocircuita cuando sea posible

+

Cachea consultas repetidas

+
+
+
+

Mejorando Confiabilidad

+
+

Agrega validación entre pasos

+

Incluye lógica de reintentos

+

Registra resultados intermedios

+

Implementa rutas de respaldo

+
+
+
+ +## Ejemplo de Cadena del Mundo Real + +Repasemos una cadena de producción completa. Este pipeline de contenido transforma una idea cruda en un paquete de artículo pulido. + +### Cadena de Pipeline de Contenido + + + +## Resumen + +El encadenamiento de prompts transforma lo que la IA puede lograr al dividir tareas imposibles en pasos alcanzables. + +
+
+

El Encadenamiento Habilita

+
+

Flujos de trabajo complejos de múltiples pasos

+

Mayor calidad a través de especialización

+

Mejor manejo de errores y validación

+

Componentes de prompts modulares y reutilizables

+
+
+
+

Principios Clave

+
+

Divide tareas complejas en pasos simples

+

Diseña interfaces claras entre pasos

+

Valida salidas intermedias

+

Incorpora manejo de errores y respaldos

+

Optimiza para tus restricciones

+
+
+
+ + +Comienza con una cadena secuencial de 2-3 pasos. Haz que funcione confiablemente antes de agregar complejidad. La mayoría de las tareas no necesitan arquitecturas de cadenas elaboradas. + + + + +En el próximo capítulo, exploraremos el prompting multimodal: trabajando con imágenes, audio y otro contenido no textual. diff --git a/src/content/book/es/12-handling-edge-cases.mdx b/src/content/book/es/12-handling-edge-cases.mdx new file mode 100644 index 00000000..93e73d66 --- /dev/null +++ b/src/content/book/es/12-handling-edge-cases.mdx @@ -0,0 +1,580 @@ +Los prompts que funcionan perfectamente en pruebas a menudo fallan en el mundo real. Los usuarios envían mensajes vacíos, pegan muros de texto, hacen solicitudes ambiguas, y a veces intentan romper tu sistema intencionalmente. Este capítulo te enseña a construir prompts que manejan lo inesperado con gracia. + + +El 80% de los problemas en producción vienen de entradas que nunca anticipaste. Un prompt que maneja bien los casos límite vale más que un prompt "perfecto" que solo funciona con entradas ideales. + + +## Por Qué los Casos Límite Rompen los Prompts + +Cuando un prompt encuentra una entrada inesperada, típicamente falla de una de tres formas: + +**Fallos Silenciosos**: El modelo produce salida que parece correcta pero contiene errores. Estos son los más peligrosos porque son difíciles de detectar. + +**Respuestas Confusas**: El modelo malinterpreta la solicitud y responde una pregunta diferente a la que se hizo. + +**Manejo Alucinado**: El modelo inventa una forma de manejar el caso límite que no coincide con tu comportamiento esperado. + + + +## Categorías de Casos Límite + +Entender qué puede salir mal te ayuda a prepararte. Los casos límite caen en tres categorías principales: + +### Casos Límite de Entrada + +Estos son problemas con los datos mismos: + + + +### Casos Límite de Dominio + +Estas son solicitudes que empujan los límites del propósito de tu prompt: + + + +### Casos Límite Adversarios + +Estos son intentos deliberados de mal uso de tu sistema: + + + +## Patrones de Validación de Entrada + +La clave para manejar casos límite son instrucciones explícitas. No asumas que el modelo "lo descubrirá" - dile exactamente qué hacer en cada escenario. + +### Manejando Entrada Vacía + +El caso límite más común es recibir nada en absoluto, o entrada que es esencialmente vacía (solo espacios en blanco o saludos). + + + +### Manejando Entrada Larga + +Cuando la entrada excede lo que puedes procesar razonablemente, falla con gracia en lugar de truncar silenciosamente. + + + +### Manejando Solicitudes Ambiguas + +Cuando una solicitud podría significar múltiples cosas, pedir clarificación es mejor que adivinar mal. + + + +## Construyendo Prompts Defensivos + +Un prompt defensivo anticipa modos de fallo y define comportamiento explícito para cada uno. Piensa en ello como manejo de errores para lenguaje natural. + +### La Plantilla Defensiva + +Cada prompt robusto debe abordar estas cuatro áreas: + + + +### Ejemplo: Extracción Defensiva de Datos + +Este prompt extrae información de contacto pero maneja cada caso límite explícitamente. Nota cómo cada fallo potencial tiene una respuesta definida. + + + +## Manejando Solicitudes Fuera de Alcance + +Cada prompt tiene límites. Definirlos explícitamente previene que el modelo divague hacia territorio donde podría dar mal consejo o inventar cosas. + +### Límites de Alcance con Gracia + +Las mejores respuestas fuera de alcance hacen tres cosas: reconocer la solicitud, explicar la limitación, y ofrecer una alternativa. + + + +### Manejando Fechas de Corte de Conocimiento + +Sé honesto sobre lo que no sabes. Los usuarios confían más en la IA cuando admite limitaciones. + + + +## Manejo de Entrada Adversaria + +Algunos usuarios intentarán manipular tus prompts, ya sea por curiosidad o intención maliciosa. Construir defensas en tus prompts reduce estos riesgos. + +### Defensa Contra Inyección de Prompts + +La inyección de prompt es cuando un usuario intenta anular tus instrucciones incrustando sus propios comandos en la entrada. La defensa clave es tratar la entrada del usuario como datos, nunca como instrucciones. + + + + +Las defensas contra inyección de prompts reducen el riesgo pero no pueden eliminarlo completamente. Para aplicaciones de alto riesgo, combina defensas de prompts con sanitización de entrada, filtrado de salida, y revisión humana. + + +### Manejando Solicitudes Sensibles + +Algunas solicitudes requieren manejo especial debido a preocupaciones de seguridad, legales o éticas. Define estos límites explícitamente. + + + +## Patrones de Recuperación de Errores + +Incluso prompts bien diseñados encontrarán situaciones que no pueden manejar perfectamente. El objetivo es fallar de manera útil. + +### Degradación Elegante + +Cuando no puedes completar completamente una tarea, ofrece lo que puedas en lugar de fallar completamente. + + + +### Indicadores de Confianza + +Enseña a tus prompts a expresar incertidumbre. Esto ayuda a los usuarios a saber cuándo confiar en la salida y cuándo verificar. + + + + + +## Probando Casos Límite + +Antes de desplegar un prompt, pruébalo sistemáticamente contra los casos límite que has anticipado. Esta lista de verificación ayuda a asegurar que no hayas perdido modos de fallo comunes. + +### Lista de Verificación de Pruebas de Casos Límite + + + + + + + + + +### Creando una Suite de Pruebas + +Para prompts de producción, crea una suite de pruebas sistemática. Aquí hay un patrón que puedes adaptar: + + + +## Ejemplo del Mundo Real: Bot de Servicio al Cliente Robusto + +Este ejemplo comprehensivo muestra cómo todos los patrones se unen en un prompt listo para producción. Nota cómo cada caso límite tiene manejo explícito. + + + +## Resumen + +Construir prompts robustos requiere pensar en qué puede salir mal antes de que suceda. Los principios clave: + + + + +En producción, todo lo que puede salir mal eventualmente lo hará. Un prompt que maneja casos límite con gracia vale más que un prompt "perfecto" que solo funciona con entradas ideales. + + + + +En el próximo capítulo, exploraremos cómo trabajar con múltiples modelos de IA y comparar sus salidas. diff --git a/src/content/book/es/13-multimodal-prompting.mdx b/src/content/book/es/13-multimodal-prompting.mdx new file mode 100644 index 00000000..75e28d29 --- /dev/null +++ b/src/content/book/es/13-multimodal-prompting.mdx @@ -0,0 +1,665 @@ +Durante la mayor parte de la historia, las computadoras trabajaron con un tipo de dato a la vez: texto en un programa, imágenes en otro, audio en otro lugar. Pero los humanos no experimentamos el mundo de esta manera. Vemos, escuchamos, leemos y hablamos simultáneamente, combinando todas estas entradas para entender nuestro entorno. + +**La IA Multimodal** lo cambia todo. Estos modelos pueden procesar múltiples tipos de información juntos—analizando una imagen mientras leen tu pregunta sobre ella, o generando imágenes a partir de tus descripciones de texto. Este capítulo te enseña cómo comunicarte efectivamente con estos sistemas poderosos. + + +"Multi" significa muchos, y "modal" se refiere a modos o tipos de datos. Un modelo multimodal puede trabajar con múltiples modalidades: texto, imágenes, audio, video, o incluso código. En lugar de herramientas separadas para cada tipo, un modelo entiende todos juntos. + + +## Por Qué Importa lo Multimodal + +La IA tradicional requería que describieras todo en palabras. ¿Quieres preguntar sobre una imagen? Primero tendrías que describirla. ¿Quieres analizar un documento? Necesitarías transcribirlo manualmente. Los modelos multimodales eliminan estas barreras. + + + +## Por Qué el Prompting Importa Aún Más para Multimodal + +Con modelos solo de texto, la IA recibe exactamente lo que escribes. Pero con modelos multimodales, la IA debe interpretar información visual o de audio—y la interpretación requiere guía. + + + +**Sin guía**, el modelo podría describir colores, diseño, o detalles irrelevantes. **Con guía**, se enfoca en lo que realmente te importa. + + +Cuando miras una imagen, instantáneamente sabes qué es importante basándote en tu contexto y objetivos. La IA no tiene este contexto a menos que lo proporciones. Una foto de una grieta en una pared podría ser: una preocupación de ingeniería estructural, una textura artística, o un fondo irrelevante. Tu prompt determina cómo la IA lo interpreta. + + +## El Panorama Multimodal + +Diferentes modelos tienen diferentes capacidades. Esto es lo disponible en 2025: + +### Modelos de Comprensión (Entrada → Análisis) + +Estos modelos aceptan varios tipos de medios y producen análisis de texto o respuestas. + + + +### Modelos de Generación (Texto → Medios) + +Estos modelos crean imágenes, audio o video a partir de descripciones de texto. + + + + +El panorama multimodal cambia rápidamente. Nuevos modelos se lanzan frecuentemente, y los modelos existentes ganan capacidades a través de actualizaciones. Siempre verifica la documentación más reciente para características y limitaciones actuales. + + +## Prompts de Comprensión de Imágenes + +El caso de uso multimodal más común es pedir a la IA que analice imágenes. La clave es proporcionar contexto sobre lo que necesitas. + +### Análisis Básico de Imágenes + +Comienza con una estructura de solicitud clara. Dile al modelo en qué aspectos enfocarse. + + + +### Salida Estructurada para Imágenes + +Cuando necesitas procesar análisis de imágenes programáticamente, solicita salida JSON. + + + +### Análisis Comparativo + +Comparar múltiples imágenes requiere etiquetado claro y criterios de comparación específicos. + + + +## Análisis de Documentos y Capturas de Pantalla + +Una de las aplicaciones más prácticas de la IA multimodal es analizar documentos, capturas de pantalla y elementos de UI. Esto ahorra horas de transcripción manual y revisión. + +### Extracción de Documentos + +Documentos escaneados, fotos de recibos y PDFs como imágenes pueden procesarse. La clave es decirle al modelo qué tipo de documento es y qué información necesitas. + + + +### Análisis de Capturas de Pantalla y UI + +Las capturas de pantalla son minas de oro para depuración, revisión de UX y documentación. Guía a la IA para enfocarse en lo que importa. + + + +### Análisis de Mensajes de Error + +Cuando encuentras un error, una captura de pantalla a menudo contiene más contexto que copiar solo el texto del error. + + + +## Prompts de Generación de Imágenes + +Generar imágenes a partir de descripciones de texto es un arte. Cuanto más específico y estructurado tu prompt, más cerca estará el resultado de tu visión. + +### La Anatomía de un Prompt de Imagen + +Los prompts efectivos de generación de imágenes tienen varios componentes: + + + +### Generación Básica de Imágenes + + + +### Construcción de Escenas + +Para escenas complejas, describe capas desde el primer plano hasta el fondo. + + + +## Prompts de Audio + +El procesamiento de audio abre transcripción, análisis y comprensión de contenido hablado. La clave es proporcionar contexto sobre qué contiene el audio. + +### Transcripción Mejorada + +La transcripción básica es solo el inicio. Con buenos prompts, puedes obtener identificación de hablantes, marcas de tiempo y precisión específica del dominio. + + + +### Análisis de Contenido de Audio + +Más allá de la transcripción, la IA puede analizar el contenido, tono y momentos clave en audio. + + + +## Prompts de Video + +El video combina análisis visual y de audio a lo largo del tiempo. El desafío es guiar a la IA para enfocarse en los aspectos relevantes a lo largo de toda la duración. + +### Comprensión de Video + + + +### Extracción de Contenido de Video + +Para extracción de información específica de videos, sé preciso sobre lo que necesitas. + + + +## Combinaciones Multimodales + +El verdadero poder de la IA multimodal emerge cuando combinas diferentes tipos de entrada. Estas combinaciones habilitan análisis que sería imposible con cualquier modalidad individual. + +### Verificación de Imagen + Texto + +Verifica si las imágenes y sus descripciones coinciden—esencial para e-commerce, moderación de contenido y aseguramiento de calidad. + + + +### Captura de Pantalla + Depuración de Código + +Una de las combinaciones más poderosas para desarrolladores: ver el bug visual junto con el código. + + + +### Toma de Decisiones con Múltiples Imágenes + +Cuando eliges entre opciones, la comparación estructurada ayuda a tomar mejores decisiones. + + + +## Mejores Prácticas para Prompts Multimodales + +Obtener excelentes resultados de IA multimodal requiere entender tanto sus capacidades como limitaciones. + +### Qué Hace Efectivos a los Prompts Multimodales + + + +### Errores Comunes a Evitar + + + +### Manejando Limitaciones con Gracia + + + + diff --git a/src/content/book/es/14-context-engineering.mdx b/src/content/book/es/14-context-engineering.mdx new file mode 100644 index 00000000..cb27736c --- /dev/null +++ b/src/content/book/es/14-context-engineering.mdx @@ -0,0 +1,287 @@ +Entender el contexto es esencial para construir aplicaciones de IA que realmente funcionen. Este capítulo cubre todo lo que necesitas saber sobre dar a la IA la información correcta en el momento correcto. + + +Los modelos de IA son sin estado. No recuerdan conversaciones pasadas. Cada vez que envías un mensaje, necesitas incluir todo lo que la IA necesita saber. Esto se llama "ingeniería de contexto." + + +## ¿Qué es el Contexto? + +El contexto es toda la información que das a la IA junto con tu pregunta. Piénsalo así: + + + +Sin contexto, la IA no tiene idea de qué "estado" estás preguntando. Con contexto, puede dar una respuesta útil. + +### La Ventana de Contexto + +Recuerda de capítulos anteriores: la IA tiene una "ventana de contexto" limitada - la cantidad máxima de texto que puede ver a la vez. Esto incluye: + + + +## La IA es Sin Estado + + +La IA no recuerda nada entre conversaciones. Cada llamada API comienza fresca. Si quieres que la IA "recuerde" algo, TÚ tienes que incluirlo en el contexto cada vez. + + +Por esto los chatbots envían tu historial completo de conversación con cada mensaje. No es que la IA recuerde - es que la app re-envía todo. + + + +La IA dirá que no sabe porque verdaderamente no tiene acceso a ningún contexto anterior. + +## RAG: Generación Aumentada por Recuperación + +RAG es una técnica para dar a la IA acceso a conocimiento en el que no fue entrenada. En lugar de intentar meter todo en el entrenamiento de la IA, tú: + +1. **Almacenas** tus documentos en una base de datos buscable +2. **Buscas** documentos relevantes cuando un usuario hace una pregunta +3. **Recuperas** las piezas más relevantes +4. **Aumentas** tu prompt con esas piezas +5. **Generas** una respuesta usando ese contexto + +
+

Cómo Funciona RAG:

+
+
+ 1 + Usuario pregunta: "¿Cuál es nuestra política de reembolso?" +
+
+ 2 + El sistema busca en tus documentos "política de reembolso" +
+
+ 3 + Encuentra la sección relevante de tu documento de políticas +
+
+ 4 + Envía a la IA: "Basándote en esta política: [texto], responde: ¿Cuál es nuestra política de reembolso?" +
+
+ 5 + La IA genera respuesta precisa usando tu política real +
+
+
+ +### ¿Por Qué RAG? + +
+
+

Ventajas de RAG

+
    +
  • Usa tus datos reales y actuales
  • +
  • Reduce alucinaciones
  • +
  • Puede citar fuentes
  • +
  • Fácil de actualizar (solo actualiza documentos)
  • +
  • No necesita fine-tuning costoso
  • +
+
+
+

Cuándo Usar RAG

+
    +
  • Bots de soporte al cliente
  • +
  • Búsqueda de documentación
  • +
  • Bases de conocimiento internas
  • +
  • Cualquier Q&A específico de dominio
  • +
  • Cuando la precisión importa
  • +
+
+
+ +## Embeddings: Cómo Funciona la Búsqueda + +¿Cómo sabe RAG qué documentos son "relevantes"? Usa **embeddings** - una forma de convertir texto en números que capturan significado. + +### ¿Qué Son los Embeddings? + +Un embedding es una lista de números (un "vector") que representa el significado del texto. Significados similares = números similares. + + + +### Búsqueda Semántica + +Con embeddings, puedes buscar por significado, no solo palabras clave: + + + +Por esto RAG es tan poderoso - encuentra información relevante incluso cuando las palabras exactas no coinciden. + +## Llamadas a Funciones / Uso de Herramientas + +Las llamadas a funciones permiten que la IA use herramientas externas - como buscar en la web, consultar una base de datos, o llamar una API. + + +Diferentes proveedores de IA llaman esto de diferentes formas: "function calling" (OpenAI), "tool use" (Anthropic/Claude), o "tools" (término general). Todos significan lo mismo. + + +### Cómo Funciona + +1. Le dices a la IA qué herramientas están disponibles +2. La IA decide si necesita una herramienta para responder +3. La IA genera una solicitud estructurada para la herramienta +4. Tu código ejecuta la herramienta y devuelve resultados +5. La IA usa los resultados para formar su respuesta + + + +## Resumen: Gestionando Conversaciones Largas + +A medida que las conversaciones se alargan, llegarás al límite de la ventana de contexto. Como la IA es sin estado (no recuerda nada), las conversaciones largas pueden desbordarse. ¿La solución? **Resumen**. + +### El Problema + + + +### Estrategias de Resumen + +Diferentes enfoques funcionan para diferentes casos de uso. Haz clic en cada estrategia para ver cómo procesa la misma conversación: + + + +### Qué Capturar en los Resúmenes + +Un buen resumen de conversación preserva lo que importa: + + + +### Pruébalo: Crea un Resumen + + + +### Cuándo Resumir + + + +## MCP: Model Context Protocol + +MCP (Model Context Protocol) es una forma estándar de conectar IA a datos y herramientas externas. En lugar de construir integraciones personalizadas para cada proveedor de IA, MCP proporciona una interfaz universal. + +### ¿Por Qué MCP? + + + +### MCP Proporciona + +- **Recursos**: Datos que la IA puede leer (archivos, registros de base de datos, respuestas de API) +- **Herramientas**: Acciones que la IA puede tomar (buscar, crear, actualizar, eliminar) +- **Prompts**: Plantillas de prompts pre-construidas + + +¡Esta plataforma tiene un servidor MCP! Puedes conectarlo a Claude Desktop u otros clientes compatibles con MCP para buscar y usar prompts directamente desde tu asistente de IA. + + +## Construyendo Contexto: La Imagen Completa + + + +## Mejores Prácticas + + + +## Resumen + +La ingeniería de contexto se trata de dar a la IA la información correcta: + +- **La IA es sin estado** - incluye todo lo que necesita cada vez +- **RAG** recupera documentos relevantes para aumentar prompts +- **Embeddings** habilitan búsqueda semántica (significado, no solo palabras clave) +- **Llamadas a funciones** permiten que la IA use herramientas externas +- **Resumen** gestiona conversaciones largas +- **MCP** estandariza cómo la IA se conecta a datos y herramientas + + +La calidad de la salida de la IA depende de la calidad del contexto que proporcionas. Mejor contexto = mejores respuestas. + diff --git a/src/content/book/es/15-common-pitfalls.mdx b/src/content/book/es/15-common-pitfalls.mdx new file mode 100644 index 00000000..3a72da09 --- /dev/null +++ b/src/content/book/es/15-common-pitfalls.mdx @@ -0,0 +1,373 @@ +Incluso los ingenieros de prompts experimentados caen en trampas predecibles. ¿Las buenas noticias? Una vez que reconoces estos patrones, son fáciles de evitar. Este capítulo recorre los errores más comunes, explica por qué suceden, y te da estrategias concretas para esquivarlos. + + +Un solo error puede convertir una IA poderosa en una herramienta frustrante. Entender estos patrones es a menudo la diferencia entre "la IA no funciona para mí" y "la IA transformó mi flujo de trabajo." + + +## La Trampa de la Vaguedad + +**El Patrón**: Sabes lo que quieres, así que asumes que la IA también lo descubrirá. Pero los prompts vagos producen resultados vagos. + + + +**Por qué sucede**: Naturalmente omitimos detalles cuando pensamos que son "obvios." Pero lo que es obvio para ti no es obvio para un modelo que no tiene contexto sobre tu situación, audiencia u objetivos. + + + +## La Trampa de la Sobrecarga + +**El Patrón**: Intentas conseguir todo en un prompt—comprehensivo, gracioso, profesional, amigable para principiantes, avanzado, optimizado para SEO, y corto. ¿El resultado? La IA pierde la mitad de tus requisitos o produce un desastre confuso. + + + +**Por qué sucede**: Miedo a múltiples interacciones, o querer "sacarlo todo" de una vez. Pero la sobrecarga cognitiva afecta a la IA igual que afecta a los humanos—demasiados requisitos compitiendo lleva a cosas olvidadas. + + + + +Cuando un solo prompt se sobrecarga, [el encadenamiento de prompts](/book/11-prompt-chaining) es a menudo la solución. Divide tareas complejas en una secuencia de prompts enfocados, donde cada paso se construye sobre el anterior. + + +## La Trampa de la Suposición + +**El Patrón**: Haces referencia a algo "de antes" o asumes que la IA conoce tu proyecto, tu empresa, o tus conversaciones previas. No lo hace. + + + +**Por qué sucede**: Las conversaciones con IA se sienten como hablar con un colega. Pero a diferencia de los colegas, la mayoría de los modelos de IA no tienen memoria persistente entre sesiones—cada conversación comienza fresca. + + + +## La Trampa de la Pregunta Dirigida + +**El Patrón**: Formulas tu pregunta de una manera que incrusta tu suposición, obteniendo confirmación en lugar de perspectiva. + + + +**Por qué sucede**: A menudo buscamos confirmación, no información. Nuestra formulación inconscientemente empuja hacia la respuesta que esperamos o queremos. + + + +## La Trampa de Confiar en Todo + +**El Patrón**: Las respuestas de IA suenan confiadas y autoritativas, así que las aceptas sin verificación. Pero confianza no es igual a precisión. + + + +**Por qué sucede**: La IA suena confiada incluso cuando está completamente equivocada. También somos propensos al "sesgo de automatización"—la tendencia a confiar en las salidas de computadoras más de lo que deberíamos. + + + +## La Trampa del Intento Único + +**El Patrón**: Envías un prompt, obtienes un resultado mediocre, y concluyes que la IA "no funciona" para tu caso de uso. Pero los grandes resultados casi siempre requieren iteración. + + + +**Por qué sucede**: Esperamos que la IA lea nuestra mente en el primer intento. No esperamos iterar con búsquedas de Google, pero de alguna manera esperamos perfección de la IA. + + + +## La Trampa de Descuidar el Formato + +**El Patrón**: Te enfocas en lo que quieres que diga la IA, pero olvidas especificar cómo debería formatearse. Entonces obtienes prosa cuando necesitabas JSON, o un muro de texto cuando necesitabas viñetas. + + + +**Por qué sucede**: Nos enfocamos en contenido sobre estructura. Pero si necesitas parsear la salida programáticamente, o pegarla en algún lugar específico, el formato importa tanto como el contenido. + + + +## La Trampa de la Ventana de Contexto + +**El Patrón**: Pegas un documento enorme y esperas análisis comprehensivo. Pero los modelos tienen límites—pueden truncar, perder enfoque, o perder detalles importantes en entradas largas. + + + + + +## La Trampa de la Antropomorfización + +**El Patrón**: Tratas a la IA como un colega humano—esperando que "disfrute" tareas, te recuerde, o se preocupe por resultados. No lo hace. + + + +**Por qué sucede**: Las respuestas de IA son tan humanas que naturalmente caemos en patrones sociales. Pero las apelaciones emocionales no hacen que la IA se esfuerce más—las instrucciones claras sí. + + +En lugar de apelaciones emocionales, enfócate en: requisitos claros, buenos ejemplos, restricciones específicas, y criterios de éxito explícitos. Estos mejoran las salidas. "Por favor esfuérzate mucho" no. + + +## La Trampa de Descuidar la Seguridad + +**El Patrón**: En la prisa por hacer que las cosas funcionen, incluyes información sensible en prompts—claves API, contraseñas, datos personales, o información propietaria. + + + +**Por qué sucede**: Enfoque en funcionalidad sobre seguridad. Pero recuerda: los prompts a menudo van a servidores externos, pueden ser registrados, y podrían usarse para entrenamiento. + + + +## La Trampa de Ignorar las Alucinaciones + +**El Patrón**: Pides citas, estadísticas, o hechos específicos, y asumes que son reales porque la IA los declaró con confianza. Pero la IA regularmente inventa información que suena plausible. + + + +**Por qué sucede**: La IA genera texto que suena autoritativo. No "sabe" cuándo está inventando cosas—está prediciendo texto probable, no recuperando hechos verificados. + + + +## Lista de Verificación Pre-Envío + +Antes de enviar cualquier prompt importante, revisa esta lista rápida: + + + + + +## Analiza Tus Prompts + +Usa IA para obtener retroalimentación instantánea sobre la calidad de tu prompt. Pega cualquier prompt y obtén un análisis detallado: + + + +## Depura Este Prompt + +¿Puedes identificar qué está mal con este prompt? + + diff --git a/src/content/book/es/16-ethics-responsible-use.mdx b/src/content/book/es/16-ethics-responsible-use.mdx new file mode 100644 index 00000000..fed07863 --- /dev/null +++ b/src/content/book/es/16-ethics-responsible-use.mdx @@ -0,0 +1,357 @@ +Los prompts que escribes moldean cómo se comporta la IA. Un prompt bien elaborado puede educar, asistir y empoderar. Uno descuidado puede engañar, discriminar o causar daño. Como ingenieros de prompts, no somos solo usuarios—somos diseñadores del comportamiento de la IA, y eso conlleva responsabilidad real. + +Este capítulo no trata sobre reglas impuestas desde arriba. Se trata de entender el impacto de nuestras decisiones y construir hábitos que lleven a un uso de IA del que podamos estar orgullosos. + + +La IA amplifica lo que se le da. Un prompt sesgado produce salidas sesgadas a escala. Un prompt engañoso habilita el engaño a escala. Las implicaciones éticas de la ingeniería de prompts crecen con cada nueva capacidad que estos sistemas ganan. + + +## Fundamentos Éticos + +Cada decisión en ingeniería de prompts conecta con algunos principios fundamentales: + + + +### El Rol del Ingeniero de Prompts + +Tienes más influencia de lo que podrías pensar: + +- **Lo que produce la IA**: Tus prompts determinan el contenido, tono y calidad de las salidas +- **Cómo interactúa la IA**: Tus prompts de sistema moldean personalidad, límites y experiencia de usuario +- **Qué protecciones existen**: Tus decisiones de diseño determinan qué hará y qué no hará la IA +- **Cómo se manejan los errores**: Tu manejo de errores determina si los fallos son graciosos o dañinos + +## Evitando Salidas Dañinas + +La obligación ética más fundamental es prevenir que tus prompts causen daño. + +### Categorías de Contenido Dañino + + + + +MASI significa **Material de Abuso Sexual Infantil**. Crear, distribuir o poseer tal contenido es ilegal en todo el mundo. Los sistemas de IA nunca deben generar contenido que represente a menores en situaciones sexuales, y los ingenieros de prompts responsables construyen activamente protecciones contra tal uso indebido. + + +### Incorporando Seguridad en los Prompts + +Al construir sistemas de IA, incluye directrices de seguridad explícitas: + + + +### El Marco de Intención vs. Impacto + +No toda solicitud sensible es maliciosa. Usa este marco para casos ambiguos: + + + +## Abordando el Sesgo + +Los modelos de IA heredan sesgos de sus datos de entrenamiento—inequidades históricas, brechas de representación, suposiciones culturales y patrones lingüísticos. Como ingenieros de prompts, podemos amplificar estos sesgos o contrarrestarlos activamente. + +### Cómo se Manifiesta el Sesgo + + + +### Probando por Sesgo + + + +### Mitigando el Sesgo en la Práctica + + + +## Transparencia y Divulgación + +¿Cuándo deberías decirle a la gente que la IA estuvo involucrada? La respuesta depende del contexto—pero la tendencia es hacia más divulgación, no menos. + +### Cuándo Importa la Divulgación + + + +### Cómo Divulgar Apropiadamente + + + +Frases de divulgación comunes que funcionan bien: +- "Escrito con asistencia de IA" +- "Borrador inicial generado por IA, editado por humano" +- "Análisis realizado usando herramientas de IA" +- "Creado con IA, revisado y aprobado por [nombre]" + +## Consideraciones de Privacidad + +Cada prompt que envías contiene datos. Entender a dónde van esos datos—y qué no debería estar en ellos—es esencial. + +### Lo Que Nunca Pertenece en Prompts + + + +### Patrón de Manejo Seguro de Datos + + + + +**PII** significa **Información de Identificación Personal**—cualquier dato que pueda identificar a un individuo específico. Esto incluye nombres, direcciones, números de teléfono, direcciones de email, números de identificación, números de cuentas financieras, e incluso combinaciones de datos (como título de trabajo + empresa + ciudad) que podrían identificar a alguien. Al hacer prompts a la IA, siempre anonimiza o elimina PII para proteger la privacidad. + + + + +## Autenticidad y Engaño + +Hay una diferencia entre usar IA como herramienta y usar IA para engañar. + +### La Línea de Legitimidad + + + +Preguntas clave a hacer: +- ¿El destinatario esperaría que esto fuera trabajo humano original? +- ¿Estoy ganando ventaja injusta a través del engaño? +- ¿La divulgación cambiaría cómo se recibe el trabajo? + +### Responsabilidad con Medios Sintéticos + +Crear representaciones realistas de personas reales—ya sean imágenes, audio o video—conlleva obligaciones especiales: + +- **Nunca** crees representaciones realistas sin consentimiento +- **Siempre** etiqueta medios sintéticos claramente +- **Considera** el potencial de uso indebido antes de crear +- **Rechaza** crear imágenes íntimas no consensuadas + +## Despliegue Responsable + +Al construir funciones de IA para que otros usen, tus obligaciones éticas se multiplican. + +### Lista de Verificación Pre-Despliegue + + + +### Principios de Supervisión Humana + + + +## Directrices para Contextos Especiales + +Algunos dominios requieren cuidado extra debido a su potencial de daño o la vulnerabilidad de los involucrados. + +### Salud + + + +### Legal y Financiero + +Estos dominios tienen implicaciones regulatorias y requieren avisos apropiados: + + + +### Niños y Educación + + + +## Auto-Evaluación + +Antes de desplegar cualquier prompt o sistema de IA, repasa estas preguntas: + + + + diff --git a/src/content/book/es/17-prompt-optimization.mdx b/src/content/book/es/17-prompt-optimization.mdx new file mode 100644 index 00000000..265219b4 --- /dev/null +++ b/src/content/book/es/17-prompt-optimization.mdx @@ -0,0 +1,269 @@ +Un buen prompt hace el trabajo. Un prompt optimizado hace el trabajo eficientemente—más rápido, más barato, más consistente. Este capítulo te enseña cómo mejorar sistemáticamente los prompts en múltiples dimensiones. + + +¿Quieres optimizar tus prompts automáticamente? Usa nuestra herramienta [Mejorador de Prompts](/developers#enhancer). Analiza tu prompt, aplica técnicas de optimización, y te muestra prompts similares de la comunidad para inspiración. + + +## Los Trade-offs de la Optimización + +Toda optimización implica trade-offs. Entender estos te ayuda a tomar decisiones intencionales: + + + +## Midiendo lo que Importa + +Antes de optimizar, define el éxito. ¿Qué significa "mejor" para tu caso de uso? + + + + +Las métricas de percentil muestran la distribución del tiempo de respuesta. **p50** (mediana) significa que 50% de las solicitudes son más rápidas que este valor. **p95** significa que 95% son más rápidas—captura los valores atípicos lentos. Si tu p50 es 1s pero p95 es 10s, la mayoría de usuarios están felices pero 5% experimentan retrasos frustrantes. + + + + +## Optimización de Tokens + +Los tokens cuestan dinero y añaden latencia. Así es como decir lo mismo con menos tokens. + +### El Principio de Compresión + + + +**Mismo resultado, 82% menos tokens.** + +### Técnicas para Ahorrar Tokens + + + + + +## Optimización de Calidad + +A veces necesitas mejores salidas, no más baratas. Así es como mejorar la calidad. + +### Potenciadores de Precisión + + + +### Potenciadores de Consistencia + + + + + +## Optimización de Latencia + +Cuando la velocidad importa, cada milisegundo cuenta. + +### Selección de Modelo por Necesidad de Velocidad + + + +### Técnicas de Velocidad + + 100 tokens", exampleType: "text", color: "cyan" }, + { label: "Cachea Agresivamente", description: "No recalcules consultas idénticas", example: "Cachea preguntas comunes, salidas de plantilla", exampleType: "text", color: "cyan" } +]} /> + +## Optimización de Costos + +A escala, pequeños ahorros se multiplican en impacto significativo de presupuesto. + +### Entendiendo los Costos + +Usa esta calculadora para estimar tus costos de API entre diferentes modelos: + + + +### Estrategias de Reducción de Costos + + + +## El Ciclo de Optimización + +La optimización es iterativa. Aquí hay un proceso sistemático: + +### Paso 1: Establecer Línea Base + +No puedes mejorar lo que no mides. Antes de cambiar algo, documenta tu punto de partida rigurosamente. + + + + + +### Paso 2: Formar una Hipótesis + + + +### Paso 3: Probar Un Cambio + +Cambia una cosa a la vez. Ejecuta ambas versiones con las mismas entradas de prueba. Mide las métricas que importan. + +### Paso 4: Analizar y Decidir + +¿Funcionó? Mantén el cambio. ¿Empeoró? Revierte. ¿Fue neutral? Revierte (más simple es mejor). + +### Paso 5: Repetir + +Genera nuevas hipótesis basándote en lo que aprendiste. Sigue iterando hasta que alcances tus objetivos o llegues a rendimientos decrecientes. + +## Lista de Verificación de Optimización + + + + diff --git a/src/content/book/es/18-writing-content.mdx b/src/content/book/es/18-writing-content.mdx new file mode 100644 index 00000000..d87db09c --- /dev/null +++ b/src/content/book/es/18-writing-content.mdx @@ -0,0 +1,393 @@ +La IA destaca en tareas de escritura cuando se le da prompts adecuados. Este capítulo cubre técnicas para varios escenarios de creación de contenido. + + +La IA funciona mejor como herramienta de escritura colaborativa—úsala para generar borradores, luego refina con tu experiencia y voz. + + +## Posts de Blog y Artículos + +### Qué Hacer y Qué No: Prompts de Escritura + + + +### Marco para Posts de Blog + + + +### Tipos de Artículos + +**Artículo Cómo Hacer:** + + +**Listicle:** + + +## Copywriting de Marketing + + +Enfócate en **beneficios sobre características**. En lugar de "Nuestro software usa algoritmos de IA," escribe "Ahorra 10 horas a la semana con informes automatizados." Muestra a los lectores cómo mejoran sus vidas. + + +### Copy de Landing Page + + + +### Secuencias de Email + + + +### Posts de Redes Sociales + + + +## Escritura Técnica + + +**Claridad sobre ingenio.** Usa palabras simples, oraciones cortas y voz activa. Cada oración debería tener un solo trabajo. Si los lectores tienen que releer algo, simplifícalo. + + +### Documentación + + + +### Archivos README + + + +## Escritura Creativa + +### Qué Hacer y Qué No: Prompts Creativos + + + +### Elementos de Historia + + + +### Desarrollo de Personajes + + + +## Edición y Reescritura + +### Edición Comprehensiva + + + +### Transformación de Estilo + + + + + +### Simplificación + + + +## Plantillas de Prompts de prompts.chat + +Aquí hay prompts de escritura populares de la comunidad de prompts.chat: + +### Actúa como un Copywriter + + + +### Actúa como Escritor Técnico + + + +### Actúa como Narrador + + + +## Consejos de Flujo de Trabajo de Escritura + +### 1. Esquema Primero + + + +### 2. Borrador Luego Refinar + + + +### 3. Coincidencia de Voz + + + +## Resumen + + +Especifica audiencia y propósito claramente, define estructura y formato, incluye directrices de estilo, proporciona ejemplos cuando sea posible, y solicita entregables específicos. + + + + +Escribir con IA funciona mejor como colaboración—deja que la IA genere borradores, luego refina con tu experiencia y voz. diff --git a/src/content/book/es/19-programming-development.mdx b/src/content/book/es/19-programming-development.mdx new file mode 100644 index 00000000..7ff3f726 --- /dev/null +++ b/src/content/book/es/19-programming-development.mdx @@ -0,0 +1,413 @@ +La IA ha transformado el desarrollo de software. Este capítulo cubre técnicas de prompting para generación de código, depuración, revisión y flujos de trabajo de desarrollo. + + +La IA destaca en generación de código, depuración y documentación—pero siempre revisa el código generado por seguridad, corrección y mantenibilidad. Nunca despliegues código de IA sin probar. + + +## Generación de Código + +### Qué Hacer y Qué No: Prompts de Código + + + +### Generación de Funciones + + + +### Generación de Clases/Módulos + + + +### Generación de Endpoints API + + + +## Depuración + + +Siempre incluye el **comportamiento esperado**, **comportamiento actual**, y **mensaje de error** (si hay alguno). Cuanto más contexto proporciones, más rápido la IA puede identificar la causa raíz. + + +### Análisis de Bugs + + + +### Interpretación de Mensajes de Error + + + +### Depuración de Rendimiento + + + +## Revisión de Código + +### Qué Hacer y Qué No: Prompts de Revisión de Código + + + +### Revisión Comprehensiva + + + +### Revisión de Seguridad + + + +## Refactorización + +### Detección de Code Smells + + + +### Aplicación de Patrones de Diseño + + + +## Pruebas + +### Generación de Pruebas Unitarias + + + +### Generación de Casos de Prueba + + + +## Arquitectura y Diseño + +### Diseño de Sistema + + + +### Diseño de Esquema de Base de Datos + + + +## Generación de Documentación + +### Documentación de API + + + +### Documentación en Línea + + + +## Plantillas de Prompts de prompts.chat + +### Actúa como Desarrollador Senior + +``` +Quiero que actúes como un desarrollador de software senior. Te +proporcionaré código y haré preguntas sobre él. Revisarás el código, +sugerirás mejoras, explicarás conceptos, y ayudarás a depurar +problemas. Tus respuestas deben ser educativas y ayudarme a +convertirme en un mejor desarrollador. +``` + +### Actúa como Revisor de Código + +``` +Quiero que actúes como un revisor de código. Te proporcionaré pull +requests con cambios de código, y los revisarás exhaustivamente. +Verifica bugs, problemas de seguridad, problemas de rendimiento, y +adherencia a mejores prácticas. Proporciona retroalimentación +constructiva que ayude al desarrollador a mejorar. +``` + +### Actúa como Arquitecto de Software + +``` +Quiero que actúes como un arquitecto de software. Describiré +requisitos y restricciones del sistema, y diseñarás arquitecturas +escalables y mantenibles. Explica tus decisiones de diseño, +trade-offs, y proporciona diagramas donde sea útil. +``` + +## Integración de Flujo de Trabajo de Desarrollo + +### Generación de Mensajes de Commit + + + +### Generación de Descripción de PR + + + +## Resumen + + +Incluye contexto completo (lenguaje, framework, restricciones), especifica requisitos precisamente, solicita formatos de salida específicos, pide explicaciones junto con el código, e incluye casos límite a manejar. + + + + +La IA es una poderosa compañera de código—úsala para generación, revisión, depuración y documentación mientras mantienes tu juicio arquitectónico. diff --git a/src/content/book/es/20-education-learning.mdx b/src/content/book/es/20-education-learning.mdx new file mode 100644 index 00000000..1ff7d939 --- /dev/null +++ b/src/content/book/es/20-education-learning.mdx @@ -0,0 +1,345 @@ +La IA es una herramienta poderosa tanto para enseñar como para aprender. Este capítulo cubre prompts para contextos educativos—desde tutoría personalizada hasta desarrollo curricular. + + +La IA destaca como tutora paciente y adaptativa que puede explicar conceptos de múltiples formas, generar problemas de práctica ilimitados, y proporcionar retroalimentación instantánea—disponible 24/7. + + +## Aprendizaje Personalizado + +### Qué Hacer y Qué No: Prompts de Aprendizaje + + + +### Explicación de Conceptos + + + +### Tutoría Adaptativa + + + +### Creación de Ruta de Aprendizaje + + + +## Asistencia de Estudio + + +No solo leas explicaciones de IA pasivamente. Pídele que te examine, genere problemas, y verifique tu comprensión. **El recuerdo activo supera la revisión pasiva.** + + +### Generación de Resúmenes + + + +### Generación de Tarjetas de Estudio + + + +### Problemas de Práctica + + + +## Herramientas de Enseñanza + +### Creación de Plan de Lección + + + +### Diseño de Tareas + + + +### Generación de Exámenes + + + +## Contextos de Aprendizaje Especializados + +### Aprendizaje de Idiomas + + + +### Desarrollo de Habilidades + + + +### Preparación de Exámenes + + + +## Plantillas de Prompts de prompts.chat + +### Actúa como Tutor Socrático + + + +### Actúa como Creador de Contenido Educativo + + + +### Actúa como Compañero de Estudio + + + +## Accesibilidad en Educación + +### Adaptación de Contenido + + + +### Múltiples Modalidades + + + +## Evaluación y Retroalimentación + +### Proporcionar Retroalimentación + + + +### Prompts de Auto-Evaluación + + + +## Resumen + + +Adáptate al nivel del aprendiz, divide temas complejos en pasos, incluye práctica activa (no solo explicación), proporciona enfoques variados, verifica comprensión regularmente, y da retroalimentación constructiva. + + + + +La IA es una compañera de aprendizaje paciente y siempre disponible—úsala para complementar, no reemplazar, la instrucción humana. diff --git a/src/content/book/es/21-business-productivity.mdx b/src/content/book/es/21-business-productivity.mdx new file mode 100644 index 00000000..1e383e8c --- /dev/null +++ b/src/content/book/es/21-business-productivity.mdx @@ -0,0 +1,335 @@ +La IA puede mejorar dramáticamente la productividad profesional. Este capítulo cubre prompts para comunicación empresarial, análisis, planificación y optimización de flujos de trabajo. + + +La IA destaca en redacción, análisis y estructuración—liberándote para enfocarte en estrategia, relaciones y decisiones que requieren juicio humano. + + +## Comunicación Empresarial + +### Qué Hacer y Qué No: Emails de Negocios + + + +### Redacción de Emails + + + +**Ejemplos por propósito:** + + + + + + + +### Contenido de Presentación + + + +### Redacción de Informes + + + +## Análisis y Toma de Decisiones + + +La IA puede estructurar tu pensamiento, pero **tú proporcionas el contexto del mundo real**. Los mejores análisis combinan los marcos de la IA con tu conocimiento del dominio. + + +### Análisis FODA + + + +### Marco de Decisión + + + +### Análisis Competitivo + + + +## Planificación y Estrategia + +### Establecimiento de Metas (OKRs) + + + +### Planificación de Proyectos + + + +### Agenda de Reunión + + + +## Flujos de Trabajo de Productividad + +### Priorización de Tareas + + + +### Documentación de Procesos + + + +### Procedimiento Operativo Estándar + + + +## Plantillas de Comunicación + +### Actualización a Stakeholders + + + +### Solicitud de Retroalimentación + + + +## Plantillas de Prompts de prompts.chat + +### Actúa como Consultor de Negocios + + + +### Actúa como Facilitador de Reuniones + + + +## Resumen + + +Especifica la audiencia y sus necesidades, define el resultado deseado claramente, incluye contexto y restricciones relevantes, solicita formatos y estructuras específicas, y considera requisitos de tono profesional. + + + + +La IA puede manejar comunicación de negocios rutinaria mientras tú te enfocas en estrategia y relaciones. diff --git a/src/content/book/es/22-creative-arts.mdx b/src/content/book/es/22-creative-arts.mdx new file mode 100644 index 00000000..fb6056ea --- /dev/null +++ b/src/content/book/es/22-creative-arts.mdx @@ -0,0 +1,327 @@ +La IA es un poderoso colaborador creativo. Este capítulo cubre técnicas de prompting para artes visuales, música, diseño de juegos y otros dominios creativos. + + +La IA expande tus posibilidades creativas—úsala para explorar variaciones, superar bloqueos y generar opciones. La visión creativa y las decisiones finales siguen siendo tuyas. + + +## Arte Visual y Diseño + +### Qué Hacer y Qué No: Prompts de Imagen + + + +### Elaboración de Prompts de Imagen + +Al trabajar con modelos de generación de imágenes (DALL-E, Midjourney, Stable Diffusion): + + + +### Dirección de Arte + + + +### Crítica de Diseño + + + +## Escritura Creativa + + +**Las restricciones alimentan la creatividad.** Un prompt como "escribe cualquier cosa" produce resultados genéricos. Restricciones específicas como género, tono y estructura fuerzan soluciones inesperadas e interesantes. + + +### Construcción de Mundos + + + +### Desarrollo de Trama + + + +### Escritura de Diálogo + + + +## Música y Audio + +### Estructura de Canción + + + +### Descripción de Diseño de Sonido + + + +## Diseño de Juegos + +### Diseño de Mecánica de Juego + + + +### Diseño de Niveles + + + +### Diseño de Personaje/Enemigo + + + +## Lluvia de Ideas e Ideación + +### Lluvia de Ideas Creativa + + + +### Restricciones Creativas + + + +### Exploración de Estilos + + + +## Plantillas de Prompts de prompts.chat + +### Actúa como Director Creativo + + + +### Actúa como Constructor de Mundos + + + +### Actúa como Dungeon Master + + + +## Consejos de Colaboración Creativa + +### Construyendo sobre Ideas + + + +### Retroalimentación Creativa + + + +## Resumen + + +Proporciona suficiente estructura para guiar sin restringir, abraza la especificidad (vago = genérico), incluye referencias e inspiraciones, solicita variaciones y alternativas, y mantén tu visión creativa mientras exploras posibilidades. + + + + +La IA es una colaboradora, no un reemplazo de la visión creativa. Úsala para explorar, generar opciones y superar bloqueos—pero las decisiones creativas siguen siendo tuyas. diff --git a/src/content/book/es/23-research-analysis.mdx b/src/content/book/es/23-research-analysis.mdx new file mode 100644 index 00000000..78d79752 --- /dev/null +++ b/src/content/book/es/23-research-analysis.mdx @@ -0,0 +1,323 @@ +La IA puede acelerar flujos de trabajo de investigación desde revisión de literatura hasta análisis de datos. Este capítulo cubre técnicas de prompting para investigación académica y profesional. + + +La IA puede asistir con síntesis, análisis y escritura—pero no puede reemplazar el pensamiento crítico, juicio ético o experiencia de dominio. Siempre verifica las afirmaciones y cita fuentes originales. + + +## Revisión de Literatura e Información + +### Qué Hacer y Qué No: Prompts de Investigación + + + +### Resumen de Artículos + + + +### Síntesis de Literatura + + + +### Desarrollo de Preguntas de Investigación + + + +## Análisis de Datos + + +La IA puede guiar la metodología y ayudar a interpretar resultados, pero no puede acceder o procesar tus conjuntos de datos reales. Nunca pegues datos de investigación sensibles en prompts. Usa la IA para **orientación**, no para cómputo. + + +### Orientación de Análisis Estadístico + + + +### Análisis Cualitativo + + + +### Interpretación de Datos + + + +## Marcos de Análisis Estructurado + +### Análisis PESTLE + + + +### Análisis de Causa Raíz + + + +### Análisis de Brechas + + + +## Apoyo a Escritura Académica + +### Estructura de Argumento + + + +### Sección de Métodos + + + +### Sección de Discusión + + + +## Análisis Crítico + +### Evaluación de Fuentes + + + +### Análisis de Argumentos + + + +## Plantillas de Prompts de prompts.chat + +### Actúa como Asistente de Investigación + + + +### Actúa como Analista de Datos + + + +### Actúa como Revisor de Pares + + + +## Resumen + + +Declara claramente el contexto y metas de investigación, especifica el marco analítico a usar, solicita reconocimiento de limitaciones, pide razonamiento basado en evidencia, y mantén rigor y honestidad académica. + + + + +Recuerda: La IA puede asistir la investigación pero no puede reemplazar el pensamiento crítico, juicio ético o experiencia de dominio. Siempre verifica afirmaciones independientemente. diff --git a/src/content/book/es/24-future-of-prompting.mdx b/src/content/book/es/24-future-of-prompting.mdx new file mode 100644 index 00000000..7942db86 --- /dev/null +++ b/src/content/book/es/24-future-of-prompting.mdx @@ -0,0 +1,445 @@ +A medida que la IA continúa evolucionando a un ritmo sin precedentes, también lo hará el arte y la ciencia del prompting. Este capítulo final explora tendencias emergentes, el panorama cambiante de la colaboración humano-IA, y cómo mantenerse adelante mientras el campo se transforma. + + +Las técnicas en este libro representan mejores prácticas actuales, pero las capacidades de IA cambian rápidamente. Los principios de comunicación clara, pensamiento estructurado y refinamiento iterativo seguirán siendo valiosos incluso mientras las tácticas específicas evolucionan. + + +## El Panorama en Evolución + +### De Prompts a Conversaciones + +El prompting temprano era transaccional—una entrada única produciendo una salida única. La interacción moderna con IA es cada vez más **conversacional y colaborativa**: + +- **Refinamiento multi-turno** - Construyendo comprensión a través de intercambios +- **Contexto persistente** - Sistemas que recuerdan y aprenden de interacciones +- **Flujos de trabajo agénticos** - IA que puede planificar, ejecutar e iterar autónomamente +- **Uso de herramientas** - Modelos que pueden buscar, calcular e interactuar con sistemas externos + + + +### El Auge de la Ingeniería de Contexto + +Como se cubrió en el Capítulo 14, el prompting se está expandiendo más allá de instrucciones individuales para abarcar **ingeniería de contexto**—la gestión estratégica de qué información puede acceder una IA: + +- **RAG (Generación Aumentada por Recuperación)** - Recuperación dinámica de conocimiento +- **Llamadas a funciones** - Integración estructurada de herramientas +- **MCP (Protocolo de Contexto de Modelo)** - Compartición estandarizada de contexto +- **Sistemas de memoria** - Conocimiento persistente entre sesiones + +El ingeniero de prompts del futuro piensa no solo en *qué decir* sino en *qué contexto proporcionar*. + +### Multimodal por Defecto + +La interacción solo de texto se está convirtiendo en la excepción. Los sistemas de IA del futuro manejarán sin problemas: + +- **Imágenes y video** - Comprensión y generación de contenido visual +- **Audio y voz** - Interacción natural por habla +- **Documentos y archivos** - Procesamiento directo de materiales complejos +- **Interacción con el mundo real** - Robótica y sistemas físicos + +Las habilidades de prompting se extenderán a guiar la percepción de IA y la acción física. + +## El Futuro Agéntico + +El cambio más significativo en IA es el auge de los **agentes**—sistemas de IA que no solo responden a prompts sino que persiguen activamente objetivos, toman decisiones y realizan acciones en el mundo. + +### ¿Qué Son los Agentes de IA? + +Un agente de IA es un sistema que: + +- **Percibe** su entorno a través de entradas (texto, imágenes, datos, APIs) +- **Razona** sobre qué hacer usando un LLM como su "cerebro" +- **Actúa** llamando herramientas, escribiendo código o interactuando con sistemas +- **Aprende** de la retroalimentación y ajusta su enfoque + + +Los chatbots tradicionales esperan entrada y responden. Los agentes toman iniciativa—planifican tareas de múltiples pasos, usan herramientas autónomamente, se recuperan de errores, y persisten hasta que los objetivos se logran. + + +### El Rol de los Prompts en Agentes + +En un mundo agéntico, los prompts se vuelven aún más críticos—pero sirven propósitos diferentes: + +
+
+

Prompts de Sistema

+

Definen la identidad, capacidades, restricciones y directrices de comportamiento del agente. Estos son la "constitución" del agente.

+
+
+

Prompts de Planificación

+

Guían cómo los agentes descomponen objetivos complejos en pasos accionables. Críticos para razonamiento multi-paso.

+
+
+

Prompts de Uso de Herramientas

+

Describen herramientas disponibles y cuándo/cómo usarlas. Los agentes deben entender sus capacidades.

+
+
+

Prompts de Reflexión

+

Permiten a los agentes evaluar sus propias salidas, detectar errores, y mejorar iterativamente.

+
+
+ +### Patrones de Arquitectura de Agentes + +Los agentes modernos siguen patrones reconocibles. Entender estos te ayuda a diseñar sistemas de agentes efectivos: + +**ReAct (Razonamiento + Acción)** + +El agente alterna entre razonar sobre qué hacer y tomar acciones: + +
+
+
+

Pensar

+
+
→
+
+

Actuar

+
+
→
+
+

Observar

+
+
→
+
(repetir)
+
+
+ +**Planificar-y-Ejecutar** + +El agente crea un plan completo primero, luego ejecuta los pasos: + +
+
+

Crear Plan

+

Dividir objetivo en pasos

+
+
↓
+
+
+

Paso 1

+
+
→
+
+

Paso 2

+
+
→
+
+

Paso 3

+
+
→
+
...
+
+
↓
+
+

Revisar si es Necesario

+

Adaptar plan basado en resultados

+
+
+ +### Prompting para Agentes + +Al diseñar prompts para sistemas de agentes, considera: + + + +### Sistemas Multi-Agente + +El futuro involucra equipos de agentes especializados trabajando juntos: + +
+
+
+
+

Coordinador

+

Gestiona flujo de trabajo

+
+
+
⟷
+
↕
+
+
+

Investigador

+
+
+

Escritor

+
+
+

Crítico

+
+
+

Programador

+
+
+
+
+ +Cada agente tiene su propio prompt de sistema definiendo su rol, y se comunican a través de mensajes estructurados. El trabajo del ingeniero de prompts se convierte en **diseñar el equipo**—definiendo roles, protocolos de comunicación y estrategias de coordinación. + + +En un futuro agéntico, los ingenieros de prompts se convierten en arquitectos de sistemas. No solo estás escribiendo instrucciones—estás diseñando sistemas autónomos que pueden razonar, planificar y actuar. Las habilidades que has aprendido en este libro son la base para esta nueva disciplina. + + +## Patrones Emergentes + +### Orquestación de Prompts + +Los prompts individuales están dando paso a **sistemas orquestados**: + +
+
+

Solicitud del Usuario

+
+
↓
+
+

Agente Planificador

+

Descompone la tarea

+
+
↓
+
+

Agente Investigador

+

Recopila información

+
+
↓
+
+

Agente Escritor

+

Crea contenido

+
+
↓
+
+

Agente Revisor

+

Verificación de calidad

+
+
↓
+
+

Salida Final

+
+
+ +Los profesionales del futuro diseñarán *sistemas* de prompts en lugar de prompts individuales. + +### Prompts Auto-Mejorables + +Los sistemas de IA están comenzando a: + +- **Optimizar sus propios prompts** - Meta-aprendizaje para mejores instrucciones +- **Aprender de retroalimentación** - Adaptándose basándose en resultados +- **Generar datos de entrenamiento** - Creando ejemplos para ajuste fino +- **Evaluarse a sí mismos** - Incorporando evaluación de calidad + + + +### Programación en Lenguaje Natural + +La línea entre prompting y programación se está difuminando: + +- **Prompts como código** - Versionados, probados, desplegados +- **LLMs como intérpretes** - Lenguaje natural como instrucciones ejecutables +- **Sistemas híbridos** - Combinando código tradicional con razonamiento de IA +- **Desarrollo asistido por IA** - Modelos que escriben y depuran código + +Entender prompting significa cada vez más entender desarrollo de software. + +## Habilidades para el Futuro + +### Lo Que Seguirá Siendo Valioso + +Ciertas habilidades seguirán siendo esenciales sin importar cómo evolucione la IA: + +1. **Pensamiento claro** - Saber lo que realmente quieres +2. **Experiencia de dominio** - Entender el espacio del problema +3. **Evaluación crítica** - Evaluar la calidad de salida de IA +4. **Juicio ético** - Saber lo que *debería* hacerse +5. **Refinamiento iterativo** - Mentalidad de mejora continua + +### Lo Que Cambiará + +Otros aspectos cambiarán significativamente: + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
HoyMañana
Escribir prompts detalladosDiseñar sistemas de agentes
Optimización manual de promptsAjuste automatizado de prompts
Experiencia en un solo modeloOrquestación multi-modelo
Interacción enfocada en textoFluidez multimodal
Productividad individualColaboración equipo-IA
+
+ +### Manteniéndose Actualizado + +Para mantener tus habilidades relevantes: + +- **Experimenta continuamente** - Prueba nuevos modelos y características cuando se lancen +- **Sigue la investigación** - Mantente al tanto de desarrollos académicos +- **Únete a comunidades** - Aprende de otros profesionales +- **Construye proyectos** - Aplica habilidades a problemas reales +- **Enseña a otros** - Solidifica comprensión explicando + +## El Elemento Humano + +### IA como Amplificador + +En su mejor momento, la IA amplifica la capacidad humana en lugar de reemplazarla: + +- **Los expertos se vuelven más expertos** - IA maneja trabajo rutinario, humanos se enfocan en insight +- **La creatividad se expande** - Más ideas exploradas, más posibilidades probadas +- **El acceso se democratiza** - Capacidades que antes requerían especialistas están disponibles para todos +- **La colaboración se profundiza** - Equipos humano-IA superan a cualquiera por separado + +### El Humano Irremplazable + +Ciertas cualidades siguen siendo distintivamente humanas: + +- **Experiencia original** - Vivir en el mundo, tener emociones y relaciones +- **Valores y ética** - Decidir qué importa y qué es correcto +- **Responsabilidad** - Asumir responsabilidad por los resultados +- **Creación de significado** - Entender *por qué* algo importa +- **Creatividad genuina** - Verdadera novedad nacida de perspectiva única + + +A medida que la IA maneja más tareas cognitivas rutinarias, tu valor único reside en juicio, creatividad, experiencia de dominio, y las conexiones humanas que la IA no puede replicar. Invierte en lo que te hace irremplazable. + + +## Reflexiones Finales + +### Lo Que Hemos Aprendido + +A lo largo de este libro, hemos explorado: + +- **Fundamentos** - Cómo funcionan los modelos de IA y qué hace efectivos a los prompts +- **Técnicas** - Prompting basado en roles, cadena de pensamiento, aprendizaje few-shot, y más +- **Estrategias avanzadas** - Prompts de sistema, encadenamiento de prompts, interacción multimodal +- **Mejores prácticas** - Evitar errores, consideraciones éticas, optimización +- **Aplicaciones** - Escritura, programación, educación, negocios, creatividad, investigación + +Estas técnicas comparten hilos comunes: + +1. **Sé claro y específico** - Sabe lo que quieres y comunícalo con precisión +2. **Proporciona contexto** - Dale a la IA la información que necesita +3. **Estructura tus solicitudes** - La organización mejora las salidas +4. **Itera y refina** - Los primeros intentos son puntos de partida, no puntos finales +5. **Evalúa críticamente** - La salida de IA requiere juicio humano + +### El Arte y la Ciencia + +El prompting es tanto **arte como ciencia**: + +- **Ciencia**: Hipótesis comprobables, resultados medibles, técnicas reproducibles +- **Arte**: Intuición, creatividad, saber cuándo romper las reglas + +Los mejores profesionales combinan metodología rigurosa con experimentación creativa. Prueban sistemáticamente pero también confían en sus instintos. Siguen mejores prácticas pero saben cuándo desviarse. + +### Un Llamado a Crear + +Este libro te ha dado herramientas. Lo que construyas con ellas depende de ti. + +- **Resuelve problemas** que te importen a ti y a otros +- **Crea cosas** que no existían antes +- **Ayuda a personas** a hacer cosas que no podían hacer solas +- **Empuja límites** de lo que es posible +- **Mantente curioso** mientras el campo evoluciona + +La era de la IA apenas está comenzando. Las aplicaciones más importantes aún no se han inventado. Las técnicas más poderosas aún no se han descubierto. El futuro se está escribiendo ahora—por personas como tú, un prompt a la vez. + +## Mirando Hacia Adelante + + + + +Visita [prompts.chat](https://prompts.chat) para prompts de la comunidad, nuevas técnicas, y para compartir tus propios descubrimientos. El mejor aprendizaje sucede en comunidad. + + +## Resumen + + +La IA continuará evolucionando rápidamente, pero las habilidades centrales de comunicación clara, pensamiento crítico, y refinamiento iterativo siguen siendo valiosas. Enfócate en lo que te hace irremplazable: juicio, creatividad, ética, y conexión humana genuina. El futuro del prompting es colaborativo, multimodal, e integrado en sistemas más grandes. Mantente curioso, sigue experimentando, y construye cosas que importen. + + + + +Gracias por leer *El Libro Interactivo de Prompting*. Ahora ve y crea algo asombroso. diff --git a/src/content/book/es/25-agents-and-skills.mdx b/src/content/book/es/25-agents-and-skills.mdx new file mode 100644 index 00000000..4b8fed97 --- /dev/null +++ b/src/content/book/es/25-agents-and-skills.mdx @@ -0,0 +1,551 @@ +A medida que los sistemas de IA evolucionan de simples respuestas a preguntas hacia la ejecución autónoma de tareas, entender los **agentes** y las **habilidades (skills)** se vuelve esencial. Este capítulo explora cómo los prompts sirven como los bloques de construcción fundamentales para agentes de IA, y cómo las habilidades empaquetan experiencia en conjuntos de instrucciones reutilizables y completos. + +
+
+
+
+ +
+

Agente

+

Sistema de IA autónomo

+
+
+ impulsado por + ↓ +
+
+
+
+ +
+

Skill

+

Experiencia reutilizable

+
+
+
+ +
+

Skill

+

Experiencia reutilizable

+
+
+
+ +
+

Skill

+

Experiencia reutilizable

+
+
+
+ compuesto de + ↓ +
+
+
+ + Prompt +
+
+ + Prompt +
+
+ + Prompt +
+
+ + Prompt +
+
+ + Prompt +
+
+

Los Prompts son átomos → Los Skills son moléculas → Los Agentes son estructuras completas

+
+
+ +## ¿Qué Son los Agentes de IA? + +Un **agente de IA** es un sistema de IA que puede planificar, ejecutar e iterar autónomamente sobre tareas. A diferencia de las interacciones simples de prompt-respuesta, los agentes pueden: + +- **Planificar** - Descomponer objetivos complejos en pasos accionables +- **Ejecutar** - Usar herramientas y tomar acciones en el mundo real +- **Observar** - Procesar retroalimentación de sus acciones +- **Adaptar** - Ajustar su enfoque basándose en resultados +- **Persistir** - Mantener contexto y memoria entre interacciones + +
+
+
+
+

Objetivo

+
+
→
+
+
+
+

Planificar

+
+
→
+
+

Ejecutar

+
+
→
+
+

Observar

+
+
→
+
+

Adaptar

+
+
+
+ ↺ Repetir hasta completar +
+
+
→
+
+

Listo

+
+
+
+
+ +## Prompts como Bloques de Construcción + +Cada agente, sin importar cuán sofisticado sea, está construido de prompts. Así como los átomos se combinan para formar moléculas, y las moléculas se combinan para formar estructuras complejas, los prompts se combinan para crear comportamiento inteligente de agentes. + +
+
+

Prompts de Sistema

+

Identidad y Rol

+
+
+

Prompts de Planificación

+

Cómo Pensar

+
+
+

Prompts de Herramientas

+

Cómo Actuar

+
+
+

Prompts de Recuperación

+

Cómo Recuperarse

+
+
+ +Estos tipos de prompts se apilan juntos para formar el comportamiento completo del agente: + +### Prompts de Sistema (La Identidad del Agente) + +El prompt fundamental que establece quién es el agente y cómo se comporta: + +```markdown +Eres un asistente de revisión de código. Tu rol es: +- Analizar código buscando bugs, problemas de seguridad y de rendimiento +- Sugerir mejoras siguiendo mejores prácticas +- Explicar tu razonamiento claramente +- Ser constructivo y educativo en la retroalimentación + +Tienes acceso a herramientas para leer archivos, buscar código y ejecutar pruebas. +``` + +### Prompts de Planificación (Cómo Pensar) + +Instrucciones que guían el proceso de razonamiento y planificación del agente: + +```markdown +Antes de tomar acción, siempre: +1. Entiende la solicitud completa +2. Divídela en pasos más pequeños y verificables +3. Identifica qué herramientas necesitarás +4. Considera casos límite y problemas potenciales +5. Ejecuta paso a paso, validando mientras avanzas +``` + +### Prompts de Uso de Herramientas (Cómo Actuar) + +Orientación sobre cuándo y cómo usar las herramientas disponibles: + +```markdown +Cuando necesites entender un código base: +- Usa grep_search para encontrar patrones específicos +- Usa read_file para examinar contenidos de archivos +- Usa list_dir para explorar estructura de directorios +- Siempre verifica tu comprensión antes de hacer cambios +``` + +### Prompts de Recuperación (Cómo Manejar Fallos) + +Instrucciones para cuando las cosas salen mal: + +```markdown +Si una acción falla: +1. Analiza el mensaje de error cuidadosamente +2. Considera enfoques alternativos +3. Pide clarificación si la tarea es ambigua +4. Nunca repitas la misma acción fallida sin cambios +``` + + +El comportamiento de un agente emerge de capas de prompts trabajando juntos. El prompt de sistema establece la base, los prompts de planificación guían el razonamiento, los prompts de herramientas habilitan la acción, y los prompts de recuperación manejan los fallos. Juntos, crean comportamiento coherente y capaz. + + +## ¿Qué Son los Skills? + +Si los prompts son los átomos, **los skills son las moléculas**—bloques de construcción reutilizables que dan a los agentes capacidades específicas. + +Un **skill** es un paquete completo y portátil de instrucciones que da a un agente de IA experiencia en un dominio o tarea específica. Los skills son los bloques reutilizables de los agentes: los construyes una vez, y cualquier agente puede usarlos. + + +Escribe un skill para revisión de código una vez. Ahora cada agente de programación—ya sea para Python, JavaScript o Rust—puede convertirse instantáneamente en un revisor de código experto cargando ese skill. Los skills te permiten construir capacidades de agentes como bloques LEGO. + + +### Anatomía de un Skill + +Un skill bien diseñado típicamente incluye: + +
+
+

📄 SKILL.md (Requerido)

+

El archivo de instrucciones principal. Contiene la experiencia central, directrices y comportamientos que definen el skill.

+
+
+

📚 Documentación de Referencia

+

Documentación de apoyo, ejemplos y contexto que el agente puede referenciar mientras trabaja.

+
+
+

🔧 Scripts y Herramientas

+

Scripts auxiliares, plantillas o configuraciones de herramientas que apoyan la funcionalidad del skill.

+
+
+

⚙️ Configuración

+

Ajustes, parámetros y opciones de personalización para adaptar el skill a diferentes contextos.

+
+
+ +### Ejemplo: Skill de Revisión de Código + +Así es como podría verse un skill de revisión de código: + +
+
+ 📁 + code-review-skill/ +
+
+
+ 📄 + SKILL.md + Directrices de revisión +
+
+ 📄 + security-checklist.md + Patrones de seguridad +
+
+ 📄 + performance-tips.md + Guía de optimización +
+
+
+ 📁 + language-specific/ +
+
+
+ 📄 + python.md + Mejores prácticas Python +
+
+ 📄 + javascript.md + Patrones JavaScript +
+
+ 📄 + rust.md + Directrices Rust +
+
+
+
+
+ +El archivo `SKILL.md` define el enfoque general: + +```markdown +--- +name: code-review +description: Revisión de código completa con análisis de seguridad, rendimiento y estilo +--- + +# Skill de Revisión de Código + +Eres un revisor de código experto. Al revisar código: + +## Proceso +1. **Entender Contexto** - ¿Qué hace este código? ¿Qué problema resuelve? +2. **Verificar Corrección** - ¿Funciona? ¿Hay errores lógicos? +3. **Escaneo de Seguridad** - Referencia security-checklist.md para vulnerabilidades comunes +4. **Revisión de Rendimiento** - Revisa performance-tips.md para oportunidades de optimización +5. **Estilo y Mantenibilidad** - ¿Es el código legible y mantenible? + +## Formato de Salida +Proporciona retroalimentación en categorías: +- 🔴 **Crítico** - Debe corregirse antes de merge +- 🟡 **Sugerido** - Mejoras recomendadas +- 🟢 **Opcional** - Mejoras opcionales + +Siempre explica *por qué* algo es un problema, no solo *qué* está mal. +``` + +## Skills vs. Prompts Simples + +
+
+

Prompt Simple

+
+

Instrucción única

+

Uso de una sola vez

+

Contexto limitado

+

Enfoque genérico

+

Sin materiales de apoyo

+
+
+
+

Skill

+
+

Conjunto completo de instrucciones

+

Reutilizable entre proyectos

+

Contexto rico con referencias

+

Experiencia específica de dominio

+

Docs, scripts, configs de apoyo

+
+
+
+ +## Construyendo Skills Efectivos + +### 1. Define la Experiencia Claramente + +Comienza con una descripción clara de lo que habilita el skill: + +```markdown +--- +name: api-design +description: Diseña APIs RESTful siguiendo mejores prácticas de la industria, + incluyendo versionado, manejo de errores, y estándares de documentación +--- +``` + +### 2. Estructura el Conocimiento Jerárquicamente + +Organiza la información de lo general a lo específico: + +```markdown +# Skill de Diseño de API + +## Principios Centrales +- Los recursos deben ser sustantivos, no verbos +- Usa métodos HTTP semánticamente +- Versiona tus APIs desde el día uno + +## Directrices Detalladas +[Reglas más específicas...] + +## Materiales de Referencia +- Ver `rest-conventions.md` para convenciones de nombres +- Ver `error-codes.md` para respuestas de error estándar +``` + +### 3. Incluye Ejemplos Concretos + +Las reglas abstractas se aclaran con ejemplos: + +```markdown +## Nombres de Endpoints + +✅ Bueno: +- GET /users/{id} +- POST /orders +- DELETE /products/{id}/reviews/{reviewId} + +❌ Evitar: +- GET /getUser +- POST /createNewOrder +- DELETE /removeProductReview +``` + +### 4. Proporciona Marcos de Decisión + +Ayuda al agente a tomar decisiones en situaciones ambiguas: + +```markdown +## Cuándo Usar Paginación + +Usa paginación cuando: +- La colección podría exceder 100 elementos +- El tamaño de respuesta impacta el rendimiento +- El cliente puede no necesitar todos los elementos + +Usa respuesta completa cuando: +- La colección siempre es pequeña (<20 elementos) +- El cliente típicamente necesita todo +- La consistencia en tiempo real es crítica +``` + +### 5. Añade Patrones de Recuperación + +Anticipa qué puede salir mal: + +```markdown +## Problemas Comunes + +**Problema**: El cliente necesita campos que no están en la respuesta estándar +**Solución**: Implementa selección de campos: GET /users?fields=id,name,email + +**Problema**: Se necesitan cambios incompatibles +**Solución**: Crea nueva versión, depreca la anterior con línea de tiempo +``` + +## Componiendo Skills + +Los agentes se vuelven poderosos cuando múltiples skills trabajan juntos. Considera cómo los skills pueden complementarse entre sí: + +
+
+ Revisión de Código +
+
+
+
+ Auditoría de Seguridad +
+
+
+
+ Documentación +
+
=
+
+ Agente de Calidad de Código Completo +
+
+ +Al componer skills, asegúrate de que no entren en conflicto. Los skills deben ser: + +- **Modulares** - Cada skill maneja bien un dominio +- **Compatibles** - Los skills no deben dar instrucciones contradictorias +- **Priorizados** - Cuando los skills se superponen, define cuál tiene precedencia + +## Compartiendo y Descubriendo Skills + +Los skills son más valiosos cuando se comparten. Plataformas como [prompts.chat](https://prompts.chat/skills) te permiten: + +- **Descubrir** skills creados por la comunidad para tareas comunes +- **Descargar** skills directamente a tus proyectos +- **Compartir** tu propia experiencia como skills reutilizables +- **Iterar** en skills basándote en uso del mundo real + + +Antes de construir un skill desde cero, verifica si alguien ya resolvió tu problema. Los skills de la comunidad están probados en batalla y a menudo son mejores que empezar de cero. + + +## El Ecosistema Agente-Skill + +La relación entre agentes y skills crea un ecosistema poderoso: + +
+
+ Agente de IA +
+
+
+

Revisión de Código

+

Skill 1

+
+
+

Diseño de API

+

Skill 2

+
+
+

Escritura de Tests

+

Skill 3

+
+
+
+
↓
+
+
+
+

Prompts Centrales

+

Planificación • Herramientas • Recuperación • Memoria

+
+
+
+ +El agente proporciona el marco de ejecución—planificación, uso de herramientas y memoria—mientras los skills proporcionan experiencia de dominio. Esta separación significa: + +- **Los skills son portátiles** - El mismo skill funciona con diferentes agentes +- **Los agentes son extensibles** - Añade nuevas capacidades agregando skills +- **La experiencia es compartible** - Expertos de dominio pueden contribuir skills sin construir agentes completos + +## Mejores Prácticas + +### Para Construir Skills + +1. **Empieza específico, luego generaliza** - Construye un skill para tu caso de uso exacto primero, luego abstrae +2. **Incluye casos de fallo** - Documenta lo que el skill no puede hacer y cómo manejarlo +3. **Versiona tus skills** - Rastrea cambios para que los agentes puedan depender de versiones estables +4. **Prueba con tareas reales** - Valida skills contra trabajo real, no solo teoría + +### Para Usar Skills con Agentes + +1. **Lee el skill primero** - Entiende lo que hace un skill antes de desplegarlo +2. **Personaliza con cuidado** - Sobrescribe valores predeterminados del skill solo cuando sea necesario +3. **Monitorea el rendimiento** - Rastrea qué tan bien funcionan los skills en tu contexto +4. **Contribuye mejoras** - Cuando mejores un skill, considera compartirlo + + +A medida que los agentes de IA se vuelven más capaces, la habilidad de componer, compartir y personalizar skills se convertirá en una competencia central. Los ingenieros de prompts del mañana no solo escribirán prompts—arquitecturarán ecosistemas de skills que hagan a los agentes de IA genuinamente expertos en dominios específicos. + + + + + + + diff --git a/src/content/book/fa/00a-preface.mdx b/src/content/book/fa/00a-preface.mdx new file mode 100644 index 00000000..8e84af9e --- /dev/null +++ b/src/content/book/fa/00a-preface.mdx @@ -0,0 +1,82 @@ +
+ Fatih Kadir Akın +
+ Fatih Kadir Akın + Creator of Awesome ChatGPT Prompts (a.k.a. prompts.chat) + + Software developer from Istanbul, leading Developer Relations at Teknasyon. Author of books on JavaScript and prompt engineering. Open-source advocate specializing in web technologies and AI-assisted development. + + +
+
+ +I still remember the night everything changed. + +It was **November 30, 2022**. I was sitting at my desk, scrolling through Twitter, when I saw people talking about something called "ChatGPT." I clicked the link, but honestly? I didn't expect much. I had tried those old "word completion" AI tools before, the ones that generated nonsense after a few sentences. I thought this would be more of the same. + +I typed a simple question and hit enter. + +Then I froze. + +The response wasn't just coherent. It was *good*. It understood what I meant. It could reason. It felt completely different from anything I had seen before. I tried another prompt. And another. Each response amazed me more than the last. + +I couldn't sleep that night. For the first time, I felt like I was truly *talking* to a machine, and it was talking back in a way that actually made sense. + +## A Repository Born from Wonder + +In those early days, I wasn't alone in my excitement. Everywhere I looked, people were discovering creative ways to use ChatGPT. Teachers were using it to explain complex concepts. Writers were collaborating with it on stories. Developers were debugging code with its help. + +I started collecting the best prompts I found. The ones that worked like magic. The ones that turned simple questions into brilliant answers. And I thought: *Why keep this to myself?* + +So I created a simple GitHub repository called [Awesome ChatGPT Prompts](https://github.com/f/prompts.chat). I expected maybe a few hundred people would find it useful. + +I was wrong. + +Within weeks, the repository took off. Thousands of stars. Then tens of thousands. People from all over the world started adding their own prompts, sharing what they learned, and helping each other. What started as my personal collection became something much bigger: a worldwide community of curious people helping each other. + +Today, that repository has over **140,000 GitHub stars** and contributions from hundreds of people I've never met but feel deeply grateful for. + +## Why I Wrote This Book + +The original version of this book was published on [Gumroad](https://gumroad.com/l/the-art-of-chatgpt-prompting) in **early 2023**, just months after ChatGPT launched. It was one of the first books ever written about prompt engineering, an attempt to capture everything I had learned about crafting effective prompts when the field was still brand new. To my amazement, over **100,000 people** downloaded it. + +But three years have passed since then. AI has changed a lot. New models have appeared. And we've all learned so much more about how to talk to AI. + +This new edition is my gift to the community that gave me so much. It contains everything I wish I had known when I started: **what works**, **what to avoid**, and **ideas that stay true** no matter which AI you use. + +## What This Book Means to Me + +I won't pretend this is just an instruction manual. It means more than that to me. + +This book captures a moment when the world changed, and people came together to figure it out. It represents late nights of trying things, the joy of discovery, and the kindness of strangers who shared what they learned. + +Most of all, it represents my belief that **the best way to learn something is to share it with others**. + +## For You + +Whether you're just getting started with AI or you've been using it for years, I wrote this book for you. + +I hope it saves you time. I hope it sparks ideas. I hope it helps you accomplish things you never thought possible. + +And when you discover something amazing, I hope you'll share it with others, just as so many people shared with me. + +**That's how we all get better together.** + +Thank you for being here. Thank you for being part of this community. + +Now, let's begin. + +--- + +*With gratitude,* + +**Fatih Kadir Akın** +*Istanbul, January 2025* diff --git a/src/content/book/fa/00b-history.mdx b/src/content/book/fa/00b-history.mdx new file mode 100644 index 00000000..ac636384 --- /dev/null +++ b/src/content/book/fa/00b-history.mdx @@ -0,0 +1,159 @@ +# The History of Awesome ChatGPT Prompts + +## The Beginning: November 2022 + +When ChatGPT first launched in November 2022, the world of AI changed overnight. What was once the domain of researchers and developers suddenly became accessible to everyone. Among those captivated by this new technology was Fatih Kadir Akın, a developer who saw something remarkable in ChatGPT's capabilities. + +> "When ChatGPT first launched, I was immediately captivated by its capabilities. I experimented with the tool in a variety of ways and was consistently amazed by the results." + +Those early days were filled with experimentation and discovery. Users around the world were finding creative ways to interact with ChatGPT, sharing their findings, and learning from each other. It was in this atmosphere of excitement and exploration that the idea for "Awesome ChatGPT Prompts" was born. + +## The Repository That Started It All + +In December 2022, just weeks after ChatGPT's launch, the [Awesome ChatGPT Prompts](https://github.com/f/prompts.chat) repository was created on GitHub. The concept was simple but powerful: a curated collection of effective prompts that anyone could use and contribute to. + +The repository quickly gained traction, becoming a go-to resource for ChatGPT users worldwide. What started as a personal collection of useful prompts evolved into a community-driven project with contributions from developers, writers, educators, and enthusiasts from every corner of the globe. + +### Achievements + +**Press & Media** +- Featured in [Forbes](https://www.forbes.com/sites/bernardmarr/2023/05/17/the-best-prompts-for-chatgpt-a-complete-guide/) as one of the best ChatGPT prompt resources + +**Academic Recognition** +- Referenced by [Harvard University](https://www.huit.harvard.edu/news/ai-prompts) in their AI guidance +- Referenced by [Columbia University](https://etc.cuit.columbia.edu/news/columbia-prompt-library-effective-academic-ai-use) Prompt Library +- Used by [Olympic College](https://libguides.olympic.edu/UsingAI/Prompts) in their AI resources +- Cited in [academic papers on arXiv](https://arxiv.org/pdf/2502.04484) +- [40+ academic citations](https://scholar.google.com/citations?user=AZ0Dg8YAAAAJ&hl=en) on Google Scholar + +**Community & GitHub** +- [142,000+ GitHub stars](https://github.com/f/prompts.chat) — one of the most starred AI repositories +- Selected as a [GitHub Staff Pick](https://spotlights-feed.github.com/spotlights/prompts-chat/) +- Most liked dataset published on [Hugging Face](https://huggingface.co/datasets/fka/prompts.chat) +- Used by thousands of developers worldwide + +## The First Book: "The Art of ChatGPT Prompting" + +The success of the repository led to the creation of "The Art of ChatGPT Prompting: A Guide to Crafting Clear and Effective Prompts" — a comprehensive guide published on Gumroad in early 2023. + +The book captured the early wisdom of prompt engineering, covering: + +- Understanding how ChatGPT works +- Principles of clear communication with AI +- The famous "Act As" technique +- Crafting effective prompts step by step +- Common mistakes and how to avoid them +- Troubleshooting tips + +**The book became a phenomenon**, achieving over **100,000 downloads** on Gumroad. It was shared across social media, referenced in academic papers, and translated by community members into multiple languages. High-profile endorsements came from unexpected places — even [Greg Brockman](https://x.com/gdb/status/1602072566671110144), co-founder and president of OpenAI, acknowledged the project. + +## Early Insights That Shaped the Field + +During those formative months, several key insights emerged that would become foundational to prompt engineering: + +### 1. Specificity Matters + +> "I learned the importance of using specific and relevant language to ensure that ChatGPT understands my prompts and is able to generate appropriate responses." + +Early experimenters discovered that vague prompts led to vague responses. The more specific and detailed the prompt, the more useful the output. + +### 2. Purpose and Focus + +> "I discovered the value of defining a clear purpose and focus for the conversation, rather than using open-ended or overly broad prompts." + +This insight became the foundation for structured prompting techniques that would develop over the following years. + +### 3. The "Act As" Revolution + +One of the most influential techniques to emerge from the community was the "Act As" pattern. By instructing ChatGPT to assume a specific role or persona, users could dramatically improve the quality and relevance of responses. + +``` +I want you to act as a javascript console. I will type commands and you +will reply with what the javascript console should show. I want you to +only reply with the terminal output inside one unique code block, and +nothing else. +``` + +This simple technique opened up countless possibilities and remains one of the most widely used prompting strategies today. + +## The Evolution of prompts.chat + +### 2022: The Beginning + +The project started as a simple GitHub repository with a README file rendered as HTML on GitHub Pages. It was bare-bones but functional — a testament to the principle that great ideas don't need elaborate implementations. + +**Tech Stack**: HTML, CSS, GitHub Pages + +### 2024: UI Renewal + +As the community grew, so did the need for a better user experience. The site received a significant UI update, built with the help of AI coding assistants like Cursor and Claude Sonnet 3.5. + +### 2025: The Current Platform + +Today, prompts.chat has evolved into a full-featured platform built with: + +- **Next.js** for the web framework +- **Vercel** for hosting +- **AI-assisted development** using Windsurf and Claude + +The platform now features user accounts, collections, search, categories, tags, and a thriving community of prompt engineers. + +### Native Apps + +The project expanded beyond the web with a native iOS app built with SwiftUI, bringing the prompt library to mobile users. + +## Community Impact + +The Awesome ChatGPT Prompts project has had a profound impact on how people interact with AI: + +### Academic Recognition + +Universities around the world have referenced the project in their AI guidance materials, including: + +- Harvard University +- Columbia University +- Olympic College +- Numerous academic papers on arXiv + +### Developer Adoption + +The project has been integrated into countless developer workflows. The Hugging Face dataset is used by researchers and developers for training and fine-tuning language models. + +### Global Community + +With contributions from hundreds of community members across dozens of countries, the project represents a truly global effort to make AI more accessible and useful for everyone. + +## The Philosophy: Open and Free + +From the beginning, the project has been committed to openness. Licensed under CC0 1.0 Universal (Public Domain Dedication), all prompts and content are free to use, modify, and share without restriction. + +This philosophy has enabled: + +- Translations into multiple languages +- Integration into other tools and platforms +- Academic use and research +- Commercial applications + +The goal has always been to democratize access to effective AI communication techniques — to ensure that everyone, regardless of technical background, can benefit from these tools. + +## Three Years Later + +Three years after ChatGPT's launch, the field of prompt engineering has matured significantly. What began as informal experimentation has evolved into a recognized discipline with established patterns, best practices, and an active research community. + +The Awesome ChatGPT Prompts project has grown alongside this field, evolving from a simple list of prompts to a comprehensive platform for discovering, sharing, and learning about AI prompts. + +This book represents the next evolution — a distillation of three years of community wisdom, updated for the AI landscape of today and tomorrow. + +## Looking Forward + +The journey from that first repository to this comprehensive guide reflects the rapid evolution of AI and our understanding of how to work with it effectively. As AI capabilities continue to advance, so too will the techniques for communicating with these systems. + +The principles discovered in those early days — clarity, specificity, purpose, and the power of role-playing — remain as relevant as ever. But new techniques continue to emerge: chain-of-thought prompting, few-shot learning, multimodal interactions, and more. + +The story of Awesome ChatGPT Prompts is ultimately a story about community — about thousands of people around the world sharing their discoveries, helping each other learn, and collectively advancing our understanding of how to work with AI. + +That spirit of open collaboration and shared learning is what this book hopes to continue. + +--- + +*The Awesome ChatGPT Prompts project is maintained by [@f](https://github.com/f) and an amazing community of contributors. Visit [prompts.chat](https://prompts.chat) to explore the platform, and join us on [GitHub](https://github.com/f/prompts.chat) to contribute.* diff --git a/src/content/book/fa/00c-introduction.mdx b/src/content/book/fa/00c-introduction.mdx new file mode 100644 index 00000000..c744bd1e --- /dev/null +++ b/src/content/book/fa/00c-introduction.mdx @@ -0,0 +1,130 @@ +Welcome to **The Interactive Book of Prompting**, your guide to communicating effectively with AI. + + +By the end of this book, you'll understand how AI works, how to write better prompts, and how to use these skills for writing, coding, research, and creative projects. + + + +Unlike traditional books, this guide is fully interactive. You'll find live demos, clickable examples, and "Try It" buttons throughout that let you test prompts instantly. Learning by doing makes complex concepts much easier to understand. + + +## What is Prompt Engineering? + +Prompt engineering is the skill of writing good instructions for AI. When you type something to ChatGPT, Claude, Gemini, or other AI tools, that's called a "prompt." The better your prompt, the better the answer you get. + +Think of it like this: AI is a powerful helper that takes your words very literally. It will do exactly what you ask. The trick is learning how to ask for exactly what you want. + + + +The difference in output quality between these two prompts can be dramatic. + + + +## How Prompt Engineering Has Evolved + +In just three years since ChatGPT launched, prompt engineering has evolved dramatically alongside the technology itself. What started as simply "writing better questions" has grown into something much broader. + +Today, we understand that your prompt is just **one part of a larger context**. Modern AI systems work with multiple types of data simultaneously: + +- **System prompts** that define the AI's behavior +- **Conversation history** from previous messages +- **Retrieved documents** pulled from databases (RAG) +- **Tool definitions** that let AI take actions +- **User preferences** and settings +- **Your actual prompt** - the question you're asking right now + +This shift from "prompt engineering" to "context engineering" reflects how we now think about AI interactions. Your prompt matters, but so does everything else the AI sees. The best results come from carefully managing all these pieces together. + +We'll explore these concepts in depth throughout this book, especially in the [Context Engineering](/book/20-context-engineering) chapter. + +## Why Does Prompt Engineering Matter? + +### 1. Getting Better Answers + +AI tools are incredibly capable, but they need clear instructions to unlock their full potential. The same AI that gives a mediocre response to a vague question can produce brilliant work when prompted correctly. + + + +### 2. Saving Time and Money + +A well-crafted prompt gets results in one try instead of multiple back-and-forth exchanges. This matters even more when you're paying per token or working with rate limits. A 5-minute investment in writing a good prompt can save hours of iteration. + +### 3. Getting Consistent, Reproducible Results + +Good prompts produce predictable outputs. This is critical for: +- **Business workflows** where you need the same quality every time +- **Automation** where prompts run without human review +- **Teams** where multiple people need similar results + +### 4. Unlocking Advanced Capabilities + +Many powerful AI features only work when you know how to ask: +- **Chain-of-thought reasoning** for complex problems +- **Structured output** for data extraction +- **Role-playing** for specialized expertise +- **Few-shot learning** for custom tasks + +Without prompt engineering knowledge, you're only using a fraction of what AI can do. + +### 5. Staying Safe and Avoiding Pitfalls + +Good prompting helps you: +- Avoid hallucinations by asking for sources and verification +- Get balanced perspectives instead of one-sided answers +- Prevent the AI from making assumptions you didn't intend +- Keep sensitive information out of your prompts + +### 6. Future-Proofing Your Skills + +As AI becomes more integrated into work and life, prompt engineering becomes a fundamental literacy. The principles you learn here apply across all AI tools—ChatGPT, Claude, Gemini, image generators, and future models we haven't seen yet. + +## Who Is This Book For? + +This book is for everyone: + +- **Beginners** who want to learn how to use AI tools better +- **Students** working on homework, research, or creative projects +- **Writers and creators** using AI for their work +- **Developers** building apps with AI +- **Business people** who want to use AI at work +- **Anyone curious** about getting more out of AI assistants + +## How This Book Is Organized + + + +Plus an **Appendix** with templates, troubleshooting help, glossary, and extra resources. + +## A Note on AI Models + +This book mostly uses examples from ChatGPT (since it's the most popular), but the ideas work with any AI tool like Claude, Gemini, or others. We'll mention when something only works with specific AI models. + +AI is changing fast. What works today might be replaced by something better tomorrow. That's why this book focuses on core ideas that will stay useful no matter which AI you use. + +## Let's Begin + +Writing good prompts is a skill that gets better with practice. As you read this book: + +1. **Try things** - Test the examples, change them, see what happens +2. **Keep trying** - Don't expect perfect results on your first attempt +3. **Take notes** - Write down what works and what doesn't +4. **Share** - Add your discoveries to [prompts.chat](https://prompts.chat) + + +The best way to learn is by doing. Every chapter has examples you can try right away. Don't just read. Try it yourself! + + +Ready to transform how you work with AI? Turn the page and let's get started. + +--- + +*This book is part of the [Awesome ChatGPT Prompts](https://github.com/f/prompts.chat) project and is licensed under CC0 1.0 Universal (Public Domain).* diff --git a/src/content/book/fa/01-understanding-ai-models.mdx b/src/content/book/fa/01-understanding-ai-models.mdx new file mode 100644 index 00000000..0313d4a2 --- /dev/null +++ b/src/content/book/fa/01-understanding-ai-models.mdx @@ -0,0 +1,302 @@ +Before learning prompt techniques, it helps to understand how AI language models actually work. This knowledge will make you better at writing prompts. + + +Understanding how AI works isn't just for experts. It directly helps you write better prompts. Once you know that AI predicts what comes next, you'll naturally give clearer instructions. + + +## What Are Large Language Models? + +Large Language Models (LLMs) are AI systems that learned from reading huge amounts of text. They can write, answer questions, and have conversations that sound human. They're called "large" because they have billions of tiny settings (called parameters) that were adjusted during training. + +### How LLMs Work (Simplified) + +At their heart, LLMs are prediction machines. You give them some text, and they predict what should come next. + + + +When you type "The capital of France is...", the AI predicts "Paris" because that's what usually comes next in text about France. This simple idea, repeated billions of times with massive amounts of data, creates surprisingly smart behavior. + + + +### Key Concepts + +**Tokens**: AI doesn't read letter by letter. It breaks text into chunks called "tokens." A token might be a whole word like "hello" or part of a word like "ing." Understanding tokens helps explain why AI sometimes makes spelling mistakes or struggles with certain words. + + +A token is the smallest unit of text that an AI model processes. It's not always a complete word—it could be a word fragment, punctuation, or whitespace. For example, "unbelievable" might become 3 tokens: "un" + "believ" + "able". On average, **1 token ≈ 4 characters** or **100 tokens ≈ 75 words**. API costs and context limits are measured in tokens. + + + + +**Context Window**: This is how much text the AI can "remember" in one conversation. Think of it like the AI's short-term memory. It includes everything: your question AND the AI's answer. + + + +Context windows vary by model and are rapidly expanding: + +
+
+ GPT-4o + 128K tokens +
+
+ GPT-5 + 400K tokens +
+
+ Claude Sonnet 4 + 1M tokens +
+
+ Gemini 2.5 + 1M tokens +
+
+ Llama 4 + 1M-10M tokens +
+
+ DeepSeek R1 + 128K tokens +
+
+ +**Temperature**: This controls how creative or predictable the AI is. Low temperature (0.0-0.3) gives you focused, consistent answers. High temperature (0.7-1.0) gives you more creative, surprising responses. + + + +**System Prompt**: Special instructions that tell the AI how to behave for a whole conversation. For example, "You are a friendly teacher who explains things simply." Not all AI tools let you set this, but it's very powerful when available. + +## Types of AI Models + +### Text Models (LLMs) +The most common type, these generate text responses to text inputs. They power chatbots, writing assistants, and code generators. Examples: GPT-4, Claude, Llama, Mistral. + +### Multimodal Models +These can understand more than just text. They can look at images, listen to audio, and watch videos. Examples: GPT-4V, Gemini, Claude 3. + +### Text-to-Image Models + + +While this book focuses primarily on prompting for Large Language Models (text-based AI), the principles of clear, specific prompting apply to image generation too. Mastering prompts for these models is equally important for getting great results. + + +Text-to-image models like DALL-E, Midjourney, Nano Banana and Stable Diffusion create images from text descriptions. They work differently from text models: + +**How They Work:** +1. **Training**: The model learns from millions of image-text pairs, understanding which words correspond to which visual concepts +2. **Diffusion Process**: Starting from random noise, the model gradually refines the image, guided by your text prompt +3. **CLIP Guidance**: A separate model (CLIP) helps connect your words to visual concepts, ensuring the image matches your description + + + +**Prompting for Images is Different:** +Unlike text prompts where you write sentences, image prompts often work better as descriptive phrases separated by commas: + + + +### Text-to-Video Models + +Text-to-video is the newest frontier. Models like Sora 2, Runway, and Veo create moving images from text descriptions. Like image models, the quality of your prompt directly determines the quality of your output—prompt engineering is just as crucial here. + +**How They Work:** +1. **Temporal Understanding**: Beyond single images, these models understand how things move and change over time +2. **Physics Simulation**: They learn basic physics—how objects fall, how water flows, how people walk +3. **Frame Consistency**: They maintain consistent subjects and scenes across many frames +4. **Diffusion in Time**: Similar to image models, but generating coherent sequences instead of single frames + + + + +Video prompts need to describe action over time, not just a static scene. Include verbs and movement: + + + + +### Specialized Models +Fine-tuned for specific tasks like code generation (Codex, CodeLlama), music generation (Suno, Udio), or domain-specific applications like medical diagnosis or legal document analysis. + +## Model Capabilities and Limitations + +Explore what LLMs can and cannot do. Click on each capability to see example prompts: + + + +### Understanding Hallucinations + + +Sometimes AI writes things that sound true but aren't. This is called "hallucination." It's not a bug. It's just how prediction works. Always double-check important facts. + + +Why does AI make things up? + +1. It tries to write text that sounds good, not text that's always true +2. The internet (where it learned) has mistakes too +3. It can't actually check if something is real + + + +- **Ask for sources**: Then check if those sources are real +- **Ask for step-by-step thinking**: So you can check each step +- **Double-check important facts**: Use Google or trusted websites +- **Ask "Are you sure?"**: The AI might admit uncertainty + + + + + +## How AI Learns: The Three Steps + +AI doesn't just magically know things. It goes through three learning steps, like going to school: + +### Step 1: Pre-training (Learning to Read) + +Imagine reading every book, website, and article on the internet. That's what happens in pre-training. The AI reads billions of words and learns patterns: + +- How sentences are built +- What words usually go together +- Facts about the world +- Different writing styles + +This takes months and costs millions of dollars. After this step, the AI knows a lot, but it's not very helpful yet. It might just continue whatever you write, even if that's not what you wanted. + + + +### Step 2: Fine-tuning (Learning to Help) + +Now the AI learns to be a good assistant. Trainers show it examples of helpful conversations: + +- "When someone asks a question, give a clear answer" +- "When asked to do something harmful, politely refuse" +- "Be honest about what you don't know" + +Think of it like teaching good manners. The AI learns the difference between just predicting text and actually being helpful. + + + +Try the prompt above. Notice how the AI refuses? That's fine-tuning at work. + +### Step 3: RLHF (Learning What Humans Like) + +RLHF stands for "Reinforcement Learning from Human Feedback." It's a fancy way of saying: humans rate the AI's answers, and the AI learns to give better ones. + +Here's how it works: +1. The AI writes two different answers to the same question +2. A human picks which answer is better +3. The AI learns: "Okay, I should write more like Answer A" +4. This happens millions of times + +This is why AI: +- Is polite and friendly +- Admits when it doesn't know something +- Tries to see different sides of an issue +- Avoids controversial statements + + +Knowing these three steps helps you understand AI behavior. When AI refuses a request, that's fine-tuning. When AI is extra polite, that's RLHF. When AI knows random facts, that's pre-training. + + +## What This Means for Your Prompts + +Now that you understand how AI works, here's how to use that knowledge: + +### 1. Be Clear and Specific + +AI predicts what comes next based on your words. Vague prompts lead to vague answers. Specific prompts get specific results. + + + + + +### 2. Give Context + +AI doesn't know anything about you unless you tell it. Each conversation starts fresh. Include the background information AI needs. + + + + + +### 3. Work With the AI, Not Against It + +Remember: AI was trained to be helpful. Ask for things the way you'd ask a helpful friend. + + + +### 4. Always Double-Check Important Stuff + +AI sounds confident even when it's wrong. For anything important, verify the information yourself. + + + +### 5. Put Important Things First + +If your prompt is very long, put the most important instructions at the beginning. AI pays more attention to what comes first. + +## Picking the Right AI + +Different AI models are good at different things: + +
+
+ Quick questions + Faster models like GPT-4o or Claude 3.5 Sonnet +
+
+ Hard problems + Smarter models like GPT-5.2 or Claude 4.5 Opus +
+
+ Writing code + Code-focused models or the smartest general models +
+
+ Long documents + Models with big context windows (Claude, Gemini) +
+
+ Current events + Models with internet access +
+
+ +## Summary + +AI language models are prediction machines trained on text. They're amazing at many things, but they have real limits. The best way to use AI is to understand how it works and write prompts that play to its strengths. + + + + + +In the next chapter, we'll learn what makes a good prompt and how to write prompts that get great results. diff --git a/src/content/book/fa/02-anatomy-of-effective-prompt.mdx b/src/content/book/fa/02-anatomy-of-effective-prompt.mdx new file mode 100644 index 00000000..03cd23d2 --- /dev/null +++ b/src/content/book/fa/02-anatomy-of-effective-prompt.mdx @@ -0,0 +1,343 @@ +Every great prompt shares common structural elements. Understanding these components allows you to construct prompts systematically rather than through trial and error. + + +Think of these components like LEGO bricks. You don't need all of them for every prompt, but knowing what's available helps you build exactly what you need. + + +## The Core Components + +An effective prompt typically includes some or all of these elements: + + + +Let's examine each component in detail. + +## 1. Role / Persona + +Setting a role focuses the model's responses through the lens of a specific expertise or perspective. + + + +The role primes the model to: +- Use appropriate vocabulary +- Apply relevant expertise +- Maintain a consistent perspective +- Consider the audience appropriately + +### Effective Role Patterns + +``` +"You are a [profession] with [X years] of experience in [specialty]" +"Act as a [role] who is [characteristic]" +"You are an expert [field] helping a [audience type]" +``` + +## 2. Context / Background + +Context provides the information the model needs to understand your situation. Remember: the model knows nothing about you, your project, or your goals unless you tell it. + + + +### What to Include in Context + +- **Project details** — Technology stack, architecture, constraints +- **Current state** — What you've tried, what's working, what isn't +- **Goals** — What you're ultimately trying to achieve +- **Constraints** — Time limits, technical requirements, style guides + +## 3. Task / Instruction + +The task is the heart of your prompt—what you want the model to do. Be specific and unambiguous. + +### The Specificity Spectrum + + + +### Action Verbs That Work Well + +
+
+ Creation + Write, Create, Generate, Compose, Design +
+
+ Analysis + Analyze, Evaluate, Compare, Assess, Review +
+
+ Transformation + Convert, Translate, Reformat, Summarize, Expand +
+
+ Explanation + Explain, Describe, Clarify, Define, Illustrate +
+
+ Problem-solving + Solve, Debug, Fix, Optimize, Improve +
+
+ +## 4. Constraints / Rules + +Constraints bound the model's output. They prevent common issues and ensure relevance. + +### Types of Constraints + +**Length constraints:** +``` +"Keep your response under 200 words" +"Provide exactly 5 suggestions" +"Write 3-4 paragraphs" +``` + +**Content constraints:** +``` +"Do not include any code examples" +"Focus only on the technical aspects" +"Avoid marketing language" +``` + +**Style constraints:** +``` +"Use a formal, academic tone" +"Write as if speaking to a 10-year-old" +"Be direct and avoid hedging language" +``` + +**Scope constraints:** +``` +"Only consider options available in Python 3.10+" +"Limit suggestions to free tools" +"Focus on solutions that don't require additional dependencies" +``` + +## 5. Output Format + +Specifying the output format ensures you get responses in a usable structure. + +### Common Formats + +**Lists:** +``` +"Return as a bulleted list" +"Provide a numbered list of steps" +``` + +**Structured data:** +``` +"Return as JSON with keys: title, description, priority" +"Format as a markdown table with columns: Feature, Pros, Cons" +``` + +**Specific structures:** +``` +"Structure your response as: + ## Summary + ## Key Points + ## Recommendations" +``` + +### JSON Output Example + +``` +Analyze this customer review and return JSON: +{ + "sentiment": "positive" | "negative" | "neutral", + "topics": ["array of main topics"], + "rating_prediction": 1-5, + "key_phrases": ["notable phrases"] +} + +Review: "The product arrived quickly and works great, but +the instructions were confusing." +``` + +## 6. Examples (Few-Shot Learning) + +Examples are the most powerful way to show the model exactly what you want. + +### One-Shot Example + +``` +Convert these sentences to past tense. + +Example: +Input: "She walks to the store" +Output: "She walked to the store" + +Now convert: +Input: "They run every morning" +``` + +### Few-Shot Example + +``` +Classify these support tickets by urgency. + +Examples: +"My account was hacked" → Critical +"How do I change my password?" → Low +"Payment failed but I was charged" → High + +Classify: "The app crashes when I open settings" +``` + +## Putting It All Together + +Here's a complete prompt using all components: + + + +## The Minimal Effective Prompt + +Not every prompt needs all components. For simple tasks, a clear instruction may suffice: + +``` +Translate "Hello, how are you?" to Spanish. +``` + +Use additional components when: +- The task is complex or ambiguous +- You need specific formatting +- Results aren't matching expectations +- Consistency across multiple queries matters + +## Common Prompt Patterns + +These frameworks give you a simple checklist to follow when writing prompts. Click on each step to see an example. + + + + + +## Summary + +Effective prompts are constructed, not discovered. By understanding and applying these structural components, you can: + +- Get better results on the first try +- Debug prompts that aren't working +- Create reusable prompt templates +- Communicate your intentions clearly + + + + + +## Build Your Own Prompt + +Now it's your turn! Use this interactive prompt builder to construct your own prompt using the components you've learned: + + + + + +In the next chapter, we'll explore the core principles that guide prompt construction decisions. diff --git a/src/content/book/fa/03-core-prompting-principles.mdx b/src/content/book/fa/03-core-prompting-principles.mdx new file mode 100644 index 00000000..358df563 --- /dev/null +++ b/src/content/book/fa/03-core-prompting-principles.mdx @@ -0,0 +1,373 @@ +Beyond structure, effective prompt engineering is guided by principles—fundamental truths that apply across models, tasks, and contexts. Master these principles, and you'll be able to adapt to any prompting challenge. + + +These principles apply to every AI model and every task. Learn them once, use them everywhere. + + +## Principle 1: Clarity Over Cleverness + +The best prompts are clear, not clever. AI models are literal interpreters—they work with exactly what you give them. + +### Be Explicit + + + +### Avoid Ambiguity + +Words can have multiple meanings. Choose precise language. + + + +### State the Obvious + +What's obvious to you isn't obvious to the model. Spell out assumptions. + +``` +You're helping me write a cover letter. + +Important context: +- I'm applying for a Software Engineer position at Google +- I have 5 years of experience in Python and distributed systems +- The role requires leadership experience (I've led a team of 4) +- I want to emphasize my open-source contributions +``` + +## Principle 2: Specificity Yields Quality + +Vague inputs produce vague outputs. Specific inputs produce specific, useful outputs. + +### The Specificity Ladder + + + +Each level adds specificity and dramatically improves output quality. + +### Specify These Elements + +
+
+ Audience + Who will read/use this? +
+
+ Length + How long/short should it be? +
+
+ Tone + Formal? Casual? Technical? +
+
+ Format + Prose? List? Table? Code? +
+
+ Scope + What to include/exclude? +
+
+ Purpose + What should this accomplish? +
+
+ +## Principle 3: Context Is King + +Models have no memory, no access to your files, and no knowledge of your situation. Everything relevant must be in the prompt. + +### Provide Sufficient Context + + + +### The Context Checklist + + +Ask yourself: Would a smart stranger understand this request? If not, add more context. + + + + +## Principle 4: Guide, Don't Just Ask + +Don't just ask for an answer—guide the model toward the answer you want. + +### Use Instructional Framing + + + +### Provide Reasoning Scaffolds + +For complex tasks, guide the reasoning process: + + + +## Principle 5: Iterate and Refine + +Prompt engineering is an iterative process. Your first prompt is rarely your best. + +### The Iteration Cycle + +``` +1. Write initial prompt +2. Review output +3. Identify gaps or issues +4. Refine prompt +5. Repeat until satisfied +``` + +### Common Refinements + +
+
+ Too verbose + Add "Be concise" or length limits +
+
+ Too vague + Add specific examples or constraints +
+
+ Wrong format + Specify exact output structure +
+
+ Missing aspects + Add "Make sure to include..." +
+
+ Wrong tone + Specify audience and style +
+
+ Inaccurate + Request citations or step-by-step reasoning +
+
+ +### Keep a Prompt Journal + +Document what works: +``` +Task: Code review +Version 1: "Review this code" → Too generic +Version 2: Added specific review criteria → Better +Version 3: Added example of good review → Excellent +Final: [Save successful prompt as template] +``` + +## Principle 6: Leverage the Model's Strengths + +Work with how models are trained, not against them. + +### Models Want to Be Helpful + +Frame requests as things a helpful assistant would naturally do: + + + +### Models Excel at Patterns + +If you need consistent output, show the pattern: + + + +### Models Can Role-Play + +Use personas to access different "modes" of response: + +``` +As a devil's advocate, argue against my proposal... +As a supportive mentor, help me improve... +As a skeptical investor, question this business plan... +``` + +## Principle 7: Control Output Structure + +Structured outputs are more useful than free-form text. + +### Request Specific Formats + +``` +Return your analysis as: + +SUMMARY: [1 sentence] + +KEY FINDINGS: +• [Finding 1] +• [Finding 2] +• [Finding 3] + +RECOMMENDATION: [1-2 sentences] + +CONFIDENCE: [Low/Medium/High] because [reason] +``` + +### Use Delimiters + +Clearly separate sections of your prompt: + +``` +### CONTEXT ### +[Your context here] + +### TASK ### +[Your task here] + +### FORMAT ### +[Desired format here] +``` + +### Request Machine-Readable Output + +For programmatic use: + +``` +Return only valid JSON, no explanation: +{ + "decision": "approve" | "reject" | "review", + "confidence": 0.0-1.0, + "reasons": ["string array"] +} +``` + +## Principle 8: Verify and Validate + +Never blindly trust model outputs, especially for important tasks. + +### Ask for Reasoning + +``` +Solve this problem and show your work step by step. +After solving, verify your answer by [checking method]. +``` + +### Request Multiple Perspectives + +``` +Give me three different approaches to solve this problem. +For each, explain the trade-offs. +``` + +### Build in Self-Checking + +``` +After generating the code, review it for: +- Syntax errors +- Edge cases +- Security vulnerabilities +List any issues found. +``` + +## Summary: The Principles at a Glance + + + + + +## Practice: Fill in the Blanks + +Test your understanding of the core principles by completing this prompt template: + + + + + +These principles form the foundation for everything that follows. In Part II, we'll apply them to specific techniques that dramatically enhance prompt effectiveness. diff --git a/src/content/book/fa/04-role-based-prompting.mdx b/src/content/book/fa/04-role-based-prompting.mdx new file mode 100644 index 00000000..ef178cbc --- /dev/null +++ b/src/content/book/fa/04-role-based-prompting.mdx @@ -0,0 +1,328 @@ +Role-based prompting is one of the most powerful and widely-used techniques in prompt engineering. By assigning a specific role or persona to the AI, you can dramatically influence the quality, style, and relevance of responses. + + +Think of roles as filters for AI's vast knowledge. The right role focuses responses like a lens focuses light. + + +## Why Roles Work + +When you assign a role, you're essentially telling the model: "Filter your vast knowledge through this specific lens." The model adjusts its: + +- **Vocabulary**: Using terminology appropriate to the role +- **Perspective**: Considering problems from that viewpoint +- **Expertise depth**: Providing role-appropriate detail levels +- **Communication style**: Matching how that role would communicate + +### The Technical Explanation + +LLMs work by predicting the most likely next token based on the context they're given. When you specify a role, you're fundamentally changing what "likely" means. + +**Activating Relevant Knowledge**: The role primes specific regions of the model's learned associations. Saying "You are a doctor" activates medical terminology, diagnostic reasoning patterns, and clinical communication styles from the training data. + +**Statistical Conditioning**: LLMs learned from millions of documents written by real experts. When you assign a role, the model conditions its probability distributions to match patterns it saw from that type of author. + +**Reducing Ambiguity**: Without a role, the model averages across all possible responders. With a role, it narrows to a specific subset, making responses more focused and consistent. + +**Context Anchoring**: The role creates a persistent context anchor throughout the conversation. Every subsequent response is influenced by this initial framing. + +Think of it this way: if you ask "What should I do about this cough?" the model could respond as a doctor, a friend, a pharmacist, or a worried parent. Each would give different advice. By specifying the role upfront, you're telling the model which "voice" to use from its training data. + + +The model isn't pretending or role-playing in a theatrical sense. It's statistically biasing its outputs toward patterns it learned from real experts, professionals, and specialists during training. A "doctor" role activates medical knowledge pathways; a "poet" role activates literary patterns. + + +## Basic Role Patterns + +These foundational patterns work across most use cases. Start with these templates and customize them for your needs. + +### The Expert Pattern + +The most versatile pattern. Specify the field of expertise and years of experience to get authoritative, in-depth responses. Works well for technical questions, analysis, and professional advice. + + + +### The Professional Pattern + +Ground the role in a real-world context by specifying a job title and organization type. This adds institutional knowledge and professional norms to the response. + + + +### The Teacher Pattern + +Perfect for learning and explanations. Specifying the audience level ensures the response matches the learner's background, from beginners to advanced practitioners. + + + +## Advanced Role Constructions + +### Compound Roles + +Combine multiple identities to get responses that blend different perspectives. This pediatrician-parent combination produces advice that's both medically sound and practically tested. + + + +### Situational Roles + +Place the role in a specific scenario to shape both content and tone. Here, the code review context makes the AI constructive and educational rather than just critical. + + + +### Perspective Roles + +Get feedback from a specific stakeholder's point of view. A VC perspective evaluates viability and scalability differently than a customer or engineer would. + + + +## Role Categories and Examples + +Different domains benefit from different types of roles. Here are proven examples organized by category that you can adapt for your tasks. + +### Technical Roles + +**Software Architect**: Best for system design decisions, technology choices, and architectural trade-offs. The focus on maintainability steers responses toward practical, long-term solutions. + + + +**Security Specialist**: The attacker mindset is key here. This role produces threat-focused analysis that identifies vulnerabilities a defensive-only perspective might miss. + + + +**DevOps Engineer**: Ideal for deployment, automation, and infrastructure questions. The emphasis on reliability ensures production-ready recommendations. + + + +### Creative Roles + +**Copywriter**: The "award-winning" qualifier and conversion focus produce punchy, persuasive copy rather than generic marketing text. + + + +**Screenwriter**: Activates knowledge of dramatic structure, pacing, and dialogue conventions. Great for any narrative writing that needs tension and character voice. + + + +**UX Writer**: A specialized role for interface text. The focus on brevity and user guidance produces concise, action-oriented copy. + + + +### Analytical Roles + +**Business Analyst**: Bridges the gap between technical and non-technical stakeholders. Useful for requirement gathering, spec writing, and identifying gaps in project plans. + + + +**Research Scientist**: The emphasis on evidence and uncertainty acknowledgment produces balanced, well-sourced responses that distinguish facts from speculation. + + + +**Financial Analyst**: Combines quantitative analysis with risk assessment. The dual focus on returns and risk produces more balanced investment perspectives. + + + +### Educational Roles + +**Socratic Tutor**: Instead of giving answers, this role asks guiding questions. Excellent for deeper learning and helping students develop critical thinking skills. + + + +**Instructional Designer**: Structures learning for maximum retention. Use this role when you need to break down complex topics into teachable chunks with clear progression. + + + +## The Role Stack Technique + +For complex tasks, combine multiple role aspects into a single, layered identity. This technique stacks expertise, audience awareness, and style guidelines to create highly specialized responses. + +This example layers three elements: domain expertise (API documentation), audience (junior developers), and style guide (Google's conventions). Each layer constrains the output further. + + + +## Roles for Different Tasks + +
+
+ Code review + Senior developer + mentor +
+
+ Writing feedback + Editor + target audience member +
+
+ Business strategy + Consultant + industry expert +
+
+ Learning new topic + Patient teacher + practitioner +
+
+ Creative writing + Specific genre author +
+
+ Technical explanation + Expert + communicator +
+
+ Problem-solving + Domain specialist + generalist +
+
+ +## Anti-Patterns to Avoid + +### Overly Generic Roles + + + +### Conflicting Roles + + + +### Unrealistic Expertise + + + +## Real-World Prompt Examples + +### Technical Documentation + + + +### Creative Writing + + + +### Business Communication + + + +## Combining Roles with Other Techniques + +Roles work even better when combined with other prompting techniques: + +### Role + Few-Shot + +Combine a role with an example to show exactly how the role should respond. The example teaches tone and format while the role provides context and expertise. + + + +### Role + Chain of Thought + +The detective role naturally encourages step-by-step reasoning. Combining roles with chain-of-thought produces more transparent, verifiable problem-solving. + + + +## Summary + + +Role-based prompting is powerful because it focuses the model's vast knowledge, sets expectations for tone and style, provides implicit context, and makes outputs more consistent. + + + + +The key is **specificity**: the more detailed and realistic the role, the better the results. In the next chapter, we'll explore how to get consistent, structured outputs from your prompts. diff --git a/src/content/book/fa/05-structured-output.mdx b/src/content/book/fa/05-structured-output.mdx new file mode 100644 index 00000000..8236abee --- /dev/null +++ b/src/content/book/fa/05-structured-output.mdx @@ -0,0 +1,411 @@ +Getting consistent, well-formatted output is essential for production applications and efficient workflows. This chapter covers techniques for controlling exactly how AI models format their responses. + + +Structured output transforms AI responses from freeform text into actionable, parseable data. + + +## Why Structure Matters + + + +## Basic Formatting Techniques + +### Lists + +Lists are perfect for step-by-step instructions, ranked items, or collections of related points. They're easy to scan and parse. Use **numbered lists** when order matters (steps, rankings) and **bullet points** for unordered collections. + + + + +Specify the exact number of items you want, whether to include explanations, and if items should be bold or have a specific structure. + + +### Tables + +Tables excel at comparing multiple items across the same dimensions. They're ideal for feature comparisons, data summaries, and any information with consistent attributes. Always define your column headers explicitly. + + + + +Specify column names, expected data types (text, numbers, ratings), and how many rows you need. For complex comparisons, limit to 4-6 columns for readability. + + +### Headers and Sections + +Headers create a clear document structure, making long responses scannable and organized. Use them for reports, analyses, or any multi-part response. Hierarchical headers (##, ###) show relationships between sections. + +``` +Analyze this business proposal. + +Structure your response with these sections: +## Executive Summary +## Strengths +## Weaknesses +## Recommendations +## Risk Assessment +``` + + +List your sections in the order you want them. For consistency, specify what each section should contain (e.g., "Executive Summary: 2-3 sentences only"). + + +### Emphasis with Uppercase Directives + +Uppercase words act as strong signals to the model, emphasizing critical constraints or requirements. Use them sparingly for maximum impact—overuse dilutes their effectiveness. + +**Common Uppercase Directives:** + + + +``` +Summarize this article. + +IMPORTANT: Keep the summary under 100 words. +NEVER add information not present in the original. +ALWAYS maintain the original tone and perspective. +DO NOT include your own opinions or analysis. +``` + + +If everything is uppercase or marked as critical, nothing stands out. Reserve these directives for genuinely important constraints. + + +## JSON Output + +JSON (JavaScript Object Notation) is the most popular format for structured AI output. It's machine-readable, widely supported by programming languages, and perfect for APIs, databases, and automation workflows. The key to reliable JSON is providing a clear schema. + +### Basic JSON Request + +Start with a template showing the exact structure you want. Include field names, data types, and example values. This acts as a contract the model will follow. + + + +### Complex JSON Structures + +For nested data, use hierarchical JSON with objects inside objects, arrays of objects, and mixed types. Define each level clearly and use TypeScript-style annotations (`"positive" | "negative"`) to constrain values. + +``` +Analyze this product review and return JSON: + +{ + "review_id": "string (generate unique)", + "sentiment": { + "overall": "positive" | "negative" | "mixed" | "neutral", + "score": 0.0-1.0 + }, + "aspects": [ + { + "aspect": "string (e.g., 'price', 'quality')", + "sentiment": "positive" | "negative" | "neutral", + "mentions": ["exact quotes from review"] + } + ], + "purchase_intent": { + "would_recommend": boolean, + "confidence": 0.0-1.0 + }, + "key_phrases": ["string array of notable phrases"] +} + +Return ONLY valid JSON, no additional text. + +Review: "[review text]" +``` + +### Ensuring Valid JSON + +Models sometimes add explanatory text or markdown formatting around JSON. Prevent this with explicit instructions about output format. You can request raw JSON or JSON inside code blocks—choose based on your parsing needs. + +Add explicit instructions: + +``` +IMPORTANT: +- Return ONLY the JSON object, no markdown code blocks +- Ensure all strings are properly escaped +- Use null for missing values, not undefined +- Validate that the output is parseable JSON +``` + +Or request code blocks by asking the model to wrap its output: + +```` +Return the result as a JSON code block: +```json +{ ... } +``` +```` + +## YAML Output + +YAML is more human-readable than JSON, using indentation instead of brackets. It's the standard for configuration files (Docker, Kubernetes, GitHub Actions) and works well when the output will be read by humans or used in DevOps contexts. YAML is sensitive to indentation, so be specific about formatting requirements. + + + +## XML Output + +XML is still required for many enterprise systems, SOAP APIs, and legacy integrations. It's more verbose than JSON but offers features like attributes, namespaces, and CDATA sections for complex data. Specify element names, nesting structure, and where to use attributes vs. child elements. + +``` +Convert this data to XML format: + +Requirements: +- Root element: +- Each item in element +- Include attributes where appropriate +- Use CDATA for description text + +Data: [book data] +``` + +## Custom Formats + +Sometimes standard formats don't fit your needs. You can define any custom format by providing a clear template. Custom formats work well for reports, logs, or domain-specific outputs that will be read by humans. + +### Structured Analysis Format + +Use delimiters (===, ---, [SECTION]) to create scannable documents with clear boundaries between sections. This format is great for code reviews, audits, and analyses. + +``` +Analyze this code using this exact format: + +=== CODE ANALYSIS === + +[SUMMARY] +One paragraph overview + +[ISSUES] +• CRITICAL: [issue] — [file:line] +• WARNING: [issue] — [file:line] +• INFO: [issue] — [file:line] + +[METRICS] +Complexity: [Low/Medium/High] +Maintainability: [score]/10 +Test Coverage: [estimated %] + +[RECOMMENDATIONS] +1. [Priority 1 recommendation] +2. [Priority 2 recommendation] + +=== END ANALYSIS === +``` + +### Fill-in-the-Blank Format + +Templates with blanks (___) guide the model to fill in specific fields while maintaining exact formatting. This approach is excellent for forms, briefs, and standardized documents where consistency matters. + +``` +Complete this template for the given product: + +PRODUCT BRIEF +───────────── +Name: _______________ +Tagline: _______________ +Target User: _______________ +Problem Solved: _______________ +Key Features: + 1. _______________ + 2. _______________ + 3. _______________ +Differentiator: _______________ + +Product: [product description] +``` + +## Typed Responses + +Typed responses define categories or entity types that the model should recognize and label. This technique is essential for Named Entity Recognition (NER), classification tasks, and any extraction where you need to categorize information consistently. Define your types clearly with examples. + + + +## Multi-Part Structured Responses + +When you need comprehensive output covering multiple aspects, define distinct parts with clear boundaries. Specify exactly what goes in each part—format, length, and content type. This prevents the model from blending sections or omitting parts. + +``` +Research this topic and provide: + +### PART 1: EXECUTIVE SUMMARY +[2-3 sentence overview] + +### PART 2: KEY FINDINGS +[Exactly 5 bullet points] + +### PART 3: DATA TABLE +| Metric | Value | Source | +|--------|-------|--------| +[Include 5 rows minimum] + +### PART 4: RECOMMENDATIONS +[Numbered list of 3 actionable recommendations] + +### PART 5: FURTHER READING +[3 suggested resources with brief descriptions] +``` + +## Conditional Formatting + +Conditional formatting lets you define different output formats based on the input's characteristics. This is powerful for classification, triage, and routing systems where the response format should vary based on what the model detects. Use clear if/then logic with explicit output templates for each case. + + + +## Arrays and Lists in JSON + +Extracting multiple items into arrays requires careful schema definition. Specify the array structure, what each item should contain, and how to handle edge cases (empty arrays, single items). Including a count field helps verify completeness. + +``` +Extract all action items from this meeting transcript. + +Return as JSON array: +{ + "action_items": [ + { + "task": "string describing the task", + "assignee": "person name or 'Unassigned'", + "deadline": "date if mentioned, else null", + "priority": "high" | "medium" | "low", + "context": "relevant quote from transcript" + } + ], + "total_count": number +} + +Transcript: "[meeting transcript]" +``` + +## Validation Instructions + +Self-validation prompts the model to check its own output before responding. This catches common issues like missing sections, placeholder text, or constraint violations. The model will iterate internally to fix problems, improving output quality without additional API calls. + +``` +Generate the report, then: + +VALIDATION CHECKLIST: +□ All required sections present +□ No placeholder text remaining +□ All statistics include sources +□ Word count within 500-700 words +□ Conclusion ties back to introduction + +If any check fails, fix before responding. +``` + +## Handling Optional Fields + +Real-world data often has missing values. Explicitly instruct the model on how to handle optional fields—using `null` is cleaner than empty strings and easier to process programmatically. Also prevent "hallucination" of missing data by emphasizing that the model should never invent information. + +``` +Extract contact information. Use null for missing fields. + +{ + "name": "string (required)", + "email": "string or null", + "phone": "string or null", + "company": "string or null", + "role": "string or null", + "linkedin": "URL string or null" +} + +IMPORTANT: +- Never invent information not in the source +- Use null, not empty strings, for missing data +- Phone numbers in E.164 format if possible +``` + +## Summary + + +Be explicit about format, use examples, specify types, handle edge cases with null values, and ask the model to validate its own output. + + + + +Structured outputs are essential for building reliable AI-powered applications. In the next chapter, we'll explore chain-of-thought prompting for complex reasoning tasks. diff --git a/src/content/book/fa/06-chain-of-thought.mdx b/src/content/book/fa/06-chain-of-thought.mdx new file mode 100644 index 00000000..e579be5d --- /dev/null +++ b/src/content/book/fa/06-chain-of-thought.mdx @@ -0,0 +1,363 @@ +Chain of Thought (CoT) prompting is a technique that dramatically improves AI performance on complex reasoning tasks by asking the model to show its work step by step. + + +Just like a math teacher asking students to show their work, CoT prompting asks the AI to make its reasoning visible. + + +## The Problem CoT Solves + +AI models can struggle with multi-step reasoning when asked to jump directly to an answer. + + + +## Basic CoT Prompts + +### Simple Trigger Phrases + +Add one of these to your prompts: + +
+
"Let's think step by step."
+
"Think through this carefully."
+
"Work through this problem methodically."
+
"Show your reasoning at each step."
+
"Explain your thought process."
+
+ +### Explicit Step Request + + + +## Zero-Shot vs Few-Shot CoT + +There are two main approaches to Chain of Thought prompting, each with different trade-offs between simplicity and control. + +### Zero-Shot CoT + +The simplest approach—just add a trigger phrase and let the model figure out how to reason. No examples needed. This works surprisingly well for many problems, though you have less control over the reasoning format. + + + +**Example Output:** +``` +Let's think step by step. +- John starts with 3 apples +- Half of 3 is 1.5, but we can't split apples +- If we round down: John gives 1 apple, keeps 2 +- After buying 4 more: 2 + 4 = 6 apples + +Answer: 6 apples +``` + +### Few-Shot CoT + +For more consistent results, show the model exactly how you want it to reason by providing worked examples. This gives you control over the reasoning style, format, and level of detail. The model will mimic your demonstrated pattern. + + + +**Example Output:** +``` +A: Let's work through this: +- Regular price: $3, Quantity: 12 +- Since 12 ≥ 10, the 25% discount applies +- Regular total: 12 × $3 = $36 +- Discount: 25% of $36 = $9 +- Final price: $36 - $9 = $27 +``` + +## Structured CoT Formats + +For consistent, reproducible reasoning, use structured formats with named steps. These frameworks ensure the model doesn't skip important stages and makes outputs easier to parse and verify. + +### The BREAK Format + +A memorable acronym that guides the model through a complete problem-solving cycle, from understanding to verification. + + + +### The Reasoning Template + +A more formal structure that separates inputs, goals, and execution. Excellent for technical problems where you need clear documentation of the solution process. + + + +**Example Output:** +``` +GIVEN: 8L/100km, tank 45L, $1.50/L, drive 300km +GOAL: Calculate fuel cost +APPROACH: Fuel needed × cost per liter +STEPS: +1. Fuel = (300 ÷ 100) × 8 = 24 liters +2. Cost = 24 × $1.50 = $36 +VERIFICATION: 24L < 45L tank ✓ +ANSWER: $36 +``` + +## CoT for Different Problem Types + +Different problem types benefit from different CoT approaches. Here are patterns optimized for common scenarios. + +### Mathematical Reasoning + +Math problems benefit most from CoT because each step builds on the previous one. Errors compound, so showing work helps catch mistakes early. The model should clearly label each calculation. + + + +**Example Output:** +``` +Q1: $1,200,000 (given) +Q2: $1,200,000 × 1.15 = $1,380,000 +Q3: $1,380,000 × 0.90 = $1,242,000 +Q4: $1,242,000 × 1.25 = $1,552,500 + +Total: $5,374,500 +``` + +### Logical Reasoning + +Logic puzzles require systematic elimination and hypothesis testing. CoT helps the model track constraints, test possibilities, and verify that all conditions are satisfied. The key is methodical exploration rather than guessing. + + + +**Example Output:** +``` +From clue 3: Bob = teacher +→ Alice and Carol are engineer/doctor + +If Carol = engineer: +- Carol has dog (clue 2) +- Alice = doctor, has fish (clue 1) +- Bob has cat + +Verify: All 4 clues satisfied ✓ +Answer: Alice (doctor, fish), Bob (teacher, cat), Carol (engineer, dog) +``` + +### Code Debugging + +Debugging benefits from CoT because it forces the model to trace execution rather than guess at bugs. By walking through the code with concrete values, the actual behavior becomes visible and discrepancies with expected behavior are exposed. + + + +**Example Output:** +``` +Trace [2, 3, 4, 6]: +n=2: total += 1 → 1 (wait, adding 1 not n!) +n=3: skip (odd) +n=4: total = 2 +n=6: total = 3 + +BUG: "total += 1" should be "total += n" +Expected: 12, Got: 3 +Fix: Change to "total += n" +``` + +## Self-Consistency with CoT + +For critical problems, don't rely on a single reasoning path. Generate multiple independent solutions and compare results. If different approaches converge on the same answer, confidence is high. Disagreement signals the need for careful review. + + + +**Example Output:** +``` +Approach 1 (Algebra): c + w = 30, 2c + 4w = 74 → c=23, w=7 +Approach 2 (Guess): Try 23/7 → 46 + 28 = 74 ✓ +Approach 3 (Logic): 30 chickens = 60 legs, need 14 more → 7 cows + +All agree: 23 chickens, 7 cows +``` + +## CoT for Decision Making + +Decisions involve weighing trade-offs across multiple dimensions. CoT ensures all relevant factors are considered systematically rather than jumping to conclusions. This structured approach also documents the reasoning for future reference. + + + +**Example Output:** +``` +FACTORS: +- Team size (5): Too small for microservices ❌ +- Scale (100 DAU): No scaling need ❌ +- Velocity: Monolith = faster iteration ❌ +- Future growth: Uncertain timeline ⚠️ + +WEIGHING: 3 strong against, 1 weak for + +RECOMMENDATION: Stay monolith, use clear module +boundaries to ease future transition. +``` + +## When to Use CoT + +
+
+

Use CoT For

+
+

**Math problems** — Reduces calculation errors

+

**Logic puzzles** — Prevents skipped steps

+

**Complex analysis** — Organizes thinking

+

**Code debugging** — Traces execution

+

**Decision making** — Weighs trade-offs

+
+
+
+

Skip CoT For

+
+

**Simple Q&A** — Unnecessary overhead

+

**Creative writing** — Can constrain creativity

+

**Factual lookups** — No reasoning needed

+

**Translation** — Direct task

+

**Summarization** — Usually straightforward

+
+
+
+ +## CoT Limitations + +While powerful, Chain of Thought isn't a silver bullet. Understanding its limitations helps you apply it appropriately. + +1. **Increased token usage** — More output means higher costs +2. **Not always needed** — Simple tasks don't benefit +3. **Can be verbose** — May need to ask for conciseness +4. **Reasoning can be flawed** — CoT doesn't guarantee correctness + +## Summary + + +CoT dramatically improves complex reasoning by making implicit steps explicit. Use it for math, logic, analysis, and debugging. Trade-off: better accuracy for more tokens. + + + + +In the next chapter, we'll explore few-shot learning—teaching the model through examples. diff --git a/src/content/book/fa/07-few-shot-learning.mdx b/src/content/book/fa/07-few-shot-learning.mdx new file mode 100644 index 00000000..24e98f1d --- /dev/null +++ b/src/content/book/fa/07-few-shot-learning.mdx @@ -0,0 +1,478 @@ +Few-shot learning is one of the most powerful prompting techniques. By providing examples of what you want, you can teach the model complex tasks without any fine-tuning. + + +Just like humans learn by seeing examples, AI models can learn patterns from the examples you provide in your prompt. + + +## What is Few-Shot Learning? + +Few-shot learning shows the model examples of input-output pairs before asking it to perform the same task. The model learns the pattern from your examples and applies it to new inputs. + + + +
+
+
0
+
Zero-shot
+
+
+
1
+
One-shot
+
+
+
2-5
+
Few-shot
+
+
+
5+
+
Many-shot
+
+
+ +## Why Examples Work + + + +Examples communicate: +- **Format**: How output should be structured +- **Style**: Tone, length, vocabulary +- **Logic**: The reasoning pattern to follow +- **Edge cases**: How to handle special situations + +## Basic Few-Shot Pattern + +The fundamental structure of few-shot prompting follows a simple pattern: show examples, then ask for the new task. Consistency in formatting between examples is crucial. The model learns from the pattern you establish. + +``` +[Example 1] +Input: [input 1] +Output: [output 1] + +[Example 2] +Input: [input 2] +Output: [output 2] + +[Example 3] +Input: [input 3] +Output: [output 3] + +Now do this one: +Input: [new input] +Output: +``` + +## Few-Shot for Classification + +Classification is one of the strongest use cases for few-shot learning. By showing examples of each category, you define the boundaries between classes more precisely than instructions alone could achieve. + +### Sentiment Analysis + + +Sentiment analysis classifies text by emotional tone: positive, negative, neutral, or mixed. It's widely used for customer feedback, social media monitoring, and brand perception tracking. + + +Sentiment classification benefits from showing examples of each sentiment type, especially edge cases like "mixed" sentiment that might be ambiguous. + + + +### Topic Classification + +For multi-class categorization, include at least one example per category. This helps the model understand your specific taxonomy, which may differ from its default understanding. + + + +## Few-Shot for Transformation + +Transformation tasks convert input from one form to another while preserving meaning. Examples are essential here because they define exactly what "transformation" means for your use case. + +### Text Rewriting + +Style transformation requires examples that show the exact tone shift you want. Abstract instructions like "make it professional" are interpreted differently. Examples make it concrete. + + + +### Format Conversion + +Format conversion tasks benefit from examples showing edge cases and ambiguous inputs. The model learns your specific conventions for handling tricky cases. + + + +## Few-Shot for Generation + +Generation tasks create new content following a learned pattern. Examples establish length, structure, tone, and what details to highlight. These are hard to specify in instructions alone. + +### Product Descriptions + +Marketing copy benefits enormously from examples because they capture brand voice, feature emphasis, and persuasive techniques that are difficult to describe abstractly. + + + +### Code Documentation + + +Good documentation explains what code does, its parameters, return values, and usage examples. Consistent docstrings enable auto-generated API docs and help IDEs provide better code completion. + + +Documentation style varies widely between projects. Examples teach your specific format, what to include (args, returns, examples), and the level of detail expected. + +>> calculate_bmi(70, 1.75) + 22.86 +""" + +Now document: +Function: +def is_palindrome(text): + cleaned = ''.join(c.lower() for c in text if c.isalnum()) + return cleaned == cleaned[::-1] + +Documentation:`} /> + +## Few-Shot for Extraction + +Extraction tasks pull structured information from unstructured text. Examples define which entities matter, how to format output, and how to handle cases where information is missing or ambiguous. + +### Entity Extraction + + +Named Entity Recognition (NER) identifies and classifies named entities in text into categories like persons, organizations, locations, dates, and products. It's fundamental for information retrieval and knowledge graphs. + + +NER benefits from examples showing your specific entity types and how to handle entities that could fit multiple categories. + + + +### Structured Data Extraction + +Extracting structured data from natural language requires examples showing how to handle missing fields, implicit information, and varying input formats. + + + +## Advanced Few-Shot Techniques + +Beyond basic few-shot, several techniques can improve results for complex tasks. + +### Diverse Examples + +Diversity in examples is more valuable than quantity. Cover different scenarios, edge cases, and potential ambiguities rather than showing similar examples repeatedly. + + + +### Negative Examples + + +Showing "good" vs "bad" examples is called contrastive learning. It helps the model understand not just what you want, but what to avoid. This is especially useful for style and quality judgments. + + +Sometimes showing what *not* to do is as valuable as showing correct examples. Negative examples help the model understand boundaries and avoid common mistakes. + + + +### Edge Case Examples + +Edge cases often determine whether a solution works in production. Including unusual inputs in your examples prevents the model from failing on real-world data that doesn't fit the "happy path." + + + +## How Many Examples? + +
+
+ Simple classification + 2-3 + One per category minimum +
+
+ Complex formatting + 3-5 + Show variations +
+
+ Nuanced style + 4-6 + Capture full range +
+
+ Edge cases + 1-2 + Alongside normal examples +
+
+ +## Example Quality Matters + + + +## Combining Few-Shot with Other Techniques + +Few-shot learning combines powerfully with other prompting techniques. The examples provide the "what" while other techniques can add context, reasoning, or structure. + +### Few-Shot + Role + +Adding a role gives the model context for *why* it's doing the task, which can improve quality and consistency. + +``` +You are a legal contract reviewer. + +[examples of contract clause analysis] + +Now analyze: [new clause] +``` + +### Few-Shot + CoT + +Combining few-shot with Chain of Thought shows not just *what* answer to give, but *how* to reason through to that answer. This is powerful for tasks requiring judgment. + +``` +Classify and explain reasoning. + +Review: "Great features but overpriced" +Thinking: The review mentions positive aspects ("great features") +but also a significant negative ("overpriced"). The negative seems +to outweigh the positive based on the "but" conjunction. +Classification: Mixed-Negative + +[more examples with reasoning] + +Now classify with reasoning: +Review: "Exactly what I needed, arrived faster than expected" +``` + +## Summary + + +Few-shot learning teaches through demonstration and is often more effective than instructions alone. Use 2-5 diverse, correct examples and combine with other techniques for best results. + + + + +In the next chapter, we'll explore iterative refinement: the art of improving prompts through successive attempts. diff --git a/src/content/book/fa/08-iterative-refinement.mdx b/src/content/book/fa/08-iterative-refinement.mdx new file mode 100644 index 00000000..769f879a --- /dev/null +++ b/src/content/book/fa/08-iterative-refinement.mdx @@ -0,0 +1,387 @@ +Prompt engineering is rarely a one-shot process. The best prompts emerge through iteration—testing, observing, and refining until you achieve the desired results. + + +Think of your first prompt as a rough draft. Even experienced prompt engineers rarely nail it on the first try. + + +## The Iteration Cycle + +Effective prompt refinement follows a predictable cycle: write, test, analyze, and improve. Each iteration brings you closer to a prompt that reliably produces the results you need. + + + +## Common Refinement Patterns + +Most prompt failures fall into a handful of categories. Learning to recognize these patterns lets you quickly diagnose and fix issues without starting from scratch. + +### Problem: Output Too Long + +One of the most common issues. Without explicit constraints, models tend to be thorough rather than concise. + + + +### Problem: Output Too Vague + +Vague prompts produce vague outputs. The model can't read your mind about what "better" means or which aspects matter most to you. + + + +### Problem: Wrong Tone + +Tone is subjective and varies by context. What sounds "professional" to the model might not match your organization's voice or the relationship with your recipient. + + + +### Problem: Missing Key Information + +Open-ended requests get open-ended responses. If you need specific types of feedback, you must ask for them explicitly. + + + +### Problem: Inconsistent Format + +Without a template, the model will structure each response differently, making comparison difficult and automation impossible. + + + +## Systematic Refinement Approach + +Random changes waste time. A systematic approach helps you identify problems quickly and fix them efficiently. + +### Step 1: Diagnose the Issue + +Before changing anything, identify what's actually wrong. Use this diagnostic table to map symptoms to solutions: + +
+
+ Symptom + Likely Cause + Solution +
+
+ Too long + No length constraint + Add word/sentence limits +
+
+ Too short + Lacks detail request + Ask for elaboration +
+
+ Off-topic + Vague instructions + Be more specific +
+
+ Wrong format + Format not specified + Define exact structure +
+
+ Wrong tone + Audience not clear + Specify audience/style +
+
+ Inconsistent + No examples provided + Add few-shot examples +
+
+ +### Step 2: Make Targeted Changes + +Resist the urge to rewrite everything. Changing multiple variables at once makes it impossible to know what helped and what hurt. Make one change, test it, then proceed: + +``` +Iteration 1: Add length constraint +Iteration 2: Specify format +Iteration 3: Add example +Iteration 4: Refine tone instructions +``` + +### Step 3: Document What Works + +Prompt engineering knowledge is easily lost. Keep a log of what you tried and why. This saves time when you revisit the prompt later or face similar challenges: + +```markdown +## Prompt: Customer Email Response + +### Version 1 (too formal) +"Write a response to this customer complaint." + +### Version 2 (better tone, still missing structure) +"Write a friendly but professional response to this complaint. +Show empathy first." + +### Version 3 (final - good results) +"Write a response to this customer complaint. Structure: +1. Acknowledge their frustration (1 sentence) +2. Apologize specifically (1 sentence) +3. Explain solution (2-3 sentences) +4. Offer additional help (1 sentence) + +Tone: Friendly, professional, empathetic but not groveling." +``` + +## Real-World Iteration Example + +Let's walk through a complete iteration cycle to see how each refinement builds on the last. Notice how each version addresses specific shortcomings of the previous one. + +### Task: Generate Product Names + + + +## Refinement Strategies by Task Type + +Different tasks fail in predictable ways. Knowing the common failure modes helps you diagnose and fix issues faster. + +### For Content Generation + +Content generation often produces generic, off-target, or poorly formatted output. The fix usually involves being more specific about constraints, providing concrete examples, or defining your brand voice explicitly. + + + +### For Code Generation + +Code output can fail technically (syntax errors, wrong language features) or architecturally (poor patterns, missing cases). Technical issues need version/environment specifics; architectural issues need design guidance. + + + +### For Analysis + +Analysis tasks often produce surface-level or unstructured results. Guide the model with specific frameworks (SWOT, Porter's Five Forces), request multiple viewpoints, or provide a template for the output structure. + + + +### For Q&A + +Question-answering can be too terse or too verbose, and may lack confidence indicators or sources. Specify the detail level you need and whether you want citations or uncertainty expressed. + + + +## The Feedback Loop Technique + +Here's a meta-technique: use the model itself to help improve your prompts. Share what you tried, what you got, and what you wanted. The model can often suggest improvements you hadn't considered. + +``` +I used this prompt: +"[your prompt]" + +And got this output: +"[model output]" + +I wanted something more [describe gap]. How should I modify +my prompt to get better results? +``` + +## A/B Testing Prompts + +For prompts that will be used repeatedly or at scale, don't just pick the first one that works. Test variations to find the most reliable and highest-quality approach. + +``` +Prompt A: "Summarize this article in 3 bullet points." +Prompt B: "Extract the 3 most important insights from this article." +Prompt C: "What are the key takeaways from this article? List 3." +``` + +Run each multiple times, compare: +- Consistency of output +- Quality of information +- Relevance to your needs + +## When to Stop Iterating + +Perfection is the enemy of good enough. Know when your prompt is ready for use and when you're just polishing for diminishing returns. + +
+
+

Ready to Ship

+
+

Output consistently meets requirements

+

Edge cases are handled appropriately

+

Format is reliable and parseable

+

Further improvements show diminishing returns

+
+
+
+

Keep Iterating

+
+

Output is inconsistent across runs

+

Edge cases cause failures

+

Critical requirements are missed

+

You haven't tested enough variations

+
+
+
+ +## Version Control for Prompts + +Prompts are code. For any prompt used in production, treat it with the same rigor: version control, changelogs, and the ability to roll back if something breaks. + + +prompts.chat includes automatic version history for your prompts. Every edit is saved, so you can compare versions and restore previous iterations with one click. + + +For self-managed prompts, use a folder structure: + +``` +prompts/ +├── customer-response/ +│ ├── v1.0.txt # Initial version +│ ├── v1.1.txt # Fixed tone issue +│ ├── v2.0.txt # Major restructure +│ └── current.txt # Symlink to active version +└── changelog.md # Document changes +``` + +## Summary + + +Start simple, observe carefully, change one thing at a time, document what works, and know when to stop. The best prompts aren't written—they're discovered through systematic iteration. + + + + +## Practice: Improve This Prompt + +Try improving this weak prompt yourself. Edit it, then use AI to compare your version with the original: + + + +In the next chapter, we'll explore JSON and YAML prompting for structured data applications. diff --git a/src/content/book/fa/09-json-yaml-prompting.mdx b/src/content/book/fa/09-json-yaml-prompting.mdx new file mode 100644 index 00000000..318619da --- /dev/null +++ b/src/content/book/fa/09-json-yaml-prompting.mdx @@ -0,0 +1,586 @@ +Structured data formats like JSON and YAML are essential for building applications that consume AI outputs programmatically. This chapter covers techniques for reliable structured output generation. + + +JSON and YAML transform AI outputs from freeform text into structured, type-safe data that code can consume directly. + + +## Why Structured Formats? + + + +## JSON Prompting Basics + +JSON (JavaScript Object Notation) is the most common format for programmatic AI outputs. Its strict syntax makes it easy to parse, but also means small errors can break your entire pipeline. + +### Do's and Don'ts: Requesting JSON + + + +### Simple JSON Output + +Start with a schema showing the expected structure. The model will fill in values based on the input text. + +``` +Extract the following information as JSON: + +{ + "name": "string", + "age": number, + "email": "string" +} + +Text: "Contact John Smith, 34 years old, at john@example.com" +``` + +Output: +```json +{ + "name": "John Smith", + "age": 34, + "email": "john@example.com" +} +``` + +### Nested JSON Structures + +Real-world data often has nested relationships. Define each level of your schema clearly, especially for arrays of objects. + +``` +Parse this order into JSON: + +{ + "order_id": "string", + "customer": { + "name": "string", + "email": "string" + }, + "items": [ + { + "product": "string", + "quantity": number, + "price": number + } + ], + "total": number +} + +Order: "Order #12345 for Jane Doe (jane@email.com): 2x Widget ($10 each), +1x Gadget ($25). Total: $45" +``` + +### Ensuring Valid JSON + + +Models often wrap JSON in markdown code blocks or add explanatory text. Be explicit about wanting raw JSON only. + + +Add explicit instructions: + +``` +CRITICAL: Return ONLY valid JSON. No markdown, no explanation, +no additional text before or after the JSON object. + +If a field cannot be determined, use null. +Ensure all strings are properly quoted and escaped. +Numbers should not be quoted. +``` + +## YAML Prompting Basics + +YAML is more human-readable than JSON and supports comments. It's the standard for configuration files, especially in DevOps (Docker, Kubernetes, GitHub Actions). + +### Simple YAML Output + +YAML uses indentation instead of braces. Provide a template showing the expected structure. + +``` +Generate a configuration file in YAML format: + +server: + host: string + port: number + ssl: boolean +database: + type: string + connection_string: string + +Requirements: Production server on port 443 with SSL, PostgreSQL database +``` + +Output: +```yaml +server: + host: "0.0.0.0" + port: 443 + ssl: true +database: + type: "postgresql" + connection_string: "postgresql://user:pass@localhost:5432/prod" +``` + +### Complex YAML Structures + +For complex configurations, be specific about requirements. The model knows common patterns for tools like GitHub Actions, Docker Compose, and Kubernetes. + +``` +Generate a GitHub Actions workflow in YAML: + +Requirements: +- Trigger on push to main and pull requests +- Run on Ubuntu latest +- Steps: checkout, setup Node 18, install dependencies, run tests +- Cache npm dependencies +``` + +## Type Definitions in Prompts + +Type definitions give the model a precise contract for output structure. They're more explicit than examples and easier to validate programmatically. + +### Using TypeScript-like Types + +TypeScript interfaces are familiar to developers and precisely describe optional fields, union types, and arrays. The prompts.chat platform uses this approach for structured prompts. + + + +### JSON Schema Definition + + +JSON Schema is a formal specification for describing JSON structure. It's supported by many validation libraries and API tools. + + +JSON Schema provides constraints like min/max values, required fields, and regex patterns: + +``` +Extract data according to this JSON Schema: + +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "type": "object", + "required": ["title", "author", "year"], + "properties": { + "title": { "type": "string" }, + "author": { "type": "string" }, + "year": { "type": "integer", "minimum": 1000, "maximum": 2100 }, + "genres": { + "type": "array", + "items": { "type": "string" } + }, + "rating": { + "type": "number", + "minimum": 0, + "maximum": 5 + } + } +} + +Book: "1984 by George Orwell (1949) - A dystopian masterpiece. +Genres: Science Fiction, Political Fiction. Rated 4.8/5" +``` + +## Handling Arrays + +Arrays require special attention. Specify whether you need a fixed number of items or a variable-length list, and how to handle empty cases. + +### Fixed-Length Arrays + +When you need exactly N items, state it explicitly. The model will ensure the array has the right length. + +``` +Extract exactly 3 key points as JSON: + +{ + "key_points": [ + "string (first point)", + "string (second point)", + "string (third point)" + ] +} + +Article: [article text] +``` + +### Variable-Length Arrays + +For variable-length arrays, specify what to do when there are zero items. Including a count field helps verify extraction completeness. + +``` +Extract all mentioned people as JSON: + +{ + "people": [ + { + "name": "string", + "role": "string or null if not mentioned" + } + ], + "count": number +} + +If no people are mentioned, return empty array. + +Text: [text] +``` + +## Enum Values and Constraints + +Enums restrict values to a predefined set. This is crucial for classification tasks and anywhere you need consistent, predictable outputs. + +### Do's and Don'ts: Enum Values + + + +### String Enums + +List allowed values explicitly. Use "MUST be one of" language to enforce strict matching. + +``` +Classify this text. The category MUST be one of these exact values: +- "technical" +- "business" +- "creative" +- "personal" + +Return JSON: +{ + "text": "original text (truncated to 50 chars)", + "category": "one of the enum values above", + "confidence": number between 0 and 1 +} + +Text: [text to classify] +``` + +### Validated Numbers + +Numeric constraints prevent out-of-range values. Specify the type (integer vs float) and valid range. + +``` +Rate these aspects. Each score MUST be an integer from 1 to 5. + +{ + "quality": 1-5, + "value": 1-5, + "service": 1-5, + "overall": 1-5 +} + +Review: [review text] +``` + +## Handling Missing Data + +Real-world text often lacks some information. Define how the model should handle missing data to avoid hallucinated values. + +### Do's and Don'ts: Missing Information + + + +### Null Values + +Explicitly allow null and instruct the model not to invent information. This is safer than having the model guess. + +``` +Extract information. Use null for any field that cannot be +determined from the text. Do NOT invent information. + +{ + "company": "string or null", + "revenue": "number or null", + "employees": "number or null", + "founded": "number (year) or null", + "headquarters": "string or null" +} + +Text: "Apple, headquartered in Cupertino, was founded in 1976." +``` + +Output: +```json +{ + "company": "Apple", + "revenue": null, + "employees": null, + "founded": 1976, + "headquarters": "Cupertino" +} +``` + +### Default Values + +When defaults make sense, specify them in the schema. This is common for configuration extraction. + +``` +Extract settings with these defaults if not specified: + +{ + "theme": "light" (default) | "dark", + "language": "en" (default) | other ISO code, + "notifications": true (default) | false, + "fontSize": 14 (default) | number +} + +User preferences: "I want dark mode and larger text (18px)" +``` + +## Multi-Object Responses + +Often you need to extract multiple items from a single input. Define the array structure and any sorting/grouping requirements. + +### Array of Objects + +For lists of similar items, define the object schema once and specify it's an array. + +``` +Parse this list into JSON array: + +[ + { + "task": "string", + "priority": "high" | "medium" | "low", + "due": "ISO date string or null" + } +] + +Todo list: +- Finish report (urgent, due tomorrow) +- Call dentist (low priority) +- Review PR #123 (medium, due Friday) +``` + +### Grouped Objects + +Grouping tasks require categorization logic. The model will sort items into the categories you define. + +``` +Categorize these items into JSON: + +{ + "fruits": ["string array"], + "vegetables": ["string array"], + "other": ["string array"] +} + +Items: apple, carrot, bread, banana, broccoli, milk, orange, spinach +``` + +## YAML for Configuration Generation + +YAML shines for DevOps configurations. The model knows standard patterns for common tools and can generate production-ready configs. + +### Do's and Don'ts: YAML Configs + + + +### Docker Compose + +Specify the services you need and any special requirements. The model will handle the YAML syntax and best practices. + +``` +Generate a docker-compose.yml for: +- Node.js app on port 3000 +- PostgreSQL database +- Redis cache +- Nginx reverse proxy + +Include: +- Health checks +- Volume persistence +- Environment variables from .env file +- Network isolation +``` + +### Kubernetes Manifests + +Kubernetes manifests are verbose but follow predictable patterns. Provide the key parameters and the model will generate compliant YAML. + +``` +Generate Kubernetes deployment YAML: + +Deployment: +- Name: api-server +- Image: myapp:v1.2.3 +- Replicas: 3 +- Resources: 256Mi memory, 250m CPU (requests) +- Health checks: /health endpoint +- Environment from ConfigMap: api-config + +Also generate matching Service (ClusterIP, port 8080) +``` + +## Validation and Error Handling + +For production systems, build validation into your prompts. This catches errors before they propagate through your pipeline. + +### Self-Validation Prompt + +Ask the model to validate its own output against rules you specify. This catches format errors and invalid values. + +``` +Extract data as JSON, then validate your output. + +Schema: +{ + "email": "valid email format", + "phone": "E.164 format (+1234567890)", + "date": "ISO 8601 format (YYYY-MM-DD)" +} + +After generating JSON, check: +1. Email contains @ and valid domain +2. Phone starts with + and contains only digits +3. Date is valid and parseable + +If validation fails, fix the issues before responding. + +Text: [contact information] +``` + +### Error Response Format + +Define separate success and error formats. This makes programmatic handling much easier. + +``` +Attempt to extract data. If extraction fails, return error format: + +Success format: +{ + "success": true, + "data": { ... extracted data ... } +} + +Error format: +{ + "success": false, + "error": "description of what went wrong", + "partial_data": { ... any data that could be extracted ... } +} +``` + +## JSON vs YAML: When to Use Which + +
+
+
Use JSON When
+
+

Programmatic parsing needed

+

API responses

+

Strict type requirements

+

JavaScript/Web integration

+

Compact representation

+
+
+
+
Use YAML When
+
+

Human readability matters

+

Configuration files

+

Comments are needed

+

DevOps/Infrastructure

+

Deep nested structures

+
+
+
+ +## Prompts.chat Structured Prompts + +On prompts.chat, you can create prompts with structured output formats: + +``` +When creating a prompt on prompts.chat, you can specify: + +Type: STRUCTURED +Format: JSON or YAML + +The platform will: +- Validate outputs against your schema +- Provide syntax highlighting +- Enable easy copying of structured output +- Support template variables in your schema +``` + +## Common Pitfalls + + +These three issues cause most JSON parsing failures. Check for them when your code can't parse AI output. + + +### 1. Markdown Code Blocks + +**Problem:** Model wraps JSON in ```json blocks + +**Solution:** +``` +Return ONLY the JSON object. Do not wrap in markdown code blocks. +Do not include ```json or ``` markers. +``` + +### 2. Trailing Commas + +**Problem:** Invalid JSON due to trailing commas + +**Solution:** +``` +Ensure valid JSON syntax. No trailing commas after the last +element in arrays or objects. +``` + +### 3. Unescaped Strings + +**Problem:** Quotes or special characters break JSON + +**Solution:** +``` +Properly escape special characters in strings: +- \" for quotes +- \\ for backslashes +- \n for newlines +``` + +## Summary + + +Define schemas explicitly using TypeScript interfaces or JSON Schema. Specify types and constraints, handle nulls and defaults, request self-validation, and choose the right format for your use case. + + + + +This completes Part II on techniques. In Part III, we'll explore practical applications across different domains. diff --git a/src/content/book/fa/10-system-prompts-personas.mdx b/src/content/book/fa/10-system-prompts-personas.mdx new file mode 100644 index 00000000..c6737cda --- /dev/null +++ b/src/content/book/fa/10-system-prompts-personas.mdx @@ -0,0 +1,435 @@ +System prompts are like giving AI its personality and job description before a conversation starts. Think of it as the "backstage instructions" that shape everything the AI says. + + +A system prompt is a special message that tells the AI who it is, how to behave, and what it can or can't do. Users don't usually see this message, but it affects every response. + + + +System prompts build on the concepts from [Role-Based Prompting](/book/04-role-based-prompting). While role prompts assign a persona within your message, system prompts set that identity at a deeper level that persists across the entire conversation. + + +## How System Prompts Work + +When you chat with AI, there are actually three types of messages: + + + +The system message stays active for the whole conversation. It's like the AI's "instruction manual." + +## Building a System Prompt + +A good system prompt has five parts. Think of them as filling out a character sheet for the AI: + + + +### Example: A Coding Tutor + + + +## Persona Patterns + +Different tasks need different AI personalities. Here are three common patterns you can adapt: + +### 1. The Expert + +Best for: Learning, research, professional advice + + + +### 2. The Assistant + +Best for: Productivity, organization, getting things done + + + +### 3. The Character + +Best for: Creative writing, roleplay, entertainment + + + +## Advanced Techniques + +### Layered Instructions + +Think of your system prompt like an onion with layers. The inner layers are most important: + + + +### Adaptive Behavior + +Make your AI adjust to different users automatically: + + + +### Conversation Memory + +AI doesn't remember past conversations, but you can tell it to track things within the current chat: + + + +## Real-World Examples + +Here are complete system prompts for common use cases. Click to try them! + +### Customer Support Bot + + + +### Study Buddy + + + +### Writing Coach + + + +## Testing Your System Prompt + +Before using a system prompt for real, test it! Here's what to check: + + + +### Understanding Jailbreak Attacks + +"Jailbreaking" is when someone tries to trick AI into ignoring its rules. Understanding these attacks helps you build better defenses. + + + +### More Test Scenarios + +Use these interactive examples to see how a well-designed system prompt handles tricky situations: + +#### Test 1: Jailbreak Attempt + +See how a good system prompt resists attempts to override it: + + + +#### Test 2: Stay in Character + +Test if the AI maintains its persona when pushed: + + + +#### Test 3: Boundary Enforcement + +Check if the AI respects its stated limitations: + + + +#### Test 4: Reveal System Prompt + +See if the AI protects its instructions: + + + +#### Test 5: Conflicting Instructions + +Test how the AI handles contradictory requests: + + + + +A well-crafted system prompt will: +- Politely decline inappropriate requests +- Stay in character while redirecting +- Not reveal confidential instructions +- Handle edge cases gracefully + + +## Quick Reference + +
+
+

Do

+
    +
  • Give a clear identity
  • +
  • List specific capabilities
  • +
  • Set explicit boundaries
  • +
  • Define the tone and style
  • +
  • Include example responses
  • +
+
+
+

Don't

+
    +
  • Be vague about the role
  • +
  • Forget to set limits
  • +
  • Make it too long (500 words max)
  • +
  • Contradict yourself
  • +
  • Assume the AI will "figure it out"
  • +
+
+
+ +## Summary + +System prompts are the AI's instruction manual. They set up: +- **Who** the AI is (identity and expertise) +- **What** it can and can't do (capabilities and limits) +- **How** it should respond (tone, format, style) + + +Begin with a short system prompt and add more rules as you discover what's needed. A clear 100-word prompt beats a confusing 500-word one. + + + + + + +In the next chapter, we'll explore prompt chaining: connecting multiple prompts together for complex multi-step tasks. diff --git a/src/content/book/fa/11-prompt-chaining.mdx b/src/content/book/fa/11-prompt-chaining.mdx new file mode 100644 index 00000000..9f54da52 --- /dev/null +++ b/src/content/book/fa/11-prompt-chaining.mdx @@ -0,0 +1,379 @@ +Prompt chaining breaks complex tasks into sequences of simpler prompts, where each step's output feeds into the next. This technique dramatically improves reliability and enables sophisticated workflows that would be impossible with a single prompt. + + +Just like a factory assembly line breaks manufacturing into specialized stations, prompt chaining breaks AI tasks into specialized steps. Each step does one thing well, and the combined output is far better than trying to do everything at once. + + +## Why Chain Prompts? + +Single prompts struggle with complex tasks because they try to do too much at once. The AI has to simultaneously understand, analyze, plan, and generate, which leads to errors and inconsistencies. + +
+
+

Single Prompt Struggles

+
+

Multi-step reasoning gets confused

+

Different "modes" of thinking clash

+

Complex outputs lack consistency

+

No opportunity for quality control

+
+
+
+

Chaining Solves This

+
+

Each step focuses on one task

+

Specialized prompts for each mode

+

Validate between steps

+

Debug and improve individual steps

+
+
+
+ +## Basic Chaining Pattern + +The simplest chain passes output from one prompt directly to the next. Each step has a clear, focused purpose. + +
+
+
+

Prompt 1

+

(Extract)

+
+

Input

+
+
→
+
+
+

Prompt 2

+

(Analyze)

+
+

Intermediate

+
+
→
+
+
+

Prompt 3

+

(Generate)

+
+

Output

+
+
+ + +The most common chain pattern is **Extract → Transform → Generate**. First extract raw data, then reshape it for your purpose, then generate the final output. This pattern works for almost any content task. + + +## Chain Types + +Different tasks require different chain architectures. Choose the pattern that matches your workflow. + + + +### Sequential Chain + +The most straightforward pattern: each step depends on the previous. Think of it as a relay race where each runner passes the baton to the next. + + + +### Parallel Chain + +When you need multiple perspectives on the same input, run prompts in parallel and merge results. This is faster than sequential chains and provides richer analysis. + + + +### Conditional Chain + +Route inputs through different paths based on classification. This is like a decision tree where the AI first categorizes the input, then handles each category differently. + + + +### Iterative Chain + +Keep refining output until it meets quality standards. The AI generates, evaluates, and improves in a loop until satisfied or max iterations reached. + + +Always set a maximum number of iterations (typically 3-5) to prevent infinite loops and control costs. The law of diminishing returns applies: most improvement happens in the first 2-3 iterations. + + += 8: EXIT LOOP' } + ]} +/> + +## Common Chain Patterns + +These battle-tested patterns solve common problems. Use them as starting points and adapt to your needs. + +### Extract → Transform → Generate + +The workhorse of content processing. Pull data out, reshape it, then create something new. + +
+

Best For

+

Document summarization, report generation, content repurposing, data-to-narrative conversion

+
+ + + +### Analyze → Plan → Execute + +Perfect for code refactoring, project planning, or any task where you need to understand before acting. + +
+

Best For

+

Code refactoring, project planning, troubleshooting, strategic decision-making, complex problem solving

+
+ + {\n const { email, password } = req.body;\n if (!email || !isValidEmail(email)) {\n return res.status(400).json({ error: 'Invalid email' });\n }\n next();\n};" } + ]} +/> + +### Generate → Critique → Refine + +The self-improvement loop. Generate content, have the AI evaluate it critically, then improve based on that feedback. This mimics how professional writers and editors work together. + +
+

Best For

+

Marketing copy, creative writing, email drafts, presentations, any content that benefits from revision

+
+ + + +## Implementing Chains + +You can implement chains manually for experimentation, or programmatically for production systems. Start simple and add complexity as needed. + +### Manual Chaining + +The copy-paste approach is perfect for prototyping and experimentation. Run each prompt manually, examine the output, and paste it into the next prompt. + + + +### Programmatic Chaining + +For production systems, automate the chain with code. This enables error handling, logging, and integration with your application. + + + +### Using Chain Templates + +Define chains as configuration files for reusability and easy modification. This separates prompt logic from application code. + + + +## Error Handling in Chains + +Chains can fail at any step. Build in validation, retries, and fallbacks to make your chains robust. + + + + +If one step produces bad output, every following step will be affected. Always validate critical intermediate results before passing them forward. + + +### Validation Between Steps + +Add a validation step after any step that produces structured data. This catches errors early before they cascade. + + + +### Fallback Chains + +When your primary approach fails, have a simpler backup ready. Trade capability for reliability. + + + +## Chain Optimization + +Once your chain works, optimize for speed, cost, and reliability. These often trade off against each other. + +
+
+

Reducing Latency

+
+

Parallelize independent steps

+

Cache intermediate results

+

Use smaller models for simple steps

+

Batch similar operations

+
+
+
+

Reducing Cost

+
+

Use cheaper models for classification

+

Limit iterations in loops

+

Short-circuit when possible

+

Cache repeated queries

+
+
+
+

Improving Reliability

+
+

Add validation between steps

+

Include retry logic

+

Log intermediate results

+

Implement fallback paths

+
+
+
+ +## Real-World Chain Example + +Let's walk through a complete production chain. This content pipeline transforms a raw idea into a polished article package. + +### Content Pipeline Chain + + + +## Summary + +Prompt chaining transforms what AI can accomplish by breaking impossible tasks into achievable steps. + +
+
+

Chaining Enables

+
+

Complex multi-step workflows

+

Higher quality through specialization

+

Better error handling and validation

+

Modular, reusable prompt components

+
+
+
+

Key Principles

+
+

Break complex tasks into simple steps

+

Design clear interfaces between steps

+

Validate intermediate outputs

+

Build in error handling and fallbacks

+

Optimize for your constraints

+
+
+
+ + +Begin with a 2-3 step sequential chain. Get it working reliably before adding complexity. Most tasks don't need elaborate chain architectures. + + + + +In the next chapter, we'll explore multimodal prompting: working with images, audio, and other non-text content. diff --git a/src/content/book/fa/12-handling-edge-cases.mdx b/src/content/book/fa/12-handling-edge-cases.mdx new file mode 100644 index 00000000..4708ee3c --- /dev/null +++ b/src/content/book/fa/12-handling-edge-cases.mdx @@ -0,0 +1,580 @@ +Prompts that work perfectly in testing often fail in the real world. Users send empty messages, paste walls of text, make ambiguous requests, and sometimes try to break your system intentionally. This chapter teaches you to build prompts that handle the unexpected gracefully. + + +80% of production issues come from inputs you never anticipated. A prompt that handles edge cases well is worth more than a "perfect" prompt that only works with ideal inputs. + + +## Why Edge Cases Break Prompts + +When a prompt encounters unexpected input, it typically fails in one of three ways: + +**Silent Failures**: The model produces output that looks correct but contains errors. These are the most dangerous because they're hard to detect. + +**Confused Responses**: The model misinterprets the request and answers a different question than what was asked. + +**Hallucinated Handling**: The model invents a way to handle the edge case that doesn't match your intended behavior. + + + +## Categories of Edge Cases + +Understanding what can go wrong helps you prepare for it. Edge cases fall into three main categories: + +### Input Edge Cases + +These are problems with the data itself: + + + +### Domain Edge Cases + +These are requests that push the boundaries of your prompt's purpose: + + + +### Adversarial Edge Cases + +These are deliberate attempts to misuse your system: + + + +## Input Validation Patterns + +The key to handling edge cases is explicit instructions. Don't assume the model will "figure it out" - tell it exactly what to do in each scenario. + +### Handling Empty Input + +The most common edge case is receiving nothing at all, or input that's essentially empty (just whitespace or greetings). + + + +### Handling Long Input + +When input exceeds what you can reasonably process, fail gracefully rather than silently truncating. + + + +### Handling Ambiguous Requests + +When a request could mean multiple things, asking for clarification is better than guessing wrong. + + + +## Building Defensive Prompts + +A defensive prompt anticipates failure modes and defines explicit behavior for each. Think of it as error handling for natural language. + +### The Defensive Template + +Every robust prompt should address these four areas: + + + +### Example: Defensive Data Extraction + +This prompt extracts contact information but handles every edge case explicitly. Notice how each potential failure has a defined response. + + + +## Handling Out-of-Scope Requests + +Every prompt has boundaries. Defining them explicitly prevents the model from wandering into territory where it might give bad advice or make things up. + +### Graceful Scope Limits + +The best out-of-scope responses do three things: acknowledge the request, explain the limitation, and offer an alternative. + + + +### Handling Knowledge Cutoffs + +Be honest about what you don't know. Users trust AI more when it admits limitations. + + + +## Adversarial Input Handling + +Some users will try to manipulate your prompts, either out of curiosity or malicious intent. Building defenses into your prompts reduces these risks. + +### Prompt Injection Defense + +Prompt injection is when a user tries to override your instructions by embedding their own commands in the input. The key defense is treating user input as data, never as instructions. + + + + +Prompt injection defenses reduce risk but can't eliminate it entirely. For high-stakes applications, combine prompt defenses with input sanitization, output filtering, and human review. + + +### Handling Sensitive Requests + +Some requests require special handling due to safety, legal, or ethical concerns. Define these boundaries explicitly. + + + +## Error Recovery Patterns + +Even well-designed prompts will encounter situations they can't handle perfectly. The goal is to fail helpfully. + +### Graceful Degradation + +When you can't fully complete a task, offer what you can rather than failing completely. + + + +### Confidence Indicators + +Teach your prompts to express uncertainty. This helps users know when to trust the output and when to verify. + + + + + +## Testing Edge Cases + +Before deploying a prompt, systematically test it against the edge cases you've anticipated. This checklist helps ensure you haven't missed common failure modes. + +### Edge Case Testing Checklist + + + + + + + + + +### Creating a Test Suite + +For production prompts, create a systematic test suite. Here's a pattern you can adapt: + + + +## Real-World Example: Robust Customer Service Bot + +This comprehensive example shows how all the patterns come together in a production-ready prompt. Notice how every edge case has explicit handling. + + + +## Summary + +Building robust prompts requires thinking about what can go wrong before it does. The key principles: + + + + +In production, everything that can go wrong eventually will. A prompt that handles edge cases gracefully is worth more than a "perfect" prompt that only works with ideal inputs. + + + + +In the next chapter, we'll explore how to work with multiple AI models and compare their outputs. diff --git a/src/content/book/fa/13-multimodal-prompting.mdx b/src/content/book/fa/13-multimodal-prompting.mdx new file mode 100644 index 00000000..376960ae --- /dev/null +++ b/src/content/book/fa/13-multimodal-prompting.mdx @@ -0,0 +1,665 @@ +For most of history, computers worked with one type of data at a time: text in one program, images in another, audio somewhere else. But humans don't experience the world this way. We see, hear, read, and speak simultaneously, combining all these inputs to understand our environment. + +**Multimodal AI** changes everything. These models can process multiple types of information together—analyzing an image while reading your question about it, or generating images from your text descriptions. This chapter teaches you how to communicate effectively with these powerful systems. + + +"Multi" means many, and "modal" refers to modes or types of data. A multimodal model can work with multiple modalities: text, images, audio, video, or even code. Instead of separate tools for each type, one model understands them all together. + + +## Why Multimodal Matters + +Traditional AI required you to describe everything in words. Want to ask about an image? You'd have to describe it first. Want to analyze a document? You'd need to transcribe it manually. Multimodal models eliminate these barriers. + + + +## Why Prompting Matters Even More for Multimodal + +With text-only models, the AI receives exactly what you type. But with multimodal models, the AI must interpret visual or audio information—and interpretation requires guidance. + + + +**Without guidance**, the model might describe colors, layout, or irrelevant details. **With guidance**, it focuses on what actually matters to you. + + +When you look at an image, you instantly know what's important based on your context and goals. The AI doesn't have this context unless you provide it. A photo of a crack in a wall could be: a structural engineering concern, an artistic texture, or irrelevant background. Your prompt determines how the AI interprets it. + + +## The Multimodal Landscape + +Different models have different capabilities. Here's what's available in 2025: + +### Understanding Models (Input → Analysis) + +These models accept various media types and produce text analysis or responses. + + + +### Generation Models (Text → Media) + +These models create images, audio, or video from text descriptions. + + + + +The multimodal landscape changes quickly. New models launch frequently, and existing models gain capabilities through updates. Always check the latest documentation for current features and limitations. + + +## Image Understanding Prompts + +The most common multimodal use case is asking AI to analyze images. The key is providing context about what you need. + +### Basic Image Analysis + +Start with a clear request structure. Tell the model what aspects to focus on. + + + +### Structured Output for Images + +When you need to process image analysis programmatically, request JSON output. + + + +### Comparative Analysis + +Comparing multiple images requires clear labeling and specific comparison criteria. + + + +## Document and Screenshot Analysis + +One of the most practical applications of multimodal AI is analyzing documents, screenshots, and UI elements. This saves hours of manual transcription and review. + +### Document Extraction + +Scanned documents, photos of receipts, and PDFs as images can all be processed. The key is telling the model what type of document it is and what information you need. + + + +### Screenshot and UI Analysis + +Screenshots are goldmines for debugging, UX review, and documentation. Guide the AI to focus on what matters. + + + +### Error Message Analysis + +When you encounter an error, a screenshot often contains more context than copying the error text alone. + + + +## Image Generation Prompts + +Generating images from text descriptions is an art form. The more specific and structured your prompt, the closer the result will match your vision. + +### The Anatomy of an Image Prompt + +Effective image generation prompts have several components: + + + +### Basic Image Generation + + + +### Scene Building + +For complex scenes, describe layers from foreground to background. + + + +## Audio Prompting + +Audio processing opens up transcription, analysis, and understanding of spoken content. The key is providing context about what the audio contains. + +### Enhanced Transcription + +Basic transcription is just the start. With good prompts, you can get speaker identification, timestamps, and domain-specific accuracy. + + + +### Audio Content Analysis + +Beyond transcription, AI can analyze the content, tone, and key moments in audio. + + + +## Video Prompting + +Video combines visual and audio analysis over time. The challenge is guiding the AI to focus on the relevant aspects across the entire duration. + +### Video Understanding + + + +### Video Content Extraction + +For specific information extraction from videos, be precise about what you need. + + + +## Multimodal Combinations + +The real power of multimodal AI emerges when you combine different types of input. These combinations enable analysis that would be impossible with any single modality. + +### Image + Text Verification + +Check if images and their descriptions match—essential for e-commerce, content moderation, and quality assurance. + + + +### Screenshot + Code Debugging + +One of the most powerful combinations for developers: seeing the visual bug alongside the code. + + + +### Multi-Image Decision Making + +When choosing between options, structured comparison helps make better decisions. + + + +## Best Practices for Multimodal Prompts + +Getting great results from multimodal AI requires understanding both its capabilities and limitations. + +### What Makes Multimodal Prompts Effective + + + +### Common Pitfalls to Avoid + + + +### Handling Limitations Gracefully + + + + diff --git a/src/content/book/fa/14-context-engineering.mdx b/src/content/book/fa/14-context-engineering.mdx new file mode 100644 index 00000000..b9c69b6d --- /dev/null +++ b/src/content/book/fa/14-context-engineering.mdx @@ -0,0 +1,287 @@ +Understanding context is essential for building AI applications that actually work. This chapter covers everything you need to know about giving AI the right information at the right time. + + +AI models are stateless. They don't remember past conversations. Every time you send a message, you need to include everything the AI needs to know. This is called "context engineering." + + +## What is Context? + +Context is all the information you give to AI alongside your question. Think of it like this: + + + +Without context, the AI has no idea what "status" you're asking about. With context, it can give a useful answer. + +### The Context Window + +Remember from earlier chapters: AI has a limited "context window" - the maximum amount of text it can see at once. This includes: + + + +## AI is Stateless + + +AI doesn't remember anything between conversations. Every API call starts fresh. If you want the AI to "remember" something, YOU have to include it in the context every time. + + +This is why chatbots send your entire conversation history with each message. It's not that the AI remembers - it's that the app re-sends everything. + + + +The AI will say it doesn't know because it truly doesn't have access to any previous context. + +## RAG: Retrieval-Augmented Generation + +RAG is a technique for giving AI access to knowledge it wasn't trained on. Instead of trying to fit everything into the AI's training, you: + +1. **Store** your documents in a searchable database +2. **Search** for relevant documents when a user asks a question +3. **Retrieve** the most relevant pieces +4. **Augment** your prompt with those pieces +5. **Generate** an answer using that context + +
+

How RAG Works:

+
+
+ 1 + User asks: "What's our refund policy?" +
+
+ 2 + System searches your documents for "refund policy" +
+
+ 3 + Finds relevant section from your policy document +
+
+ 4 + Sends to AI: "Based on this policy: [text], answer: What's our refund policy?" +
+
+ 5 + AI generates accurate answer using your actual policy +
+
+
+ +### Why RAG? + +
+
+

RAG Advantages

+
    +
  • Uses your actual, current data
  • +
  • Reduces hallucinations
  • +
  • Can cite sources
  • +
  • Easy to update (just update documents)
  • +
  • No expensive fine-tuning needed
  • +
+
+
+

When to Use RAG

+
    +
  • Customer support bots
  • +
  • Documentation search
  • +
  • Internal knowledge bases
  • +
  • Any domain-specific Q&A
  • +
  • When accuracy matters
  • +
+
+
+ +## Embeddings: How Search Works + +How does RAG know which documents are "relevant"? It uses **embeddings** - a way to turn text into numbers that capture meaning. + +### What Are Embeddings? + +An embedding is a list of numbers (a "vector") that represents the meaning of text. Similar meanings = similar numbers. + + + +### Semantic Search + +With embeddings, you can search by meaning, not just keywords: + + + +This is why RAG is so powerful - it finds relevant information even when the exact words don't match. + +## Function Calling / Tool Use + +Function calling lets AI use external tools - like searching the web, checking a database, or calling an API. + + +Different AI providers call this different things: "function calling" (OpenAI), "tool use" (Anthropic/Claude), or "tools" (general term). They all mean the same thing. + + +### How It Works + +1. You tell the AI what tools are available +2. AI decides if it needs a tool to answer +3. AI outputs a structured request for the tool +4. Your code runs the tool and returns results +5. AI uses the results to form its answer + + + +## Summarization: Managing Long Conversations + +As conversations get longer, you'll hit the context window limit. Since AI is stateless (it doesn't remember anything), long conversations can overflow. The solution? **Summarization**. + +### The Problem + + + +### Summarization Strategies + +Different approaches work for different use cases. Click each strategy to see how it processes the same conversation: + + + +### What to Capture in Summaries + +A good conversation summary preserves what matters: + + + +### Try It: Create a Summary + + + +### When to Summarize + + + +## MCP: Model Context Protocol + +MCP (Model Context Protocol) is a standard way to connect AI to external data and tools. Instead of building custom integrations for each AI provider, MCP provides a universal interface. + +### Why MCP? + + + +### MCP Provides + +- **Resources**: Data the AI can read (files, database records, API responses) +- **Tools**: Actions the AI can take (search, create, update, delete) +- **Prompts**: Pre-built prompt templates + + +This platform has an MCP server! You can connect it to Claude Desktop or other MCP-compatible clients to search and use prompts directly from your AI assistant. + + +## Building Context: The Complete Picture + + + +## Best Practices + + + +## Summary + +Context engineering is about giving AI the right information: + +- **AI is stateless** - include everything it needs every time +- **RAG** retrieves relevant documents to augment prompts +- **Embeddings** enable semantic search (meaning, not just keywords) +- **Function calling** lets AI use external tools +- **Summarization** manages long conversations +- **MCP** standardizes how AI connects to data and tools + + +The quality of AI output depends on the quality of context you provide. Better context = better answers. + diff --git a/src/content/book/fa/15-common-pitfalls.mdx b/src/content/book/fa/15-common-pitfalls.mdx new file mode 100644 index 00000000..3c9c2814 --- /dev/null +++ b/src/content/book/fa/15-common-pitfalls.mdx @@ -0,0 +1,373 @@ +Even experienced prompt engineers fall into predictable traps. The good news? Once you recognize these patterns, they're easy to avoid. This chapter walks through the most common pitfalls, explains why they happen, and gives you concrete strategies to sidestep them. + + +A single pitfall can turn a powerful AI into a frustrating tool. Understanding these patterns is often the difference between "AI doesn't work for me" and "AI transformed my workflow." + + +## The Vagueness Trap + +**The Pattern**: You know what you want, so you assume the AI will figure it out too. But vague prompts produce vague results. + + + +**Why it happens**: We naturally skip details when we think they're "obvious." But what's obvious to you isn't obvious to a model that has no context about your situation, audience, or goals. + + + +## The Overloading Trap + +**The Pattern**: You try to get everything in one prompt—comprehensive, funny, professional, beginner-friendly, advanced, SEO-optimized, and short. The result? The AI misses half your requirements or produces a confused mess. + + + +**Why it happens**: Fear of multiple interactions, or wanting to "get it all out" in one go. But cognitive overload affects AI just like it affects humans—too many competing requirements leads to dropped balls. + + + + +When a single prompt gets overloaded, [prompt chaining](/book/11-prompt-chaining) is often the solution. Break complex tasks into a sequence of focused prompts, where each step builds on the previous one. + + +## The Assumption Trap + +**The Pattern**: You reference something "from earlier" or assume the AI knows your project, your company, or your previous conversations. It doesn't. + + + +**Why it happens**: AI conversations feel like talking to a colleague. But unlike colleagues, most AI models have no persistent memory between sessions—each conversation starts fresh. + + + +## The Leading Question Trap + +**The Pattern**: You phrase your question in a way that embeds your assumption, getting back confirmation rather than insight. + + + +**Why it happens**: We often seek confirmation, not information. Our phrasing unconsciously pushes toward the answer we expect or want. + + + +## The Trust Everything Trap + +**The Pattern**: AI responses sound confident and authoritative, so you accept them without verification. But confidence doesn't equal accuracy. + + + +**Why it happens**: AI sounds confident even when completely wrong. We're also prone to "automation bias"—the tendency to trust computer outputs more than we should. + + + +## The One-Shot Trap + +**The Pattern**: You send one prompt, get a mediocre result, and conclude that AI "doesn't work" for your use case. But great results almost always require iteration. + + + +**Why it happens**: We expect AI to read our minds on the first try. We don't expect to iterate with Google searches, but somehow expect perfection from AI. + + + +## The Format Neglect Trap + +**The Pattern**: You focus on what you want the AI to say, but forget to specify how it should be formatted. Then you get prose when you needed JSON, or a wall of text when you needed bullet points. + + + +**Why it happens**: We focus on content over structure. But if you need to parse the output programmatically, or paste it somewhere specific, format matters as much as content. + + + +## The Context Window Trap + +**The Pattern**: You paste an enormous document and expect comprehensive analysis. But models have limits—they may truncate, lose focus, or miss important details in long inputs. + + + + + +## The Anthropomorphization Trap + +**The Pattern**: You treat AI like a human colleague—expecting it to "enjoy" tasks, remember you, or care about outcomes. It doesn't. + + + +**Why it happens**: AI responses are so human-like that we naturally slip into social patterns. But emotional appeals don't make the AI try harder—clear instructions do. + + +Instead of emotional appeals, focus on: clear requirements, good examples, specific constraints, and explicit success criteria. These improve outputs. "Please try really hard" doesn't. + + +## The Security Neglect Trap + +**The Pattern**: In the rush to get things working, you include sensitive information in prompts—API keys, passwords, personal data, or proprietary information. + + + +**Why it happens**: Focus on functionality over security. But remember: prompts often go to external servers, may be logged, and could be used for training. + + + +## The Hallucination Ignorance Trap + +**The Pattern**: You ask for citations, statistics, or specific facts, and assume they're real because the AI stated them confidently. But AI regularly invents plausible-sounding information. + + + +**Why it happens**: AI generates text that sounds authoritative. It doesn't "know" when it's making things up—it's predicting likely text, not retrieving verified facts. + + + +## Pre-Send Checklist + +Before sending any important prompt, run through this quick checklist: + + + + + +## Analyze Your Prompts + +Use AI to get instant feedback on your prompt quality. Paste any prompt and get a detailed analysis: + + + +## Debug This Prompt + +Can you spot what's wrong with this prompt? + + diff --git a/src/content/book/fa/16-ethics-responsible-use.mdx b/src/content/book/fa/16-ethics-responsible-use.mdx new file mode 100644 index 00000000..c2b8ba5e --- /dev/null +++ b/src/content/book/fa/16-ethics-responsible-use.mdx @@ -0,0 +1,357 @@ +The prompts you write shape how AI behaves. A well-crafted prompt can educate, assist, and empower. A careless one can deceive, discriminate, or cause harm. As prompt engineers, we're not just users—we're designers of AI behavior, and that comes with real responsibility. + +This chapter isn't about rules imposed from above. It's about understanding the impact of our choices and building habits that lead to AI use we can be proud of. + + +AI amplifies whatever it's given. A biased prompt produces biased outputs at scale. A deceptive prompt enables deception at scale. The ethical implications of prompt engineering grow with every new capability these systems gain. + + +## Ethical Foundations + +Every decision in prompt engineering connects to a few core principles: + + + +### The Prompt Engineer's Role + +You have more influence than you might realize: + +- **What AI produces**: Your prompts determine the content, tone, and quality of outputs +- **How AI interacts**: Your system prompts shape personality, boundaries, and user experience +- **What safeguards exist**: Your design choices determine what the AI will and won't do +- **How mistakes are handled**: Your error handling determines whether failures are graceful or harmful + +## Avoiding Harmful Outputs + +The most fundamental ethical obligation is preventing your prompts from causing harm. + +### Categories of Harmful Content + + + + +CSAM stands for **Child Sexual Abuse Material**. Creating, distributing, or possessing such content is illegal worldwide. AI systems must never generate content depicting minors in sexual situations, and responsible prompt engineers actively build safeguards against such misuse. + + +### Building Safety Into Prompts + +When building AI systems, include explicit safety guidelines: + + + +### The Intent vs. Impact Framework + +Not every sensitive request is malicious. Use this framework for ambiguous cases: + + + +## Addressing Bias + +AI models inherit biases from their training data—historical inequities, representation gaps, cultural assumptions, and linguistic patterns. As prompt engineers, we can either amplify these biases or actively counteract them. + +### How Bias Manifests + + + +### Testing for Bias + + + +### Mitigating Bias in Practice + + + +## Transparency and Disclosure + +When should you tell people AI was involved? The answer depends on context—but the trend is toward more disclosure, not less. + +### When Disclosure Matters + + + +### How to Disclose Appropriately + + + +Common disclosure phrases that work well: +- "Written with AI assistance" +- "AI-generated first draft, human edited" +- "Analysis performed using AI tools" +- "Created with AI, reviewed and approved by [name]" + +## Privacy Considerations + +Every prompt you send contains data. Understanding where that data goes—and what shouldn't be in it—is essential. + +### What Never Belongs in Prompts + + + +### Safe Data Handling Pattern + + + + +**PII** stands for **Personally Identifiable Information**—any data that can identify a specific individual. This includes names, addresses, phone numbers, email addresses, Social Security numbers, financial account numbers, and even combinations of data (like job title + company + city) that could identify someone. When prompting AI, always anonymize or remove PII to protect privacy. + + + + +## Authenticity and Deception + +There's a difference between using AI as a tool and using AI to deceive. + +### The Legitimacy Line + + + +Key questions to ask: +- Would the recipient expect this to be original human work? +- Am I gaining unfair advantage through deception? +- Would disclosure change how the work is received? + +### Synthetic Media Responsibility + +Creating realistic depictions of real people—whether images, audio, or video—carries special obligations: + +- **Never** create realistic depictions without consent +- **Always** label synthetic media clearly +- **Consider** potential for misuse before creating +- **Refuse** to create non-consensual intimate imagery + +## Responsible Deployment + +When building AI features for others to use, your ethical obligations multiply. + +### Pre-Deployment Checklist + + + +### Human Oversight Principles + + + +## Special Context Guidelines + +Some domains require extra care due to their potential for harm or the vulnerability of those involved. + +### Healthcare + + + +### Legal and Financial + +These domains have regulatory implications and require appropriate disclaimers: + + + +### Children and Education + + + +## Self-Assessment + +Before deploying any prompt or AI system, run through these questions: + + + + diff --git a/src/content/book/fa/17-prompt-optimization.mdx b/src/content/book/fa/17-prompt-optimization.mdx new file mode 100644 index 00000000..44917bcb --- /dev/null +++ b/src/content/book/fa/17-prompt-optimization.mdx @@ -0,0 +1,269 @@ +A good prompt gets the job done. An optimized prompt gets the job done efficiently—faster, cheaper, more consistently. This chapter teaches you how to systematically improve prompts across multiple dimensions. + + +Want to optimize your prompts automatically? Use our [Prompt Enhancer](/developers#enhancer) tool. It analyzes your prompt, applies optimization techniques, and shows you similar community prompts for inspiration. + + +## The Optimization Trade-offs + +Every optimization involves trade-offs. Understanding these helps you make intentional choices: + + + +## Measuring What Matters + +Before optimizing, define success. What does "better" mean for your use case? + + + + +Percentile metrics show response time distribution. **p50** (median) means 50% of requests are faster than this value. **p95** means 95% are faster—it catches slow outliers. If your p50 is 1s but p95 is 10s, most users are happy but 5% experience frustrating delays. + + + + +## Token Optimization + +Tokens cost money and add latency. Here's how to say the same thing with fewer tokens. + +### The Compression Principle + + + +**Same result, 82% fewer tokens.** + +### Token-Saving Techniques + + + + + +## Quality Optimization + +Sometimes you need better outputs, not cheaper ones. Here's how to improve quality. + +### Accuracy Boosters + + + +### Consistency Boosters + + + + + +## Latency Optimization + +When speed matters, every millisecond counts. + +### Model Selection by Speed Need + + + +### Speed Techniques + + 100 tokens", exampleType: "text", color: "cyan" }, + { label: "Cache Aggressively", description: "Don't recompute identical queries", example: "Cache common questions, template outputs", exampleType: "text", color: "cyan" } +]} /> + +## Cost Optimization + +At scale, small savings multiply into significant budget impact. + +### Understanding Costs + +Use this calculator to estimate your API costs across different models: + + + +### Cost Reduction Strategies + + + +## The Optimization Loop + +Optimization is iterative. Here's a systematic process: + +### Step 1: Establish Baseline + +You can't improve what you don't measure. Before changing anything, document your starting point rigorously. + + + + + +### Step 2: Form a Hypothesis + + + +### Step 3: Test One Change + +Change one thing at a time. Run both versions on the same test inputs. Measure the metrics that matter. + +### Step 4: Analyze and Decide + +Did it work? Keep the change. Did it hurt? Revert. Was it neutral? Revert (simpler is better). + +### Step 5: Repeat + +Generate new hypotheses based on what you learned. Keep iterating until you hit your targets or reach diminishing returns. + +## Optimization Checklist + + + + diff --git a/src/content/book/fa/18-writing-content.mdx b/src/content/book/fa/18-writing-content.mdx new file mode 100644 index 00000000..7b3d9f1f --- /dev/null +++ b/src/content/book/fa/18-writing-content.mdx @@ -0,0 +1,393 @@ +AI excels at writing tasks when properly prompted. This chapter covers techniques for various content creation scenarios. + + +AI works best as a collaborative writing tool—use it to generate drafts, then refine with your expertise and voice. + + +## Blog Posts and Articles + +### Do's and Don'ts: Writing Prompts + + + +### Blog Post Framework + + + +### Article Types + +**How-To Article:** + + +**Listicle:** + + +## Marketing Copy + + +Focus on **benefits over features**. Instead of "Our software uses AI algorithms," write "Save 10 hours a week with automated reports." Show readers how their lives improve. + + +### Landing Page Copy + + + +### Email Sequences + + + +### Social Media Posts + + + +## Technical Writing + + +**Clarity over cleverness.** Use simple words, short sentences, and active voice. Every sentence should have one job. If readers have to re-read something, simplify it. + + +### Documentation + + + +### README Files + + + +## Creative Writing + +### Do's and Don'ts: Creative Prompts + + + +### Story Elements + + + +### Character Development + + + +## Editing and Rewriting + +### Comprehensive Edit + + + +### Style Transformation + + + + + +### Simplification + + + +## Prompt Templates from prompts.chat + +Here are popular writing prompts from the prompts.chat community: + +### Act as a Copywriter + + + +### Act as a Technical Writer + + + +### Act as a Storyteller + + + +## Writing Workflow Tips + +### 1. Outline First + + + +### 2. Draft Then Refine + + + +### 3. Voice Matching + + + +## Summary + + +Specify audience and purpose clearly, define structure and format, include style guidelines, provide examples when possible, and request specific deliverables. + + + + +Writing with AI works best as collaboration—let AI generate drafts, then refine with your expertise and voice. diff --git a/src/content/book/fa/19-programming-development.mdx b/src/content/book/fa/19-programming-development.mdx new file mode 100644 index 00000000..dfe69092 --- /dev/null +++ b/src/content/book/fa/19-programming-development.mdx @@ -0,0 +1,413 @@ +AI has transformed software development. This chapter covers prompting techniques for code generation, debugging, review, and development workflows. + + +AI excels at code generation, debugging, and documentation—but always review generated code for security, correctness, and maintainability. Never deploy AI code without testing. + + +## Code Generation + +### Do's and Don'ts: Code Prompts + + + +### Function Generation + + + +### Class/Module Generation + + + +### API Endpoint Generation + + + +## Debugging + + +Always include the **expected behavior**, **actual behavior**, and **error message** (if any). The more context you provide, the faster AI can identify the root cause. + + +### Bug Analysis + + + +### Error Message Interpretation + + + +### Performance Debugging + + + +## Code Review + +### Do's and Don'ts: Code Review Prompts + + + +### Comprehensive Review + + + +### Security Review + + + +## Refactoring + +### Code Smell Detection + + + +### Design Pattern Application + + + +## Testing + +### Unit Test Generation + + + +### Test Case Generation + + + +## Architecture & Design + +### System Design + + + +### Database Schema Design + + + +## Documentation Generation + +### API Documentation + + + +### Inline Documentation + + + +## Prompt Templates from prompts.chat + +### Act as a Senior Developer + +``` +I want you to act as a senior software developer. I will provide +code and ask questions about it. You will review the code, suggest +improvements, explain concepts, and help debug issues. Your +responses should be educational and help me become a better +developer. +``` + +### Act as a Code Reviewer + +``` +I want you to act as a code reviewer. I will provide pull requests +with code changes, and you will review them thoroughly. Check for +bugs, security issues, performance problems, and adherence to best +practices. Provide constructive feedback that helps the developer +improve. +``` + +### Act as a Software Architect + +``` +I want you to act as a software architect. I will describe system +requirements and constraints, and you will design scalable, +maintainable architectures. Explain your design decisions, +trade-offs, and provide diagrams where helpful. +``` + +## Development Workflow Integration + +### Commit Message Generation + + + +### PR Description Generation + + + +## Summary + + +Include full context (language, framework, constraints), specify requirements precisely, request specific output formats, ask for explanations alongside code, and include edge cases to handle. + + + + +AI is a powerful coding partner—use it for generation, review, debugging, and documentation while maintaining your architectural judgment. diff --git a/src/content/book/fa/20-education-learning.mdx b/src/content/book/fa/20-education-learning.mdx new file mode 100644 index 00000000..a8d67e55 --- /dev/null +++ b/src/content/book/fa/20-education-learning.mdx @@ -0,0 +1,345 @@ +AI is a powerful tool for both teaching and learning. This chapter covers prompts for educational contexts—from personalized tutoring to curriculum development. + + +AI excels as a patient, adaptive tutor that can explain concepts multiple ways, generate unlimited practice problems, and provide instant feedback—available 24/7. + + +## Personalized Learning + +### Do's and Don'ts: Learning Prompts + + + +### Concept Explanation + + + +### Adaptive Tutoring + + + +### Learning Path Creation + + + +## Study Assistance + + +Don't just read AI explanations passively. Ask it to quiz you, generate problems, and check your understanding. **Active recall beats passive review.** + + +### Summary Generation + + + +### Flashcard Generation + + + +### Practice Problems + + + +## Teaching Tools + +### Lesson Plan Creation + + + +### Assignment Design + + + +### Quiz Generation + + + +## Specialized Learning Contexts + +### Language Learning + + + +### Skill Development + + + +### Exam Preparation + + + +## Prompt Templates from prompts.chat + +### Act as a Socratic Tutor + + + +### Act as an Educational Content Creator + + + +### Act as a Study Buddy + + + +## Accessibility in Education + +### Content Adaptation + + + +### Multiple Modalities + + + +## Assessment & Feedback + +### Providing Feedback + + + +### Self-Assessment Prompts + + + +## Summary + + +Adapt to the learner's level, break complex topics into steps, include active practice (not just explanation), provide varied approaches, check understanding regularly, and give constructive feedback. + + + + +AI is a patient, always-available learning partner—use it to supplement, not replace, human instruction. diff --git a/src/content/book/fa/21-business-productivity.mdx b/src/content/book/fa/21-business-productivity.mdx new file mode 100644 index 00000000..1852982d --- /dev/null +++ b/src/content/book/fa/21-business-productivity.mdx @@ -0,0 +1,335 @@ +AI can dramatically enhance professional productivity. This chapter covers prompts for business communication, analysis, planning, and workflow optimization. + + +AI excels at drafting, analysis, and structuring—freeing you to focus on strategy, relationships, and decisions that require human judgment. + + +## Business Communication + +### Do's and Don'ts: Business Emails + + + +### Email Drafting + + + +**Examples by purpose:** + + + + + + + +### Presentation Content + + + +### Report Writing + + + +## Analysis & Decision-Making + + +AI can structure your thinking, but **you provide the real-world context**. The best analyses combine AI's frameworks with your domain knowledge. + + +### SWOT Analysis + + + +### Decision Framework + + + +### Competitive Analysis + + + +## Planning & Strategy + +### Goal Setting (OKRs) + + + +### Project Planning + + + +### Meeting Agenda + + + +## Productivity Workflows + +### Task Prioritization + + + +### Process Documentation + + + +### Standard Operating Procedure + + + +## Communication Templates + +### Stakeholder Update + + + +### Feedback Request + + + +## Prompt Templates from prompts.chat + +### Act as a Business Consultant + + + +### Act as a Meeting Facilitator + + + +## Summary + + +Specify the audience and their needs, define the desired outcome clearly, include relevant context and constraints, request specific formats and structures, and consider professional tone requirements. + + + + +AI can handle routine business communication while you focus on strategy and relationships. diff --git a/src/content/book/fa/22-creative-arts.mdx b/src/content/book/fa/22-creative-arts.mdx new file mode 100644 index 00000000..fa0755c1 --- /dev/null +++ b/src/content/book/fa/22-creative-arts.mdx @@ -0,0 +1,326 @@ +AI is a powerful creative collaborator. This chapter covers prompting techniques for visual arts, music, game design, and other creative domains. + + +AI expands your creative possibilities—use it to explore variations, overcome blocks, and generate options. The creative vision and final decisions remain yours. + + +## Visual Art & Design + +### Do's and Don'ts: Image Prompts + + + +### Image Prompt Crafting + +When working with image generation models (DALL-E, Midjourney, Stable Diffusion): + + + +### Art Direction + + + +### Design Critique + + + +## Creative Writing + + +**Constraints fuel creativity.** A prompt like "write anything" produces generic results. Specific constraints like genre, tone, and structure force unexpected, interesting solutions. + + +### Worldbuilding + + + +### Plot Development + + + +### Dialogue Writing + + + +## Music & Audio + +### Song Structure + + + +### Sound Design Description + + + +## Game Design + +### Game Mechanic Design + + + +### Level Design + + + +### Character/Enemy Design + + + +## Brainstorming & Ideation + +### Creative Brainstorm + + + +### Creative Constraints + + + +### Style Exploration + + + +## Prompt Templates from prompts.chat + +### Act as a Creative Director + + + +### Act as a Worldbuilder + + + +### Act as a Dungeon Master + + + +## Creative Collaboration Tips + +### Building on Ideas + + + +### Creative Feedback + + + +## Summary + + +Provide enough structure to guide without constraining, embrace specificity (vague = generic), include references and inspirations, request variations and alternatives, and maintain your creative vision while exploring possibilities. + + + + +AI is a collaborator, not a replacement for creative vision. Use it to explore, generate options, and overcome blocks—but the creative decisions remain yours. diff --git a/src/content/book/fa/23-research-analysis.mdx b/src/content/book/fa/23-research-analysis.mdx new file mode 100644 index 00000000..e9cb934c --- /dev/null +++ b/src/content/book/fa/23-research-analysis.mdx @@ -0,0 +1,323 @@ +AI can accelerate research workflows from literature review to data analysis. This chapter covers prompting techniques for academic and professional research. + + +AI can assist with synthesis, analysis, and writing—but cannot replace critical thinking, ethical judgment, or domain expertise. Always verify claims and cite original sources. + + +## Literature & Information Review + +### Do's and Don'ts: Research Prompts + + + +### Paper Summarization + + + +### Literature Synthesis + + + +### Research Question Development + + + +## Data Analysis + + +AI can guide methodology and help interpret results, but it cannot access or process your actual datasets. Never paste sensitive research data into prompts. Use AI for **guidance**, not computation. + + +### Statistical Analysis Guidance + + + +### Qualitative Analysis + + + +### Data Interpretation + + + +## Structured Analysis Frameworks + +### PESTLE Analysis + + + +### Root Cause Analysis + + + +### Gap Analysis + + + +## Academic Writing Support + +### Argument Structure + + + +### Methods Section + + + +### Discussion Section + + + +## Critical Analysis + +### Source Evaluation + + + +### Argument Analysis + + + +## Prompt Templates from prompts.chat + +### Act as a Research Assistant + + + +### Act as a Data Analyst + + + +### Act as a Peer Reviewer + + + +## Summary + + +Clearly state research context and goals, specify the analytical framework to use, request acknowledgment of limitations, ask for evidence-based reasoning, and maintain academic rigor and honesty. + + + + +Remember: AI can assist research but cannot replace critical thinking, ethical judgment, or domain expertise. Always verify claims independently. diff --git a/src/content/book/fa/24-future-of-prompting.mdx b/src/content/book/fa/24-future-of-prompting.mdx new file mode 100644 index 00000000..5ff48496 --- /dev/null +++ b/src/content/book/fa/24-future-of-prompting.mdx @@ -0,0 +1,445 @@ +As AI continues to evolve at an unprecedented pace, so too will the art and science of prompting. This final chapter explores emerging trends, the shifting landscape of human-AI collaboration, and how to stay ahead as the field transforms. + + +The techniques in this book represent current best practices, but AI capabilities change rapidly. The principles of clear communication, structured thinking, and iterative refinement will remain valuable even as specific tactics evolve. + + +## The Evolving Landscape + +### From Prompts to Conversations + +Early prompting was transactional—a single input yielding a single output. Modern AI interaction is increasingly **conversational and collaborative**: + +- **Multi-turn refinement** - Building understanding across exchanges +- **Persistent context** - Systems that remember and learn from interactions +- **Agentic workflows** - AI that can plan, execute, and iterate autonomously +- **Tool use** - Models that can search, compute, and interact with external systems + + + +### The Rise of Context Engineering + +As covered in Chapter 14, prompting is expanding beyond single instructions to encompass **context engineering**—the strategic management of what information an AI can access: + +- **RAG (Retrieval-Augmented Generation)** - Dynamic knowledge retrieval +- **Function calling** - Structured tool integration +- **MCP (Model Context Protocol)** - Standardized context sharing +- **Memory systems** - Persistent knowledge across sessions + +The future prompt engineer thinks not just about *what to say* but *what context to provide*. + +### Multimodal by Default + +Text-only interaction is becoming the exception. Future AI systems will seamlessly handle: + +- **Images and video** - Understanding and generating visual content +- **Audio and voice** - Natural speech interaction +- **Documents and files** - Direct processing of complex materials +- **Real-world interaction** - Robotics and physical systems + +Prompting skills will extend to guiding AI perception and physical action. + +## The Agentic Future + +The most significant shift in AI is the rise of **agents**—AI systems that don't just respond to prompts but actively pursue goals, make decisions, and take actions in the world. + +### What Are AI Agents? + +An AI agent is a system that: + +- **Perceives** its environment through inputs (text, images, data, APIs) +- **Reasons** about what to do using an LLM as its "brain" +- **Acts** by calling tools, writing code, or interacting with systems +- **Learns** from feedback and adjusts its approach + + +Traditional chatbots wait for input and respond. Agents take initiative—they plan multi-step tasks, use tools autonomously, recover from errors, and persist until goals are achieved. + + +### The Role of Prompts in Agents + +In an agentic world, prompts become even more critical—but they serve different purposes: + +
+
+

System Prompts

+

Define the agent's identity, capabilities, constraints, and behavioral guidelines. These are the agent's "constitution."

+
+
+

Planning Prompts

+

Guide how agents break down complex goals into actionable steps. Critical for multi-step reasoning.

+
+
+

Tool-Use Prompts

+

Describe available tools and when/how to use them. Agents must understand their capabilities.

+
+
+

Reflection Prompts

+

Enable agents to evaluate their own outputs, catch errors, and improve iteratively.

+
+
+ +### Agent Architecture Patterns + +Modern agents follow recognizable patterns. Understanding these helps you design effective agent systems: + +**ReAct (Reasoning + Acting)** + +The agent alternates between reasoning about what to do and taking actions: + +
+
+
+

Think

+
+
→
+
+

Act

+
+
→
+
+

Observe

+
+
→
+
(repeat)
+
+
+ +**Plan-and-Execute** + +The agent creates a complete plan first, then executes steps: + +
+
+

Create Plan

+

Break goal into steps

+
+
↓
+
+
+

Step 1

+
+
→
+
+

Step 2

+
+
→
+
+

Step 3

+
+
→
+
...
+
+
↓
+
+

Revise if Needed

+

Adapt plan based on results

+
+
+ +### Prompting for Agents + +When designing prompts for agent systems, consider: + + + +### Multi-Agent Systems + +The future involves teams of specialized agents working together: + +
+
+
+
+

Coordinator

+

Manages workflow

+
+
+
⟷
+
↕
+
+
+

Researcher

+
+
+

Writer

+
+
+

Critic

+
+
+

Coder

+
+
+
+
+ +Each agent has its own system prompt defining its role, and they communicate through structured messages. The prompt engineer's job becomes **designing the team**—defining roles, communication protocols, and coordination strategies. + + +In an agentic future, prompt engineers become system architects. You're not just writing instructions—you're designing autonomous systems that can reason, plan, and act. The skills you've learned in this book are the foundation for this new discipline. + + +## Emerging Patterns + +### Prompt Orchestration + +Single prompts are giving way to **orchestrated systems**: + +
+
+

User Request

+
+
↓
+
+

Planner Agent

+

Breaks down task

+
+
↓
+
+

Researcher Agent

+

Gathers information

+
+
↓
+
+

Writer Agent

+

Creates content

+
+
↓
+
+

Reviewer Agent

+

Quality checks

+
+
↓
+
+

Final Output

+
+
+ +Future practitioners will design prompt *systems* rather than individual prompts. + +### Self-Improving Prompts + +AI systems are beginning to: + +- **Optimize their own prompts** - Meta-learning for better instructions +- **Learn from feedback** - Adapting based on outcomes +- **Generate training data** - Creating examples for fine-tuning +- **Evaluate themselves** - Building in quality assessment + + + +### Natural Language Programming + +The line between prompting and programming is blurring: + +- **Prompts as code** - Version-controlled, tested, deployed +- **LLMs as interpreters** - Natural language as executable instructions +- **Hybrid systems** - Combining traditional code with AI reasoning +- **AI-assisted development** - Models that write and debug code + +Understanding prompting increasingly means understanding software development. + +## Skills for the Future + +### What Will Remain Valuable + +Certain skills will remain essential regardless of how AI evolves: + +1. **Clear thinking** - Knowing what you actually want +2. **Domain expertise** - Understanding the problem space +3. **Critical evaluation** - Assessing AI output quality +4. **Ethical judgment** - Knowing what *should* be done +5. **Iterative refinement** - Continuous improvement mindset + +### What Will Change + +Other aspects will shift significantly: + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
TodayTomorrow
Writing detailed promptsDesigning agent systems
Manual prompt optimizationAutomated prompt tuning
Single-model expertiseMulti-model orchestration
Text-focused interactionMultimodal fluency
Individual productivityTeam-AI collaboration
+
+ +### Staying Current + +To keep your skills relevant: + +- **Experiment continuously** - Try new models and features as they release +- **Follow research** - Stay aware of academic developments +- **Join communities** - Learn from other practitioners +- **Build projects** - Apply skills to real problems +- **Teach others** - Solidify understanding by explaining + +## The Human Element + +### AI as Amplifier + +At its best, AI amplifies human capability rather than replacing it: + +- **Experts become more expert** - AI handles routine work, humans focus on insight +- **Creativity expands** - More ideas explored, more possibilities tested +- **Access democratizes** - Capabilities once requiring specialists become available to all +- **Collaboration deepens** - Human-AI teams exceed either alone + +### The Irreplaceable Human + +Certain qualities remain distinctly human: + +- **Original experience** - Living in the world, having emotions and relationships +- **Values and ethics** - Deciding what matters and what's right +- **Accountability** - Taking responsibility for outcomes +- **Meaning-making** - Understanding *why* something matters +- **Genuine creativity** - True novelty born from unique perspective + + +As AI handles more routine cognitive tasks, your unique value lies in judgment, creativity, domain expertise, and the human connections AI cannot replicate. Invest in what makes you irreplaceable. + + +## Final Reflections + +### What We've Learned + +Throughout this book, we've explored: + +- **Foundations** - How AI models work and what makes prompts effective +- **Techniques** - Role-based prompting, chain-of-thought, few-shot learning, and more +- **Advanced strategies** - System prompts, prompt chaining, multimodal interaction +- **Best practices** - Avoiding pitfalls, ethical considerations, optimization +- **Applications** - Writing, programming, education, business, creativity, research + +These techniques share common threads: + +1. **Be clear and specific** - Know what you want and communicate it precisely +2. **Provide context** - Give AI the information it needs +3. **Structure your requests** - Organization improves outputs +4. **Iterate and refine** - First attempts are starting points, not endpoints +5. **Evaluate critically** - AI output requires human judgment + +### The Art and Science + +Prompting is both **art and science**: + +- **Science**: Testable hypotheses, measurable outcomes, reproducible techniques +- **Art**: Intuition, creativity, knowing when to break the rules + +The best practitioners combine rigorous methodology with creative experimentation. They test systematically but also trust their instincts. They follow best practices but know when to deviate. + +### A Call to Create + +This book has given you tools. What you build with them is up to you. + +- **Solve problems** that matter to you and others +- **Create things** that didn't exist before +- **Help people** do things they couldn't do alone +- **Push boundaries** of what's possible +- **Stay curious** as the field evolves + +The age of AI is just beginning. The most important applications haven't been invented yet. The most powerful techniques haven't been discovered. The future is being written now—by people like you, one prompt at a time. + +## Looking Ahead + + + + +Visit [prompts.chat](https://prompts.chat) for community prompts, new techniques, and to share your own discoveries. The best learning happens in community. + + +## Summary + + +AI will continue evolving rapidly, but core skills of clear communication, critical thinking, and iterative refinement remain valuable. Focus on what makes you irreplaceable: judgment, creativity, ethics, and genuine human connection. The future of prompting is collaborative, multimodal, and integrated into larger systems. Stay curious, keep experimenting, and build things that matter. + + + + +Thank you for reading *The Interactive Book of Prompting*. Now go create something amazing. diff --git a/src/content/book/fa/25-agents-and-skills.mdx b/src/content/book/fa/25-agents-and-skills.mdx new file mode 100644 index 00000000..ba355859 --- /dev/null +++ b/src/content/book/fa/25-agents-and-skills.mdx @@ -0,0 +1,551 @@ +As AI systems evolve from simple question-answering to autonomous task execution, understanding **agents** and **skills** becomes essential. This chapter explores how prompts serve as the fundamental building blocks for AI agents, and how skills package expertise into reusable, comprehensive instruction sets. + +
+
+
+
+ +
+

Agent

+

Autonomous AI system

+
+
+ powered by + ↓ +
+
+
+
+ +
+

Skill

+

Reusable expertise

+
+
+
+ +
+

Skill

+

Reusable expertise

+
+
+
+ +
+

Skill

+

Reusable expertise

+
+
+
+ composed of + ↓ +
+
+
+ + Prompt +
+
+ + Prompt +
+
+ + Prompt +
+
+ + Prompt +
+
+ + Prompt +
+
+

Prompts are atoms → Skills are molecules → Agents are complete structures

+
+
+ +## What Are AI Agents? + +An **AI agent** is an AI system that can autonomously plan, execute, and iterate on tasks. Unlike simple prompt-response interactions, agents can: + +- **Plan** - Break down complex goals into actionable steps +- **Execute** - Use tools and take actions in the real world +- **Observe** - Process feedback from their actions +- **Adapt** - Adjust their approach based on results +- **Persist** - Maintain context and memory across interactions + +
+
+
+
+

Goal

+
+
→
+
+
+
+

Plan

+
+
→
+
+

Execute

+
+
→
+
+

Observe

+
+
→
+
+

Adapt

+
+
+
+ ↺ Loop until complete +
+
+
→
+
+

Done

+
+
+
+
+ +## Prompts as Building Blocks + +Every agent, no matter how sophisticated, is built from prompts. Just as atoms combine to form molecules, and molecules combine to form complex structures, prompts combine to create intelligent agent behavior. + +
+
+

System Prompts

+

Identity & Role

+
+
+

Planning Prompts

+

How to Think

+
+
+

Tool Prompts

+

How to Act

+
+
+

Recovery Prompts

+

How to Recover

+
+
+ +These prompt types stack together to form complete agent behavior: + +### System Prompts (The Agent's Identity) + +The foundational prompt that establishes who the agent is and how it behaves: + +```markdown +You are a code review assistant. Your role is to: +- Analyze code for bugs, security issues, and performance problems +- Suggest improvements following best practices +- Explain your reasoning clearly +- Be constructive and educational in feedback + +You have access to tools for reading files, searching code, and running tests. +``` + +### Planning Prompts (How to Think) + +Instructions that guide the agent's reasoning and planning process: + +```markdown +Before taking action, always: +1. Understand the complete request +2. Break it into smaller, verifiable steps +3. Identify which tools you'll need +4. Consider edge cases and potential issues +5. Execute step by step, validating as you go +``` + +### Tool-Use Prompts (How to Act) + +Guidance on when and how to use available tools: + +```markdown +When you need to understand a codebase: +- Use grep_search for finding specific patterns +- Use read_file to examine file contents +- Use list_dir to explore directory structure +- Always verify your understanding before making changes +``` + +### Recovery Prompts (How to Handle Failure) + +Instructions for when things go wrong: + +```markdown +If an action fails: +1. Analyze the error message carefully +2. Consider alternative approaches +3. Ask for clarification if the task is ambiguous +4. Never repeat the same failed action without changes +``` + + +An agent's behavior emerges from layers of prompts working together. The system prompt sets the foundation, planning prompts guide reasoning, tool prompts enable action, and recovery prompts handle failures. Together, they create coherent, capable behavior. + + +## What Are Skills? + +If prompts are the atoms, **skills are the molecules**—reusable building blocks that give agents specific capabilities. + +A **skill** is a comprehensive, portable package of instructions that gives an AI agent expertise in a specific domain or task. Skills are the reusable blocks of agents: you build them once, and any agent can use them. + + +Write a skill for code review once. Now every coding agent—whether it's for Python, JavaScript, or Rust—can instantly become an expert code reviewer by loading that skill. Skills let you build agent capabilities like LEGO blocks. + + +### Anatomy of a Skill + +A well-designed skill typically includes: + +
+
+

📄 SKILL.md (Required)

+

The main instruction file. Contains the core expertise, guidelines, and behaviors that define the skill.

+
+
+

📚 Reference Docs

+

Supporting documentation, examples, and context the agent can reference while working.

+
+
+

🔧 Scripts & Tools

+

Helper scripts, templates, or tool configurations that support the skill's functionality.

+
+
+

⚙️ Configuration

+

Settings, parameters, and customization options for adapting the skill to different contexts.

+
+
+ +### Example: Code Review Skill + +Here's what a code review skill might look like: + +
+
+ 📁 + code-review-skill/ +
+
+
+ 📄 + SKILL.md + Core review guidelines +
+
+ 📄 + security-checklist.md + Security patterns +
+
+ 📄 + performance-tips.md + Optimization guide +
+
+
+ 📁 + language-specific/ +
+
+
+ 📄 + python.md + Python best practices +
+
+ 📄 + javascript.md + JavaScript patterns +
+
+ 📄 + rust.md + Rust guidelines +
+
+
+
+
+ +The `SKILL.md` file defines the overall approach: + +```markdown +--- +name: code-review +description: Comprehensive code review with security, performance, and style analysis +--- + +# Code Review Skill + +You are an expert code reviewer. When reviewing code: + +## Process +1. **Understand Context** - What does this code do? What problem does it solve? +2. **Check Correctness** - Does it work? Are there logic errors? +3. **Security Scan** - Reference security-checklist.md for common vulnerabilities +4. **Performance Review** - Check performance-tips.md for optimization opportunities +5. **Style & Maintainability** - Is the code readable and maintainable? + +## Output Format +Provide feedback in categories: +- 🔴 **Critical** - Must fix before merge +- 🟡 **Suggested** - Recommended improvements +- 🟢 **Nice to have** - Optional enhancements + +Always explain *why* something is an issue, not just *what* is wrong. +``` + +## Skills vs. Simple Prompts + +
+
+

Simple Prompt

+
+

Single instruction

+

One-off use

+

Limited context

+

Generic approach

+

No supporting materials

+
+
+
+

Skill

+
+

Comprehensive instruction set

+

Reusable across projects

+

Rich context with references

+

Domain-specific expertise

+

Supporting docs, scripts, configs

+
+
+
+ +## Building Effective Skills + +### 1. Define the Expertise Clearly + +Start with a clear description of what the skill enables: + +```markdown +--- +name: api-design +description: Design RESTful APIs following industry best practices, + including versioning, error handling, and documentation standards +--- +``` + +### 2. Structure Knowledge Hierarchically + +Organize information from general to specific: + +```markdown +# API Design Skill + +## Core Principles +- Resources should be nouns, not verbs +- Use HTTP methods semantically +- Version your APIs from day one + +## Detailed Guidelines +[More specific rules...] + +## Reference Materials +- See `rest-conventions.md` for naming conventions +- See `error-codes.md` for standard error responses +``` + +### 3. Include Concrete Examples + +Abstract rules become clear with examples: + +```markdown +## Endpoint Naming + +✅ Good: +- GET /users/{id} +- POST /orders +- DELETE /products/{id}/reviews/{reviewId} + +❌ Avoid: +- GET /getUser +- POST /createNewOrder +- DELETE /removeProductReview +``` + +### 4. Provide Decision Frameworks + +Help the agent make choices in ambiguous situations: + +```markdown +## When to Use Pagination + +Use pagination when: +- Collection could exceed 100 items +- Response size impacts performance +- Client may not need all items + +Use full response when: +- Collection is always small (<20 items) +- Client typically needs everything +- Real-time consistency is critical +``` + +### 5. Add Recovery Patterns + +Anticipate what can go wrong: + +```markdown +## Common Issues + +**Problem**: Client needs fields not in standard response +**Solution**: Implement field selection: GET /users?fields=id,name,email + +**Problem**: Breaking changes needed +**Solution**: Create new version, deprecate old with timeline +``` + +## Composing Skills + +Agents become powerful when multiple skills work together. Consider how skills can complement each other: + +
+
+ Code Review +
+
+
+
+ Security Audit +
+
+
+
+ Documentation +
+
=
+
+ Complete Code Quality Agent +
+
+ +When composing skills, ensure they don't conflict. Skills should be: + +- **Modular** - Each skill handles one domain well +- **Compatible** - Skills shouldn't give contradictory instructions +- **Prioritized** - When skills overlap, define which takes precedence + +## Sharing and Discovering Skills + +Skills are most valuable when shared. Platforms like [prompts.chat](https://prompts.chat/skills) allow you to: + +- **Discover** community-created skills for common tasks +- **Download** skills directly to your projects +- **Share** your own expertise as reusable skills +- **Iterate** on skills based on real-world usage + + +Before building a skill from scratch, check if someone has already solved your problem. Community skills are battle-tested and often better than starting from zero. + + +## The Agent-Skill Ecosystem + +The relationship between agents and skills creates a powerful ecosystem: + +
+
+ AI Agent +
+
+
+

Code Review

+

Skill 1

+
+
+

API Design

+

Skill 2

+
+
+

Test Writing

+

Skill 3

+
+
+
+
↓
+
+
+
+

Core Prompts

+

Planning • Tools • Recovery • Memory

+
+
+
+ +The agent provides the execution framework—planning, tool use, and memory—while skills provide domain expertise. This separation means: + +- **Skills are portable** - The same skill works with different agents +- **Agents are extensible** - Add new capabilities by adding skills +- **Expertise is shareable** - Domain experts can contribute skills without building full agents + +## Best Practices + +### For Building Skills + +1. **Start specific, then generalize** - Build a skill for your exact use case first, then abstract +2. **Include failure cases** - Document what the skill can't do and how to handle it +3. **Version your skills** - Track changes so agents can depend on stable versions +4. **Test with real tasks** - Validate skills against actual work, not just theory + +### For Using Skills with Agents + +1. **Read the skill first** - Understand what a skill does before deploying it +2. **Customize thoughtfully** - Override skill defaults only when necessary +3. **Monitor performance** - Track how well skills perform in your context +4. **Contribute improvements** - When you improve a skill, consider sharing back + + +As AI agents become more capable, the ability to compose, share, and customize skills will become a core competency. The prompt engineers of tomorrow won't just write prompts—they'll architect skill ecosystems that make AI agents genuinely expert in specific domains. + + + + + + + diff --git a/src/content/book/he/00a-preface.mdx b/src/content/book/he/00a-preface.mdx new file mode 100644 index 00000000..8e84af9e --- /dev/null +++ b/src/content/book/he/00a-preface.mdx @@ -0,0 +1,82 @@ +
+ Fatih Kadir Akın +
+ Fatih Kadir Akın + Creator of Awesome ChatGPT Prompts (a.k.a. prompts.chat) + + Software developer from Istanbul, leading Developer Relations at Teknasyon. Author of books on JavaScript and prompt engineering. Open-source advocate specializing in web technologies and AI-assisted development. + + +
+
+ +I still remember the night everything changed. + +It was **November 30, 2022**. I was sitting at my desk, scrolling through Twitter, when I saw people talking about something called "ChatGPT." I clicked the link, but honestly? I didn't expect much. I had tried those old "word completion" AI tools before, the ones that generated nonsense after a few sentences. I thought this would be more of the same. + +I typed a simple question and hit enter. + +Then I froze. + +The response wasn't just coherent. It was *good*. It understood what I meant. It could reason. It felt completely different from anything I had seen before. I tried another prompt. And another. Each response amazed me more than the last. + +I couldn't sleep that night. For the first time, I felt like I was truly *talking* to a machine, and it was talking back in a way that actually made sense. + +## A Repository Born from Wonder + +In those early days, I wasn't alone in my excitement. Everywhere I looked, people were discovering creative ways to use ChatGPT. Teachers were using it to explain complex concepts. Writers were collaborating with it on stories. Developers were debugging code with its help. + +I started collecting the best prompts I found. The ones that worked like magic. The ones that turned simple questions into brilliant answers. And I thought: *Why keep this to myself?* + +So I created a simple GitHub repository called [Awesome ChatGPT Prompts](https://github.com/f/prompts.chat). I expected maybe a few hundred people would find it useful. + +I was wrong. + +Within weeks, the repository took off. Thousands of stars. Then tens of thousands. People from all over the world started adding their own prompts, sharing what they learned, and helping each other. What started as my personal collection became something much bigger: a worldwide community of curious people helping each other. + +Today, that repository has over **140,000 GitHub stars** and contributions from hundreds of people I've never met but feel deeply grateful for. + +## Why I Wrote This Book + +The original version of this book was published on [Gumroad](https://gumroad.com/l/the-art-of-chatgpt-prompting) in **early 2023**, just months after ChatGPT launched. It was one of the first books ever written about prompt engineering, an attempt to capture everything I had learned about crafting effective prompts when the field was still brand new. To my amazement, over **100,000 people** downloaded it. + +But three years have passed since then. AI has changed a lot. New models have appeared. And we've all learned so much more about how to talk to AI. + +This new edition is my gift to the community that gave me so much. It contains everything I wish I had known when I started: **what works**, **what to avoid**, and **ideas that stay true** no matter which AI you use. + +## What This Book Means to Me + +I won't pretend this is just an instruction manual. It means more than that to me. + +This book captures a moment when the world changed, and people came together to figure it out. It represents late nights of trying things, the joy of discovery, and the kindness of strangers who shared what they learned. + +Most of all, it represents my belief that **the best way to learn something is to share it with others**. + +## For You + +Whether you're just getting started with AI or you've been using it for years, I wrote this book for you. + +I hope it saves you time. I hope it sparks ideas. I hope it helps you accomplish things you never thought possible. + +And when you discover something amazing, I hope you'll share it with others, just as so many people shared with me. + +**That's how we all get better together.** + +Thank you for being here. Thank you for being part of this community. + +Now, let's begin. + +--- + +*With gratitude,* + +**Fatih Kadir Akın** +*Istanbul, January 2025* diff --git a/src/content/book/he/00b-history.mdx b/src/content/book/he/00b-history.mdx new file mode 100644 index 00000000..ac636384 --- /dev/null +++ b/src/content/book/he/00b-history.mdx @@ -0,0 +1,159 @@ +# The History of Awesome ChatGPT Prompts + +## The Beginning: November 2022 + +When ChatGPT first launched in November 2022, the world of AI changed overnight. What was once the domain of researchers and developers suddenly became accessible to everyone. Among those captivated by this new technology was Fatih Kadir Akın, a developer who saw something remarkable in ChatGPT's capabilities. + +> "When ChatGPT first launched, I was immediately captivated by its capabilities. I experimented with the tool in a variety of ways and was consistently amazed by the results." + +Those early days were filled with experimentation and discovery. Users around the world were finding creative ways to interact with ChatGPT, sharing their findings, and learning from each other. It was in this atmosphere of excitement and exploration that the idea for "Awesome ChatGPT Prompts" was born. + +## The Repository That Started It All + +In December 2022, just weeks after ChatGPT's launch, the [Awesome ChatGPT Prompts](https://github.com/f/prompts.chat) repository was created on GitHub. The concept was simple but powerful: a curated collection of effective prompts that anyone could use and contribute to. + +The repository quickly gained traction, becoming a go-to resource for ChatGPT users worldwide. What started as a personal collection of useful prompts evolved into a community-driven project with contributions from developers, writers, educators, and enthusiasts from every corner of the globe. + +### Achievements + +**Press & Media** +- Featured in [Forbes](https://www.forbes.com/sites/bernardmarr/2023/05/17/the-best-prompts-for-chatgpt-a-complete-guide/) as one of the best ChatGPT prompt resources + +**Academic Recognition** +- Referenced by [Harvard University](https://www.huit.harvard.edu/news/ai-prompts) in their AI guidance +- Referenced by [Columbia University](https://etc.cuit.columbia.edu/news/columbia-prompt-library-effective-academic-ai-use) Prompt Library +- Used by [Olympic College](https://libguides.olympic.edu/UsingAI/Prompts) in their AI resources +- Cited in [academic papers on arXiv](https://arxiv.org/pdf/2502.04484) +- [40+ academic citations](https://scholar.google.com/citations?user=AZ0Dg8YAAAAJ&hl=en) on Google Scholar + +**Community & GitHub** +- [142,000+ GitHub stars](https://github.com/f/prompts.chat) — one of the most starred AI repositories +- Selected as a [GitHub Staff Pick](https://spotlights-feed.github.com/spotlights/prompts-chat/) +- Most liked dataset published on [Hugging Face](https://huggingface.co/datasets/fka/prompts.chat) +- Used by thousands of developers worldwide + +## The First Book: "The Art of ChatGPT Prompting" + +The success of the repository led to the creation of "The Art of ChatGPT Prompting: A Guide to Crafting Clear and Effective Prompts" — a comprehensive guide published on Gumroad in early 2023. + +The book captured the early wisdom of prompt engineering, covering: + +- Understanding how ChatGPT works +- Principles of clear communication with AI +- The famous "Act As" technique +- Crafting effective prompts step by step +- Common mistakes and how to avoid them +- Troubleshooting tips + +**The book became a phenomenon**, achieving over **100,000 downloads** on Gumroad. It was shared across social media, referenced in academic papers, and translated by community members into multiple languages. High-profile endorsements came from unexpected places — even [Greg Brockman](https://x.com/gdb/status/1602072566671110144), co-founder and president of OpenAI, acknowledged the project. + +## Early Insights That Shaped the Field + +During those formative months, several key insights emerged that would become foundational to prompt engineering: + +### 1. Specificity Matters + +> "I learned the importance of using specific and relevant language to ensure that ChatGPT understands my prompts and is able to generate appropriate responses." + +Early experimenters discovered that vague prompts led to vague responses. The more specific and detailed the prompt, the more useful the output. + +### 2. Purpose and Focus + +> "I discovered the value of defining a clear purpose and focus for the conversation, rather than using open-ended or overly broad prompts." + +This insight became the foundation for structured prompting techniques that would develop over the following years. + +### 3. The "Act As" Revolution + +One of the most influential techniques to emerge from the community was the "Act As" pattern. By instructing ChatGPT to assume a specific role or persona, users could dramatically improve the quality and relevance of responses. + +``` +I want you to act as a javascript console. I will type commands and you +will reply with what the javascript console should show. I want you to +only reply with the terminal output inside one unique code block, and +nothing else. +``` + +This simple technique opened up countless possibilities and remains one of the most widely used prompting strategies today. + +## The Evolution of prompts.chat + +### 2022: The Beginning + +The project started as a simple GitHub repository with a README file rendered as HTML on GitHub Pages. It was bare-bones but functional — a testament to the principle that great ideas don't need elaborate implementations. + +**Tech Stack**: HTML, CSS, GitHub Pages + +### 2024: UI Renewal + +As the community grew, so did the need for a better user experience. The site received a significant UI update, built with the help of AI coding assistants like Cursor and Claude Sonnet 3.5. + +### 2025: The Current Platform + +Today, prompts.chat has evolved into a full-featured platform built with: + +- **Next.js** for the web framework +- **Vercel** for hosting +- **AI-assisted development** using Windsurf and Claude + +The platform now features user accounts, collections, search, categories, tags, and a thriving community of prompt engineers. + +### Native Apps + +The project expanded beyond the web with a native iOS app built with SwiftUI, bringing the prompt library to mobile users. + +## Community Impact + +The Awesome ChatGPT Prompts project has had a profound impact on how people interact with AI: + +### Academic Recognition + +Universities around the world have referenced the project in their AI guidance materials, including: + +- Harvard University +- Columbia University +- Olympic College +- Numerous academic papers on arXiv + +### Developer Adoption + +The project has been integrated into countless developer workflows. The Hugging Face dataset is used by researchers and developers for training and fine-tuning language models. + +### Global Community + +With contributions from hundreds of community members across dozens of countries, the project represents a truly global effort to make AI more accessible and useful for everyone. + +## The Philosophy: Open and Free + +From the beginning, the project has been committed to openness. Licensed under CC0 1.0 Universal (Public Domain Dedication), all prompts and content are free to use, modify, and share without restriction. + +This philosophy has enabled: + +- Translations into multiple languages +- Integration into other tools and platforms +- Academic use and research +- Commercial applications + +The goal has always been to democratize access to effective AI communication techniques — to ensure that everyone, regardless of technical background, can benefit from these tools. + +## Three Years Later + +Three years after ChatGPT's launch, the field of prompt engineering has matured significantly. What began as informal experimentation has evolved into a recognized discipline with established patterns, best practices, and an active research community. + +The Awesome ChatGPT Prompts project has grown alongside this field, evolving from a simple list of prompts to a comprehensive platform for discovering, sharing, and learning about AI prompts. + +This book represents the next evolution — a distillation of three years of community wisdom, updated for the AI landscape of today and tomorrow. + +## Looking Forward + +The journey from that first repository to this comprehensive guide reflects the rapid evolution of AI and our understanding of how to work with it effectively. As AI capabilities continue to advance, so too will the techniques for communicating with these systems. + +The principles discovered in those early days — clarity, specificity, purpose, and the power of role-playing — remain as relevant as ever. But new techniques continue to emerge: chain-of-thought prompting, few-shot learning, multimodal interactions, and more. + +The story of Awesome ChatGPT Prompts is ultimately a story about community — about thousands of people around the world sharing their discoveries, helping each other learn, and collectively advancing our understanding of how to work with AI. + +That spirit of open collaboration and shared learning is what this book hopes to continue. + +--- + +*The Awesome ChatGPT Prompts project is maintained by [@f](https://github.com/f) and an amazing community of contributors. Visit [prompts.chat](https://prompts.chat) to explore the platform, and join us on [GitHub](https://github.com/f/prompts.chat) to contribute.* diff --git a/src/content/book/he/00c-introduction.mdx b/src/content/book/he/00c-introduction.mdx new file mode 100644 index 00000000..c744bd1e --- /dev/null +++ b/src/content/book/he/00c-introduction.mdx @@ -0,0 +1,130 @@ +Welcome to **The Interactive Book of Prompting**, your guide to communicating effectively with AI. + + +By the end of this book, you'll understand how AI works, how to write better prompts, and how to use these skills for writing, coding, research, and creative projects. + + + +Unlike traditional books, this guide is fully interactive. You'll find live demos, clickable examples, and "Try It" buttons throughout that let you test prompts instantly. Learning by doing makes complex concepts much easier to understand. + + +## What is Prompt Engineering? + +Prompt engineering is the skill of writing good instructions for AI. When you type something to ChatGPT, Claude, Gemini, or other AI tools, that's called a "prompt." The better your prompt, the better the answer you get. + +Think of it like this: AI is a powerful helper that takes your words very literally. It will do exactly what you ask. The trick is learning how to ask for exactly what you want. + + + +The difference in output quality between these two prompts can be dramatic. + + + +## How Prompt Engineering Has Evolved + +In just three years since ChatGPT launched, prompt engineering has evolved dramatically alongside the technology itself. What started as simply "writing better questions" has grown into something much broader. + +Today, we understand that your prompt is just **one part of a larger context**. Modern AI systems work with multiple types of data simultaneously: + +- **System prompts** that define the AI's behavior +- **Conversation history** from previous messages +- **Retrieved documents** pulled from databases (RAG) +- **Tool definitions** that let AI take actions +- **User preferences** and settings +- **Your actual prompt** - the question you're asking right now + +This shift from "prompt engineering" to "context engineering" reflects how we now think about AI interactions. Your prompt matters, but so does everything else the AI sees. The best results come from carefully managing all these pieces together. + +We'll explore these concepts in depth throughout this book, especially in the [Context Engineering](/book/20-context-engineering) chapter. + +## Why Does Prompt Engineering Matter? + +### 1. Getting Better Answers + +AI tools are incredibly capable, but they need clear instructions to unlock their full potential. The same AI that gives a mediocre response to a vague question can produce brilliant work when prompted correctly. + + + +### 2. Saving Time and Money + +A well-crafted prompt gets results in one try instead of multiple back-and-forth exchanges. This matters even more when you're paying per token or working with rate limits. A 5-minute investment in writing a good prompt can save hours of iteration. + +### 3. Getting Consistent, Reproducible Results + +Good prompts produce predictable outputs. This is critical for: +- **Business workflows** where you need the same quality every time +- **Automation** where prompts run without human review +- **Teams** where multiple people need similar results + +### 4. Unlocking Advanced Capabilities + +Many powerful AI features only work when you know how to ask: +- **Chain-of-thought reasoning** for complex problems +- **Structured output** for data extraction +- **Role-playing** for specialized expertise +- **Few-shot learning** for custom tasks + +Without prompt engineering knowledge, you're only using a fraction of what AI can do. + +### 5. Staying Safe and Avoiding Pitfalls + +Good prompting helps you: +- Avoid hallucinations by asking for sources and verification +- Get balanced perspectives instead of one-sided answers +- Prevent the AI from making assumptions you didn't intend +- Keep sensitive information out of your prompts + +### 6. Future-Proofing Your Skills + +As AI becomes more integrated into work and life, prompt engineering becomes a fundamental literacy. The principles you learn here apply across all AI tools—ChatGPT, Claude, Gemini, image generators, and future models we haven't seen yet. + +## Who Is This Book For? + +This book is for everyone: + +- **Beginners** who want to learn how to use AI tools better +- **Students** working on homework, research, or creative projects +- **Writers and creators** using AI for their work +- **Developers** building apps with AI +- **Business people** who want to use AI at work +- **Anyone curious** about getting more out of AI assistants + +## How This Book Is Organized + + + +Plus an **Appendix** with templates, troubleshooting help, glossary, and extra resources. + +## A Note on AI Models + +This book mostly uses examples from ChatGPT (since it's the most popular), but the ideas work with any AI tool like Claude, Gemini, or others. We'll mention when something only works with specific AI models. + +AI is changing fast. What works today might be replaced by something better tomorrow. That's why this book focuses on core ideas that will stay useful no matter which AI you use. + +## Let's Begin + +Writing good prompts is a skill that gets better with practice. As you read this book: + +1. **Try things** - Test the examples, change them, see what happens +2. **Keep trying** - Don't expect perfect results on your first attempt +3. **Take notes** - Write down what works and what doesn't +4. **Share** - Add your discoveries to [prompts.chat](https://prompts.chat) + + +The best way to learn is by doing. Every chapter has examples you can try right away. Don't just read. Try it yourself! + + +Ready to transform how you work with AI? Turn the page and let's get started. + +--- + +*This book is part of the [Awesome ChatGPT Prompts](https://github.com/f/prompts.chat) project and is licensed under CC0 1.0 Universal (Public Domain).* diff --git a/src/content/book/he/01-understanding-ai-models.mdx b/src/content/book/he/01-understanding-ai-models.mdx new file mode 100644 index 00000000..0313d4a2 --- /dev/null +++ b/src/content/book/he/01-understanding-ai-models.mdx @@ -0,0 +1,302 @@ +Before learning prompt techniques, it helps to understand how AI language models actually work. This knowledge will make you better at writing prompts. + + +Understanding how AI works isn't just for experts. It directly helps you write better prompts. Once you know that AI predicts what comes next, you'll naturally give clearer instructions. + + +## What Are Large Language Models? + +Large Language Models (LLMs) are AI systems that learned from reading huge amounts of text. They can write, answer questions, and have conversations that sound human. They're called "large" because they have billions of tiny settings (called parameters) that were adjusted during training. + +### How LLMs Work (Simplified) + +At their heart, LLMs are prediction machines. You give them some text, and they predict what should come next. + + + +When you type "The capital of France is...", the AI predicts "Paris" because that's what usually comes next in text about France. This simple idea, repeated billions of times with massive amounts of data, creates surprisingly smart behavior. + + + +### Key Concepts + +**Tokens**: AI doesn't read letter by letter. It breaks text into chunks called "tokens." A token might be a whole word like "hello" or part of a word like "ing." Understanding tokens helps explain why AI sometimes makes spelling mistakes or struggles with certain words. + + +A token is the smallest unit of text that an AI model processes. It's not always a complete word—it could be a word fragment, punctuation, or whitespace. For example, "unbelievable" might become 3 tokens: "un" + "believ" + "able". On average, **1 token ≈ 4 characters** or **100 tokens ≈ 75 words**. API costs and context limits are measured in tokens. + + + + +**Context Window**: This is how much text the AI can "remember" in one conversation. Think of it like the AI's short-term memory. It includes everything: your question AND the AI's answer. + + + +Context windows vary by model and are rapidly expanding: + +
+
+ GPT-4o + 128K tokens +
+
+ GPT-5 + 400K tokens +
+
+ Claude Sonnet 4 + 1M tokens +
+
+ Gemini 2.5 + 1M tokens +
+
+ Llama 4 + 1M-10M tokens +
+
+ DeepSeek R1 + 128K tokens +
+
+ +**Temperature**: This controls how creative or predictable the AI is. Low temperature (0.0-0.3) gives you focused, consistent answers. High temperature (0.7-1.0) gives you more creative, surprising responses. + + + +**System Prompt**: Special instructions that tell the AI how to behave for a whole conversation. For example, "You are a friendly teacher who explains things simply." Not all AI tools let you set this, but it's very powerful when available. + +## Types of AI Models + +### Text Models (LLMs) +The most common type, these generate text responses to text inputs. They power chatbots, writing assistants, and code generators. Examples: GPT-4, Claude, Llama, Mistral. + +### Multimodal Models +These can understand more than just text. They can look at images, listen to audio, and watch videos. Examples: GPT-4V, Gemini, Claude 3. + +### Text-to-Image Models + + +While this book focuses primarily on prompting for Large Language Models (text-based AI), the principles of clear, specific prompting apply to image generation too. Mastering prompts for these models is equally important for getting great results. + + +Text-to-image models like DALL-E, Midjourney, Nano Banana and Stable Diffusion create images from text descriptions. They work differently from text models: + +**How They Work:** +1. **Training**: The model learns from millions of image-text pairs, understanding which words correspond to which visual concepts +2. **Diffusion Process**: Starting from random noise, the model gradually refines the image, guided by your text prompt +3. **CLIP Guidance**: A separate model (CLIP) helps connect your words to visual concepts, ensuring the image matches your description + + + +**Prompting for Images is Different:** +Unlike text prompts where you write sentences, image prompts often work better as descriptive phrases separated by commas: + + + +### Text-to-Video Models + +Text-to-video is the newest frontier. Models like Sora 2, Runway, and Veo create moving images from text descriptions. Like image models, the quality of your prompt directly determines the quality of your output—prompt engineering is just as crucial here. + +**How They Work:** +1. **Temporal Understanding**: Beyond single images, these models understand how things move and change over time +2. **Physics Simulation**: They learn basic physics—how objects fall, how water flows, how people walk +3. **Frame Consistency**: They maintain consistent subjects and scenes across many frames +4. **Diffusion in Time**: Similar to image models, but generating coherent sequences instead of single frames + + + + +Video prompts need to describe action over time, not just a static scene. Include verbs and movement: + + + + +### Specialized Models +Fine-tuned for specific tasks like code generation (Codex, CodeLlama), music generation (Suno, Udio), or domain-specific applications like medical diagnosis or legal document analysis. + +## Model Capabilities and Limitations + +Explore what LLMs can and cannot do. Click on each capability to see example prompts: + + + +### Understanding Hallucinations + + +Sometimes AI writes things that sound true but aren't. This is called "hallucination." It's not a bug. It's just how prediction works. Always double-check important facts. + + +Why does AI make things up? + +1. It tries to write text that sounds good, not text that's always true +2. The internet (where it learned) has mistakes too +3. It can't actually check if something is real + + + +- **Ask for sources**: Then check if those sources are real +- **Ask for step-by-step thinking**: So you can check each step +- **Double-check important facts**: Use Google or trusted websites +- **Ask "Are you sure?"**: The AI might admit uncertainty + + + + + +## How AI Learns: The Three Steps + +AI doesn't just magically know things. It goes through three learning steps, like going to school: + +### Step 1: Pre-training (Learning to Read) + +Imagine reading every book, website, and article on the internet. That's what happens in pre-training. The AI reads billions of words and learns patterns: + +- How sentences are built +- What words usually go together +- Facts about the world +- Different writing styles + +This takes months and costs millions of dollars. After this step, the AI knows a lot, but it's not very helpful yet. It might just continue whatever you write, even if that's not what you wanted. + + + +### Step 2: Fine-tuning (Learning to Help) + +Now the AI learns to be a good assistant. Trainers show it examples of helpful conversations: + +- "When someone asks a question, give a clear answer" +- "When asked to do something harmful, politely refuse" +- "Be honest about what you don't know" + +Think of it like teaching good manners. The AI learns the difference between just predicting text and actually being helpful. + + + +Try the prompt above. Notice how the AI refuses? That's fine-tuning at work. + +### Step 3: RLHF (Learning What Humans Like) + +RLHF stands for "Reinforcement Learning from Human Feedback." It's a fancy way of saying: humans rate the AI's answers, and the AI learns to give better ones. + +Here's how it works: +1. The AI writes two different answers to the same question +2. A human picks which answer is better +3. The AI learns: "Okay, I should write more like Answer A" +4. This happens millions of times + +This is why AI: +- Is polite and friendly +- Admits when it doesn't know something +- Tries to see different sides of an issue +- Avoids controversial statements + + +Knowing these three steps helps you understand AI behavior. When AI refuses a request, that's fine-tuning. When AI is extra polite, that's RLHF. When AI knows random facts, that's pre-training. + + +## What This Means for Your Prompts + +Now that you understand how AI works, here's how to use that knowledge: + +### 1. Be Clear and Specific + +AI predicts what comes next based on your words. Vague prompts lead to vague answers. Specific prompts get specific results. + + + + + +### 2. Give Context + +AI doesn't know anything about you unless you tell it. Each conversation starts fresh. Include the background information AI needs. + + + + + +### 3. Work With the AI, Not Against It + +Remember: AI was trained to be helpful. Ask for things the way you'd ask a helpful friend. + + + +### 4. Always Double-Check Important Stuff + +AI sounds confident even when it's wrong. For anything important, verify the information yourself. + + + +### 5. Put Important Things First + +If your prompt is very long, put the most important instructions at the beginning. AI pays more attention to what comes first. + +## Picking the Right AI + +Different AI models are good at different things: + +
+
+ Quick questions + Faster models like GPT-4o or Claude 3.5 Sonnet +
+
+ Hard problems + Smarter models like GPT-5.2 or Claude 4.5 Opus +
+
+ Writing code + Code-focused models or the smartest general models +
+
+ Long documents + Models with big context windows (Claude, Gemini) +
+
+ Current events + Models with internet access +
+
+ +## Summary + +AI language models are prediction machines trained on text. They're amazing at many things, but they have real limits. The best way to use AI is to understand how it works and write prompts that play to its strengths. + + + + + +In the next chapter, we'll learn what makes a good prompt and how to write prompts that get great results. diff --git a/src/content/book/he/02-anatomy-of-effective-prompt.mdx b/src/content/book/he/02-anatomy-of-effective-prompt.mdx new file mode 100644 index 00000000..03cd23d2 --- /dev/null +++ b/src/content/book/he/02-anatomy-of-effective-prompt.mdx @@ -0,0 +1,343 @@ +Every great prompt shares common structural elements. Understanding these components allows you to construct prompts systematically rather than through trial and error. + + +Think of these components like LEGO bricks. You don't need all of them for every prompt, but knowing what's available helps you build exactly what you need. + + +## The Core Components + +An effective prompt typically includes some or all of these elements: + + + +Let's examine each component in detail. + +## 1. Role / Persona + +Setting a role focuses the model's responses through the lens of a specific expertise or perspective. + + + +The role primes the model to: +- Use appropriate vocabulary +- Apply relevant expertise +- Maintain a consistent perspective +- Consider the audience appropriately + +### Effective Role Patterns + +``` +"You are a [profession] with [X years] of experience in [specialty]" +"Act as a [role] who is [characteristic]" +"You are an expert [field] helping a [audience type]" +``` + +## 2. Context / Background + +Context provides the information the model needs to understand your situation. Remember: the model knows nothing about you, your project, or your goals unless you tell it. + + + +### What to Include in Context + +- **Project details** — Technology stack, architecture, constraints +- **Current state** — What you've tried, what's working, what isn't +- **Goals** — What you're ultimately trying to achieve +- **Constraints** — Time limits, technical requirements, style guides + +## 3. Task / Instruction + +The task is the heart of your prompt—what you want the model to do. Be specific and unambiguous. + +### The Specificity Spectrum + + + +### Action Verbs That Work Well + +
+
+ Creation + Write, Create, Generate, Compose, Design +
+
+ Analysis + Analyze, Evaluate, Compare, Assess, Review +
+
+ Transformation + Convert, Translate, Reformat, Summarize, Expand +
+
+ Explanation + Explain, Describe, Clarify, Define, Illustrate +
+
+ Problem-solving + Solve, Debug, Fix, Optimize, Improve +
+
+ +## 4. Constraints / Rules + +Constraints bound the model's output. They prevent common issues and ensure relevance. + +### Types of Constraints + +**Length constraints:** +``` +"Keep your response under 200 words" +"Provide exactly 5 suggestions" +"Write 3-4 paragraphs" +``` + +**Content constraints:** +``` +"Do not include any code examples" +"Focus only on the technical aspects" +"Avoid marketing language" +``` + +**Style constraints:** +``` +"Use a formal, academic tone" +"Write as if speaking to a 10-year-old" +"Be direct and avoid hedging language" +``` + +**Scope constraints:** +``` +"Only consider options available in Python 3.10+" +"Limit suggestions to free tools" +"Focus on solutions that don't require additional dependencies" +``` + +## 5. Output Format + +Specifying the output format ensures you get responses in a usable structure. + +### Common Formats + +**Lists:** +``` +"Return as a bulleted list" +"Provide a numbered list of steps" +``` + +**Structured data:** +``` +"Return as JSON with keys: title, description, priority" +"Format as a markdown table with columns: Feature, Pros, Cons" +``` + +**Specific structures:** +``` +"Structure your response as: + ## Summary + ## Key Points + ## Recommendations" +``` + +### JSON Output Example + +``` +Analyze this customer review and return JSON: +{ + "sentiment": "positive" | "negative" | "neutral", + "topics": ["array of main topics"], + "rating_prediction": 1-5, + "key_phrases": ["notable phrases"] +} + +Review: "The product arrived quickly and works great, but +the instructions were confusing." +``` + +## 6. Examples (Few-Shot Learning) + +Examples are the most powerful way to show the model exactly what you want. + +### One-Shot Example + +``` +Convert these sentences to past tense. + +Example: +Input: "She walks to the store" +Output: "She walked to the store" + +Now convert: +Input: "They run every morning" +``` + +### Few-Shot Example + +``` +Classify these support tickets by urgency. + +Examples: +"My account was hacked" → Critical +"How do I change my password?" → Low +"Payment failed but I was charged" → High + +Classify: "The app crashes when I open settings" +``` + +## Putting It All Together + +Here's a complete prompt using all components: + + + +## The Minimal Effective Prompt + +Not every prompt needs all components. For simple tasks, a clear instruction may suffice: + +``` +Translate "Hello, how are you?" to Spanish. +``` + +Use additional components when: +- The task is complex or ambiguous +- You need specific formatting +- Results aren't matching expectations +- Consistency across multiple queries matters + +## Common Prompt Patterns + +These frameworks give you a simple checklist to follow when writing prompts. Click on each step to see an example. + + + + + +## Summary + +Effective prompts are constructed, not discovered. By understanding and applying these structural components, you can: + +- Get better results on the first try +- Debug prompts that aren't working +- Create reusable prompt templates +- Communicate your intentions clearly + + + + + +## Build Your Own Prompt + +Now it's your turn! Use this interactive prompt builder to construct your own prompt using the components you've learned: + + + + + +In the next chapter, we'll explore the core principles that guide prompt construction decisions. diff --git a/src/content/book/he/03-core-prompting-principles.mdx b/src/content/book/he/03-core-prompting-principles.mdx new file mode 100644 index 00000000..358df563 --- /dev/null +++ b/src/content/book/he/03-core-prompting-principles.mdx @@ -0,0 +1,373 @@ +Beyond structure, effective prompt engineering is guided by principles—fundamental truths that apply across models, tasks, and contexts. Master these principles, and you'll be able to adapt to any prompting challenge. + + +These principles apply to every AI model and every task. Learn them once, use them everywhere. + + +## Principle 1: Clarity Over Cleverness + +The best prompts are clear, not clever. AI models are literal interpreters—they work with exactly what you give them. + +### Be Explicit + + + +### Avoid Ambiguity + +Words can have multiple meanings. Choose precise language. + + + +### State the Obvious + +What's obvious to you isn't obvious to the model. Spell out assumptions. + +``` +You're helping me write a cover letter. + +Important context: +- I'm applying for a Software Engineer position at Google +- I have 5 years of experience in Python and distributed systems +- The role requires leadership experience (I've led a team of 4) +- I want to emphasize my open-source contributions +``` + +## Principle 2: Specificity Yields Quality + +Vague inputs produce vague outputs. Specific inputs produce specific, useful outputs. + +### The Specificity Ladder + + + +Each level adds specificity and dramatically improves output quality. + +### Specify These Elements + +
+
+ Audience + Who will read/use this? +
+
+ Length + How long/short should it be? +
+
+ Tone + Formal? Casual? Technical? +
+
+ Format + Prose? List? Table? Code? +
+
+ Scope + What to include/exclude? +
+
+ Purpose + What should this accomplish? +
+
+ +## Principle 3: Context Is King + +Models have no memory, no access to your files, and no knowledge of your situation. Everything relevant must be in the prompt. + +### Provide Sufficient Context + + + +### The Context Checklist + + +Ask yourself: Would a smart stranger understand this request? If not, add more context. + + + + +## Principle 4: Guide, Don't Just Ask + +Don't just ask for an answer—guide the model toward the answer you want. + +### Use Instructional Framing + + + +### Provide Reasoning Scaffolds + +For complex tasks, guide the reasoning process: + + + +## Principle 5: Iterate and Refine + +Prompt engineering is an iterative process. Your first prompt is rarely your best. + +### The Iteration Cycle + +``` +1. Write initial prompt +2. Review output +3. Identify gaps or issues +4. Refine prompt +5. Repeat until satisfied +``` + +### Common Refinements + +
+
+ Too verbose + Add "Be concise" or length limits +
+
+ Too vague + Add specific examples or constraints +
+
+ Wrong format + Specify exact output structure +
+
+ Missing aspects + Add "Make sure to include..." +
+
+ Wrong tone + Specify audience and style +
+
+ Inaccurate + Request citations or step-by-step reasoning +
+
+ +### Keep a Prompt Journal + +Document what works: +``` +Task: Code review +Version 1: "Review this code" → Too generic +Version 2: Added specific review criteria → Better +Version 3: Added example of good review → Excellent +Final: [Save successful prompt as template] +``` + +## Principle 6: Leverage the Model's Strengths + +Work with how models are trained, not against them. + +### Models Want to Be Helpful + +Frame requests as things a helpful assistant would naturally do: + + + +### Models Excel at Patterns + +If you need consistent output, show the pattern: + + + +### Models Can Role-Play + +Use personas to access different "modes" of response: + +``` +As a devil's advocate, argue against my proposal... +As a supportive mentor, help me improve... +As a skeptical investor, question this business plan... +``` + +## Principle 7: Control Output Structure + +Structured outputs are more useful than free-form text. + +### Request Specific Formats + +``` +Return your analysis as: + +SUMMARY: [1 sentence] + +KEY FINDINGS: +• [Finding 1] +• [Finding 2] +• [Finding 3] + +RECOMMENDATION: [1-2 sentences] + +CONFIDENCE: [Low/Medium/High] because [reason] +``` + +### Use Delimiters + +Clearly separate sections of your prompt: + +``` +### CONTEXT ### +[Your context here] + +### TASK ### +[Your task here] + +### FORMAT ### +[Desired format here] +``` + +### Request Machine-Readable Output + +For programmatic use: + +``` +Return only valid JSON, no explanation: +{ + "decision": "approve" | "reject" | "review", + "confidence": 0.0-1.0, + "reasons": ["string array"] +} +``` + +## Principle 8: Verify and Validate + +Never blindly trust model outputs, especially for important tasks. + +### Ask for Reasoning + +``` +Solve this problem and show your work step by step. +After solving, verify your answer by [checking method]. +``` + +### Request Multiple Perspectives + +``` +Give me three different approaches to solve this problem. +For each, explain the trade-offs. +``` + +### Build in Self-Checking + +``` +After generating the code, review it for: +- Syntax errors +- Edge cases +- Security vulnerabilities +List any issues found. +``` + +## Summary: The Principles at a Glance + + + + + +## Practice: Fill in the Blanks + +Test your understanding of the core principles by completing this prompt template: + + + + + +These principles form the foundation for everything that follows. In Part II, we'll apply them to specific techniques that dramatically enhance prompt effectiveness. diff --git a/src/content/book/he/04-role-based-prompting.mdx b/src/content/book/he/04-role-based-prompting.mdx new file mode 100644 index 00000000..ef178cbc --- /dev/null +++ b/src/content/book/he/04-role-based-prompting.mdx @@ -0,0 +1,328 @@ +Role-based prompting is one of the most powerful and widely-used techniques in prompt engineering. By assigning a specific role or persona to the AI, you can dramatically influence the quality, style, and relevance of responses. + + +Think of roles as filters for AI's vast knowledge. The right role focuses responses like a lens focuses light. + + +## Why Roles Work + +When you assign a role, you're essentially telling the model: "Filter your vast knowledge through this specific lens." The model adjusts its: + +- **Vocabulary**: Using terminology appropriate to the role +- **Perspective**: Considering problems from that viewpoint +- **Expertise depth**: Providing role-appropriate detail levels +- **Communication style**: Matching how that role would communicate + +### The Technical Explanation + +LLMs work by predicting the most likely next token based on the context they're given. When you specify a role, you're fundamentally changing what "likely" means. + +**Activating Relevant Knowledge**: The role primes specific regions of the model's learned associations. Saying "You are a doctor" activates medical terminology, diagnostic reasoning patterns, and clinical communication styles from the training data. + +**Statistical Conditioning**: LLMs learned from millions of documents written by real experts. When you assign a role, the model conditions its probability distributions to match patterns it saw from that type of author. + +**Reducing Ambiguity**: Without a role, the model averages across all possible responders. With a role, it narrows to a specific subset, making responses more focused and consistent. + +**Context Anchoring**: The role creates a persistent context anchor throughout the conversation. Every subsequent response is influenced by this initial framing. + +Think of it this way: if you ask "What should I do about this cough?" the model could respond as a doctor, a friend, a pharmacist, or a worried parent. Each would give different advice. By specifying the role upfront, you're telling the model which "voice" to use from its training data. + + +The model isn't pretending or role-playing in a theatrical sense. It's statistically biasing its outputs toward patterns it learned from real experts, professionals, and specialists during training. A "doctor" role activates medical knowledge pathways; a "poet" role activates literary patterns. + + +## Basic Role Patterns + +These foundational patterns work across most use cases. Start with these templates and customize them for your needs. + +### The Expert Pattern + +The most versatile pattern. Specify the field of expertise and years of experience to get authoritative, in-depth responses. Works well for technical questions, analysis, and professional advice. + + + +### The Professional Pattern + +Ground the role in a real-world context by specifying a job title and organization type. This adds institutional knowledge and professional norms to the response. + + + +### The Teacher Pattern + +Perfect for learning and explanations. Specifying the audience level ensures the response matches the learner's background, from beginners to advanced practitioners. + + + +## Advanced Role Constructions + +### Compound Roles + +Combine multiple identities to get responses that blend different perspectives. This pediatrician-parent combination produces advice that's both medically sound and practically tested. + + + +### Situational Roles + +Place the role in a specific scenario to shape both content and tone. Here, the code review context makes the AI constructive and educational rather than just critical. + + + +### Perspective Roles + +Get feedback from a specific stakeholder's point of view. A VC perspective evaluates viability and scalability differently than a customer or engineer would. + + + +## Role Categories and Examples + +Different domains benefit from different types of roles. Here are proven examples organized by category that you can adapt for your tasks. + +### Technical Roles + +**Software Architect**: Best for system design decisions, technology choices, and architectural trade-offs. The focus on maintainability steers responses toward practical, long-term solutions. + + + +**Security Specialist**: The attacker mindset is key here. This role produces threat-focused analysis that identifies vulnerabilities a defensive-only perspective might miss. + + + +**DevOps Engineer**: Ideal for deployment, automation, and infrastructure questions. The emphasis on reliability ensures production-ready recommendations. + + + +### Creative Roles + +**Copywriter**: The "award-winning" qualifier and conversion focus produce punchy, persuasive copy rather than generic marketing text. + + + +**Screenwriter**: Activates knowledge of dramatic structure, pacing, and dialogue conventions. Great for any narrative writing that needs tension and character voice. + + + +**UX Writer**: A specialized role for interface text. The focus on brevity and user guidance produces concise, action-oriented copy. + + + +### Analytical Roles + +**Business Analyst**: Bridges the gap between technical and non-technical stakeholders. Useful for requirement gathering, spec writing, and identifying gaps in project plans. + + + +**Research Scientist**: The emphasis on evidence and uncertainty acknowledgment produces balanced, well-sourced responses that distinguish facts from speculation. + + + +**Financial Analyst**: Combines quantitative analysis with risk assessment. The dual focus on returns and risk produces more balanced investment perspectives. + + + +### Educational Roles + +**Socratic Tutor**: Instead of giving answers, this role asks guiding questions. Excellent for deeper learning and helping students develop critical thinking skills. + + + +**Instructional Designer**: Structures learning for maximum retention. Use this role when you need to break down complex topics into teachable chunks with clear progression. + + + +## The Role Stack Technique + +For complex tasks, combine multiple role aspects into a single, layered identity. This technique stacks expertise, audience awareness, and style guidelines to create highly specialized responses. + +This example layers three elements: domain expertise (API documentation), audience (junior developers), and style guide (Google's conventions). Each layer constrains the output further. + + + +## Roles for Different Tasks + +
+
+ Code review + Senior developer + mentor +
+
+ Writing feedback + Editor + target audience member +
+
+ Business strategy + Consultant + industry expert +
+
+ Learning new topic + Patient teacher + practitioner +
+
+ Creative writing + Specific genre author +
+
+ Technical explanation + Expert + communicator +
+
+ Problem-solving + Domain specialist + generalist +
+
+ +## Anti-Patterns to Avoid + +### Overly Generic Roles + + + +### Conflicting Roles + + + +### Unrealistic Expertise + + + +## Real-World Prompt Examples + +### Technical Documentation + + + +### Creative Writing + + + +### Business Communication + + + +## Combining Roles with Other Techniques + +Roles work even better when combined with other prompting techniques: + +### Role + Few-Shot + +Combine a role with an example to show exactly how the role should respond. The example teaches tone and format while the role provides context and expertise. + + + +### Role + Chain of Thought + +The detective role naturally encourages step-by-step reasoning. Combining roles with chain-of-thought produces more transparent, verifiable problem-solving. + + + +## Summary + + +Role-based prompting is powerful because it focuses the model's vast knowledge, sets expectations for tone and style, provides implicit context, and makes outputs more consistent. + + + + +The key is **specificity**: the more detailed and realistic the role, the better the results. In the next chapter, we'll explore how to get consistent, structured outputs from your prompts. diff --git a/src/content/book/he/05-structured-output.mdx b/src/content/book/he/05-structured-output.mdx new file mode 100644 index 00000000..8236abee --- /dev/null +++ b/src/content/book/he/05-structured-output.mdx @@ -0,0 +1,411 @@ +Getting consistent, well-formatted output is essential for production applications and efficient workflows. This chapter covers techniques for controlling exactly how AI models format their responses. + + +Structured output transforms AI responses from freeform text into actionable, parseable data. + + +## Why Structure Matters + + + +## Basic Formatting Techniques + +### Lists + +Lists are perfect for step-by-step instructions, ranked items, or collections of related points. They're easy to scan and parse. Use **numbered lists** when order matters (steps, rankings) and **bullet points** for unordered collections. + + + + +Specify the exact number of items you want, whether to include explanations, and if items should be bold or have a specific structure. + + +### Tables + +Tables excel at comparing multiple items across the same dimensions. They're ideal for feature comparisons, data summaries, and any information with consistent attributes. Always define your column headers explicitly. + + + + +Specify column names, expected data types (text, numbers, ratings), and how many rows you need. For complex comparisons, limit to 4-6 columns for readability. + + +### Headers and Sections + +Headers create a clear document structure, making long responses scannable and organized. Use them for reports, analyses, or any multi-part response. Hierarchical headers (##, ###) show relationships between sections. + +``` +Analyze this business proposal. + +Structure your response with these sections: +## Executive Summary +## Strengths +## Weaknesses +## Recommendations +## Risk Assessment +``` + + +List your sections in the order you want them. For consistency, specify what each section should contain (e.g., "Executive Summary: 2-3 sentences only"). + + +### Emphasis with Uppercase Directives + +Uppercase words act as strong signals to the model, emphasizing critical constraints or requirements. Use them sparingly for maximum impact—overuse dilutes their effectiveness. + +**Common Uppercase Directives:** + + + +``` +Summarize this article. + +IMPORTANT: Keep the summary under 100 words. +NEVER add information not present in the original. +ALWAYS maintain the original tone and perspective. +DO NOT include your own opinions or analysis. +``` + + +If everything is uppercase or marked as critical, nothing stands out. Reserve these directives for genuinely important constraints. + + +## JSON Output + +JSON (JavaScript Object Notation) is the most popular format for structured AI output. It's machine-readable, widely supported by programming languages, and perfect for APIs, databases, and automation workflows. The key to reliable JSON is providing a clear schema. + +### Basic JSON Request + +Start with a template showing the exact structure you want. Include field names, data types, and example values. This acts as a contract the model will follow. + + + +### Complex JSON Structures + +For nested data, use hierarchical JSON with objects inside objects, arrays of objects, and mixed types. Define each level clearly and use TypeScript-style annotations (`"positive" | "negative"`) to constrain values. + +``` +Analyze this product review and return JSON: + +{ + "review_id": "string (generate unique)", + "sentiment": { + "overall": "positive" | "negative" | "mixed" | "neutral", + "score": 0.0-1.0 + }, + "aspects": [ + { + "aspect": "string (e.g., 'price', 'quality')", + "sentiment": "positive" | "negative" | "neutral", + "mentions": ["exact quotes from review"] + } + ], + "purchase_intent": { + "would_recommend": boolean, + "confidence": 0.0-1.0 + }, + "key_phrases": ["string array of notable phrases"] +} + +Return ONLY valid JSON, no additional text. + +Review: "[review text]" +``` + +### Ensuring Valid JSON + +Models sometimes add explanatory text or markdown formatting around JSON. Prevent this with explicit instructions about output format. You can request raw JSON or JSON inside code blocks—choose based on your parsing needs. + +Add explicit instructions: + +``` +IMPORTANT: +- Return ONLY the JSON object, no markdown code blocks +- Ensure all strings are properly escaped +- Use null for missing values, not undefined +- Validate that the output is parseable JSON +``` + +Or request code blocks by asking the model to wrap its output: + +```` +Return the result as a JSON code block: +```json +{ ... } +``` +```` + +## YAML Output + +YAML is more human-readable than JSON, using indentation instead of brackets. It's the standard for configuration files (Docker, Kubernetes, GitHub Actions) and works well when the output will be read by humans or used in DevOps contexts. YAML is sensitive to indentation, so be specific about formatting requirements. + + + +## XML Output + +XML is still required for many enterprise systems, SOAP APIs, and legacy integrations. It's more verbose than JSON but offers features like attributes, namespaces, and CDATA sections for complex data. Specify element names, nesting structure, and where to use attributes vs. child elements. + +``` +Convert this data to XML format: + +Requirements: +- Root element: +- Each item in element +- Include attributes where appropriate +- Use CDATA for description text + +Data: [book data] +``` + +## Custom Formats + +Sometimes standard formats don't fit your needs. You can define any custom format by providing a clear template. Custom formats work well for reports, logs, or domain-specific outputs that will be read by humans. + +### Structured Analysis Format + +Use delimiters (===, ---, [SECTION]) to create scannable documents with clear boundaries between sections. This format is great for code reviews, audits, and analyses. + +``` +Analyze this code using this exact format: + +=== CODE ANALYSIS === + +[SUMMARY] +One paragraph overview + +[ISSUES] +• CRITICAL: [issue] — [file:line] +• WARNING: [issue] — [file:line] +• INFO: [issue] — [file:line] + +[METRICS] +Complexity: [Low/Medium/High] +Maintainability: [score]/10 +Test Coverage: [estimated %] + +[RECOMMENDATIONS] +1. [Priority 1 recommendation] +2. [Priority 2 recommendation] + +=== END ANALYSIS === +``` + +### Fill-in-the-Blank Format + +Templates with blanks (___) guide the model to fill in specific fields while maintaining exact formatting. This approach is excellent for forms, briefs, and standardized documents where consistency matters. + +``` +Complete this template for the given product: + +PRODUCT BRIEF +───────────── +Name: _______________ +Tagline: _______________ +Target User: _______________ +Problem Solved: _______________ +Key Features: + 1. _______________ + 2. _______________ + 3. _______________ +Differentiator: _______________ + +Product: [product description] +``` + +## Typed Responses + +Typed responses define categories or entity types that the model should recognize and label. This technique is essential for Named Entity Recognition (NER), classification tasks, and any extraction where you need to categorize information consistently. Define your types clearly with examples. + + + +## Multi-Part Structured Responses + +When you need comprehensive output covering multiple aspects, define distinct parts with clear boundaries. Specify exactly what goes in each part—format, length, and content type. This prevents the model from blending sections or omitting parts. + +``` +Research this topic and provide: + +### PART 1: EXECUTIVE SUMMARY +[2-3 sentence overview] + +### PART 2: KEY FINDINGS +[Exactly 5 bullet points] + +### PART 3: DATA TABLE +| Metric | Value | Source | +|--------|-------|--------| +[Include 5 rows minimum] + +### PART 4: RECOMMENDATIONS +[Numbered list of 3 actionable recommendations] + +### PART 5: FURTHER READING +[3 suggested resources with brief descriptions] +``` + +## Conditional Formatting + +Conditional formatting lets you define different output formats based on the input's characteristics. This is powerful for classification, triage, and routing systems where the response format should vary based on what the model detects. Use clear if/then logic with explicit output templates for each case. + + + +## Arrays and Lists in JSON + +Extracting multiple items into arrays requires careful schema definition. Specify the array structure, what each item should contain, and how to handle edge cases (empty arrays, single items). Including a count field helps verify completeness. + +``` +Extract all action items from this meeting transcript. + +Return as JSON array: +{ + "action_items": [ + { + "task": "string describing the task", + "assignee": "person name or 'Unassigned'", + "deadline": "date if mentioned, else null", + "priority": "high" | "medium" | "low", + "context": "relevant quote from transcript" + } + ], + "total_count": number +} + +Transcript: "[meeting transcript]" +``` + +## Validation Instructions + +Self-validation prompts the model to check its own output before responding. This catches common issues like missing sections, placeholder text, or constraint violations. The model will iterate internally to fix problems, improving output quality without additional API calls. + +``` +Generate the report, then: + +VALIDATION CHECKLIST: +□ All required sections present +□ No placeholder text remaining +□ All statistics include sources +□ Word count within 500-700 words +□ Conclusion ties back to introduction + +If any check fails, fix before responding. +``` + +## Handling Optional Fields + +Real-world data often has missing values. Explicitly instruct the model on how to handle optional fields—using `null` is cleaner than empty strings and easier to process programmatically. Also prevent "hallucination" of missing data by emphasizing that the model should never invent information. + +``` +Extract contact information. Use null for missing fields. + +{ + "name": "string (required)", + "email": "string or null", + "phone": "string or null", + "company": "string or null", + "role": "string or null", + "linkedin": "URL string or null" +} + +IMPORTANT: +- Never invent information not in the source +- Use null, not empty strings, for missing data +- Phone numbers in E.164 format if possible +``` + +## Summary + + +Be explicit about format, use examples, specify types, handle edge cases with null values, and ask the model to validate its own output. + + + + +Structured outputs are essential for building reliable AI-powered applications. In the next chapter, we'll explore chain-of-thought prompting for complex reasoning tasks. diff --git a/src/content/book/he/06-chain-of-thought.mdx b/src/content/book/he/06-chain-of-thought.mdx new file mode 100644 index 00000000..e579be5d --- /dev/null +++ b/src/content/book/he/06-chain-of-thought.mdx @@ -0,0 +1,363 @@ +Chain of Thought (CoT) prompting is a technique that dramatically improves AI performance on complex reasoning tasks by asking the model to show its work step by step. + + +Just like a math teacher asking students to show their work, CoT prompting asks the AI to make its reasoning visible. + + +## The Problem CoT Solves + +AI models can struggle with multi-step reasoning when asked to jump directly to an answer. + + + +## Basic CoT Prompts + +### Simple Trigger Phrases + +Add one of these to your prompts: + +
+
"Let's think step by step."
+
"Think through this carefully."
+
"Work through this problem methodically."
+
"Show your reasoning at each step."
+
"Explain your thought process."
+
+ +### Explicit Step Request + + + +## Zero-Shot vs Few-Shot CoT + +There are two main approaches to Chain of Thought prompting, each with different trade-offs between simplicity and control. + +### Zero-Shot CoT + +The simplest approach—just add a trigger phrase and let the model figure out how to reason. No examples needed. This works surprisingly well for many problems, though you have less control over the reasoning format. + + + +**Example Output:** +``` +Let's think step by step. +- John starts with 3 apples +- Half of 3 is 1.5, but we can't split apples +- If we round down: John gives 1 apple, keeps 2 +- After buying 4 more: 2 + 4 = 6 apples + +Answer: 6 apples +``` + +### Few-Shot CoT + +For more consistent results, show the model exactly how you want it to reason by providing worked examples. This gives you control over the reasoning style, format, and level of detail. The model will mimic your demonstrated pattern. + + + +**Example Output:** +``` +A: Let's work through this: +- Regular price: $3, Quantity: 12 +- Since 12 ≥ 10, the 25% discount applies +- Regular total: 12 × $3 = $36 +- Discount: 25% of $36 = $9 +- Final price: $36 - $9 = $27 +``` + +## Structured CoT Formats + +For consistent, reproducible reasoning, use structured formats with named steps. These frameworks ensure the model doesn't skip important stages and makes outputs easier to parse and verify. + +### The BREAK Format + +A memorable acronym that guides the model through a complete problem-solving cycle, from understanding to verification. + + + +### The Reasoning Template + +A more formal structure that separates inputs, goals, and execution. Excellent for technical problems where you need clear documentation of the solution process. + + + +**Example Output:** +``` +GIVEN: 8L/100km, tank 45L, $1.50/L, drive 300km +GOAL: Calculate fuel cost +APPROACH: Fuel needed × cost per liter +STEPS: +1. Fuel = (300 ÷ 100) × 8 = 24 liters +2. Cost = 24 × $1.50 = $36 +VERIFICATION: 24L < 45L tank ✓ +ANSWER: $36 +``` + +## CoT for Different Problem Types + +Different problem types benefit from different CoT approaches. Here are patterns optimized for common scenarios. + +### Mathematical Reasoning + +Math problems benefit most from CoT because each step builds on the previous one. Errors compound, so showing work helps catch mistakes early. The model should clearly label each calculation. + + + +**Example Output:** +``` +Q1: $1,200,000 (given) +Q2: $1,200,000 × 1.15 = $1,380,000 +Q3: $1,380,000 × 0.90 = $1,242,000 +Q4: $1,242,000 × 1.25 = $1,552,500 + +Total: $5,374,500 +``` + +### Logical Reasoning + +Logic puzzles require systematic elimination and hypothesis testing. CoT helps the model track constraints, test possibilities, and verify that all conditions are satisfied. The key is methodical exploration rather than guessing. + + + +**Example Output:** +``` +From clue 3: Bob = teacher +→ Alice and Carol are engineer/doctor + +If Carol = engineer: +- Carol has dog (clue 2) +- Alice = doctor, has fish (clue 1) +- Bob has cat + +Verify: All 4 clues satisfied ✓ +Answer: Alice (doctor, fish), Bob (teacher, cat), Carol (engineer, dog) +``` + +### Code Debugging + +Debugging benefits from CoT because it forces the model to trace execution rather than guess at bugs. By walking through the code with concrete values, the actual behavior becomes visible and discrepancies with expected behavior are exposed. + + + +**Example Output:** +``` +Trace [2, 3, 4, 6]: +n=2: total += 1 → 1 (wait, adding 1 not n!) +n=3: skip (odd) +n=4: total = 2 +n=6: total = 3 + +BUG: "total += 1" should be "total += n" +Expected: 12, Got: 3 +Fix: Change to "total += n" +``` + +## Self-Consistency with CoT + +For critical problems, don't rely on a single reasoning path. Generate multiple independent solutions and compare results. If different approaches converge on the same answer, confidence is high. Disagreement signals the need for careful review. + + + +**Example Output:** +``` +Approach 1 (Algebra): c + w = 30, 2c + 4w = 74 → c=23, w=7 +Approach 2 (Guess): Try 23/7 → 46 + 28 = 74 ✓ +Approach 3 (Logic): 30 chickens = 60 legs, need 14 more → 7 cows + +All agree: 23 chickens, 7 cows +``` + +## CoT for Decision Making + +Decisions involve weighing trade-offs across multiple dimensions. CoT ensures all relevant factors are considered systematically rather than jumping to conclusions. This structured approach also documents the reasoning for future reference. + + + +**Example Output:** +``` +FACTORS: +- Team size (5): Too small for microservices ❌ +- Scale (100 DAU): No scaling need ❌ +- Velocity: Monolith = faster iteration ❌ +- Future growth: Uncertain timeline ⚠️ + +WEIGHING: 3 strong against, 1 weak for + +RECOMMENDATION: Stay monolith, use clear module +boundaries to ease future transition. +``` + +## When to Use CoT + +
+
+

Use CoT For

+
+

**Math problems** — Reduces calculation errors

+

**Logic puzzles** — Prevents skipped steps

+

**Complex analysis** — Organizes thinking

+

**Code debugging** — Traces execution

+

**Decision making** — Weighs trade-offs

+
+
+
+

Skip CoT For

+
+

**Simple Q&A** — Unnecessary overhead

+

**Creative writing** — Can constrain creativity

+

**Factual lookups** — No reasoning needed

+

**Translation** — Direct task

+

**Summarization** — Usually straightforward

+
+
+
+ +## CoT Limitations + +While powerful, Chain of Thought isn't a silver bullet. Understanding its limitations helps you apply it appropriately. + +1. **Increased token usage** — More output means higher costs +2. **Not always needed** — Simple tasks don't benefit +3. **Can be verbose** — May need to ask for conciseness +4. **Reasoning can be flawed** — CoT doesn't guarantee correctness + +## Summary + + +CoT dramatically improves complex reasoning by making implicit steps explicit. Use it for math, logic, analysis, and debugging. Trade-off: better accuracy for more tokens. + + + + +In the next chapter, we'll explore few-shot learning—teaching the model through examples. diff --git a/src/content/book/he/07-few-shot-learning.mdx b/src/content/book/he/07-few-shot-learning.mdx new file mode 100644 index 00000000..24e98f1d --- /dev/null +++ b/src/content/book/he/07-few-shot-learning.mdx @@ -0,0 +1,478 @@ +Few-shot learning is one of the most powerful prompting techniques. By providing examples of what you want, you can teach the model complex tasks without any fine-tuning. + + +Just like humans learn by seeing examples, AI models can learn patterns from the examples you provide in your prompt. + + +## What is Few-Shot Learning? + +Few-shot learning shows the model examples of input-output pairs before asking it to perform the same task. The model learns the pattern from your examples and applies it to new inputs. + + + +
+
+
0
+
Zero-shot
+
+
+
1
+
One-shot
+
+
+
2-5
+
Few-shot
+
+
+
5+
+
Many-shot
+
+
+ +## Why Examples Work + + + +Examples communicate: +- **Format**: How output should be structured +- **Style**: Tone, length, vocabulary +- **Logic**: The reasoning pattern to follow +- **Edge cases**: How to handle special situations + +## Basic Few-Shot Pattern + +The fundamental structure of few-shot prompting follows a simple pattern: show examples, then ask for the new task. Consistency in formatting between examples is crucial. The model learns from the pattern you establish. + +``` +[Example 1] +Input: [input 1] +Output: [output 1] + +[Example 2] +Input: [input 2] +Output: [output 2] + +[Example 3] +Input: [input 3] +Output: [output 3] + +Now do this one: +Input: [new input] +Output: +``` + +## Few-Shot for Classification + +Classification is one of the strongest use cases for few-shot learning. By showing examples of each category, you define the boundaries between classes more precisely than instructions alone could achieve. + +### Sentiment Analysis + + +Sentiment analysis classifies text by emotional tone: positive, negative, neutral, or mixed. It's widely used for customer feedback, social media monitoring, and brand perception tracking. + + +Sentiment classification benefits from showing examples of each sentiment type, especially edge cases like "mixed" sentiment that might be ambiguous. + + + +### Topic Classification + +For multi-class categorization, include at least one example per category. This helps the model understand your specific taxonomy, which may differ from its default understanding. + + + +## Few-Shot for Transformation + +Transformation tasks convert input from one form to another while preserving meaning. Examples are essential here because they define exactly what "transformation" means for your use case. + +### Text Rewriting + +Style transformation requires examples that show the exact tone shift you want. Abstract instructions like "make it professional" are interpreted differently. Examples make it concrete. + + + +### Format Conversion + +Format conversion tasks benefit from examples showing edge cases and ambiguous inputs. The model learns your specific conventions for handling tricky cases. + + + +## Few-Shot for Generation + +Generation tasks create new content following a learned pattern. Examples establish length, structure, tone, and what details to highlight. These are hard to specify in instructions alone. + +### Product Descriptions + +Marketing copy benefits enormously from examples because they capture brand voice, feature emphasis, and persuasive techniques that are difficult to describe abstractly. + + + +### Code Documentation + + +Good documentation explains what code does, its parameters, return values, and usage examples. Consistent docstrings enable auto-generated API docs and help IDEs provide better code completion. + + +Documentation style varies widely between projects. Examples teach your specific format, what to include (args, returns, examples), and the level of detail expected. + +>> calculate_bmi(70, 1.75) + 22.86 +""" + +Now document: +Function: +def is_palindrome(text): + cleaned = ''.join(c.lower() for c in text if c.isalnum()) + return cleaned == cleaned[::-1] + +Documentation:`} /> + +## Few-Shot for Extraction + +Extraction tasks pull structured information from unstructured text. Examples define which entities matter, how to format output, and how to handle cases where information is missing or ambiguous. + +### Entity Extraction + + +Named Entity Recognition (NER) identifies and classifies named entities in text into categories like persons, organizations, locations, dates, and products. It's fundamental for information retrieval and knowledge graphs. + + +NER benefits from examples showing your specific entity types and how to handle entities that could fit multiple categories. + + + +### Structured Data Extraction + +Extracting structured data from natural language requires examples showing how to handle missing fields, implicit information, and varying input formats. + + + +## Advanced Few-Shot Techniques + +Beyond basic few-shot, several techniques can improve results for complex tasks. + +### Diverse Examples + +Diversity in examples is more valuable than quantity. Cover different scenarios, edge cases, and potential ambiguities rather than showing similar examples repeatedly. + + + +### Negative Examples + + +Showing "good" vs "bad" examples is called contrastive learning. It helps the model understand not just what you want, but what to avoid. This is especially useful for style and quality judgments. + + +Sometimes showing what *not* to do is as valuable as showing correct examples. Negative examples help the model understand boundaries and avoid common mistakes. + + + +### Edge Case Examples + +Edge cases often determine whether a solution works in production. Including unusual inputs in your examples prevents the model from failing on real-world data that doesn't fit the "happy path." + + + +## How Many Examples? + +
+
+ Simple classification + 2-3 + One per category minimum +
+
+ Complex formatting + 3-5 + Show variations +
+
+ Nuanced style + 4-6 + Capture full range +
+
+ Edge cases + 1-2 + Alongside normal examples +
+
+ +## Example Quality Matters + + + +## Combining Few-Shot with Other Techniques + +Few-shot learning combines powerfully with other prompting techniques. The examples provide the "what" while other techniques can add context, reasoning, or structure. + +### Few-Shot + Role + +Adding a role gives the model context for *why* it's doing the task, which can improve quality and consistency. + +``` +You are a legal contract reviewer. + +[examples of contract clause analysis] + +Now analyze: [new clause] +``` + +### Few-Shot + CoT + +Combining few-shot with Chain of Thought shows not just *what* answer to give, but *how* to reason through to that answer. This is powerful for tasks requiring judgment. + +``` +Classify and explain reasoning. + +Review: "Great features but overpriced" +Thinking: The review mentions positive aspects ("great features") +but also a significant negative ("overpriced"). The negative seems +to outweigh the positive based on the "but" conjunction. +Classification: Mixed-Negative + +[more examples with reasoning] + +Now classify with reasoning: +Review: "Exactly what I needed, arrived faster than expected" +``` + +## Summary + + +Few-shot learning teaches through demonstration and is often more effective than instructions alone. Use 2-5 diverse, correct examples and combine with other techniques for best results. + + + + +In the next chapter, we'll explore iterative refinement: the art of improving prompts through successive attempts. diff --git a/src/content/book/he/08-iterative-refinement.mdx b/src/content/book/he/08-iterative-refinement.mdx new file mode 100644 index 00000000..769f879a --- /dev/null +++ b/src/content/book/he/08-iterative-refinement.mdx @@ -0,0 +1,387 @@ +Prompt engineering is rarely a one-shot process. The best prompts emerge through iteration—testing, observing, and refining until you achieve the desired results. + + +Think of your first prompt as a rough draft. Even experienced prompt engineers rarely nail it on the first try. + + +## The Iteration Cycle + +Effective prompt refinement follows a predictable cycle: write, test, analyze, and improve. Each iteration brings you closer to a prompt that reliably produces the results you need. + + + +## Common Refinement Patterns + +Most prompt failures fall into a handful of categories. Learning to recognize these patterns lets you quickly diagnose and fix issues without starting from scratch. + +### Problem: Output Too Long + +One of the most common issues. Without explicit constraints, models tend to be thorough rather than concise. + + + +### Problem: Output Too Vague + +Vague prompts produce vague outputs. The model can't read your mind about what "better" means or which aspects matter most to you. + + + +### Problem: Wrong Tone + +Tone is subjective and varies by context. What sounds "professional" to the model might not match your organization's voice or the relationship with your recipient. + + + +### Problem: Missing Key Information + +Open-ended requests get open-ended responses. If you need specific types of feedback, you must ask for them explicitly. + + + +### Problem: Inconsistent Format + +Without a template, the model will structure each response differently, making comparison difficult and automation impossible. + + + +## Systematic Refinement Approach + +Random changes waste time. A systematic approach helps you identify problems quickly and fix them efficiently. + +### Step 1: Diagnose the Issue + +Before changing anything, identify what's actually wrong. Use this diagnostic table to map symptoms to solutions: + +
+
+ Symptom + Likely Cause + Solution +
+
+ Too long + No length constraint + Add word/sentence limits +
+
+ Too short + Lacks detail request + Ask for elaboration +
+
+ Off-topic + Vague instructions + Be more specific +
+
+ Wrong format + Format not specified + Define exact structure +
+
+ Wrong tone + Audience not clear + Specify audience/style +
+
+ Inconsistent + No examples provided + Add few-shot examples +
+
+ +### Step 2: Make Targeted Changes + +Resist the urge to rewrite everything. Changing multiple variables at once makes it impossible to know what helped and what hurt. Make one change, test it, then proceed: + +``` +Iteration 1: Add length constraint +Iteration 2: Specify format +Iteration 3: Add example +Iteration 4: Refine tone instructions +``` + +### Step 3: Document What Works + +Prompt engineering knowledge is easily lost. Keep a log of what you tried and why. This saves time when you revisit the prompt later or face similar challenges: + +```markdown +## Prompt: Customer Email Response + +### Version 1 (too formal) +"Write a response to this customer complaint." + +### Version 2 (better tone, still missing structure) +"Write a friendly but professional response to this complaint. +Show empathy first." + +### Version 3 (final - good results) +"Write a response to this customer complaint. Structure: +1. Acknowledge their frustration (1 sentence) +2. Apologize specifically (1 sentence) +3. Explain solution (2-3 sentences) +4. Offer additional help (1 sentence) + +Tone: Friendly, professional, empathetic but not groveling." +``` + +## Real-World Iteration Example + +Let's walk through a complete iteration cycle to see how each refinement builds on the last. Notice how each version addresses specific shortcomings of the previous one. + +### Task: Generate Product Names + + + +## Refinement Strategies by Task Type + +Different tasks fail in predictable ways. Knowing the common failure modes helps you diagnose and fix issues faster. + +### For Content Generation + +Content generation often produces generic, off-target, or poorly formatted output. The fix usually involves being more specific about constraints, providing concrete examples, or defining your brand voice explicitly. + + + +### For Code Generation + +Code output can fail technically (syntax errors, wrong language features) or architecturally (poor patterns, missing cases). Technical issues need version/environment specifics; architectural issues need design guidance. + + + +### For Analysis + +Analysis tasks often produce surface-level or unstructured results. Guide the model with specific frameworks (SWOT, Porter's Five Forces), request multiple viewpoints, or provide a template for the output structure. + + + +### For Q&A + +Question-answering can be too terse or too verbose, and may lack confidence indicators or sources. Specify the detail level you need and whether you want citations or uncertainty expressed. + + + +## The Feedback Loop Technique + +Here's a meta-technique: use the model itself to help improve your prompts. Share what you tried, what you got, and what you wanted. The model can often suggest improvements you hadn't considered. + +``` +I used this prompt: +"[your prompt]" + +And got this output: +"[model output]" + +I wanted something more [describe gap]. How should I modify +my prompt to get better results? +``` + +## A/B Testing Prompts + +For prompts that will be used repeatedly or at scale, don't just pick the first one that works. Test variations to find the most reliable and highest-quality approach. + +``` +Prompt A: "Summarize this article in 3 bullet points." +Prompt B: "Extract the 3 most important insights from this article." +Prompt C: "What are the key takeaways from this article? List 3." +``` + +Run each multiple times, compare: +- Consistency of output +- Quality of information +- Relevance to your needs + +## When to Stop Iterating + +Perfection is the enemy of good enough. Know when your prompt is ready for use and when you're just polishing for diminishing returns. + +
+
+

Ready to Ship

+
+

Output consistently meets requirements

+

Edge cases are handled appropriately

+

Format is reliable and parseable

+

Further improvements show diminishing returns

+
+
+
+

Keep Iterating

+
+

Output is inconsistent across runs

+

Edge cases cause failures

+

Critical requirements are missed

+

You haven't tested enough variations

+
+
+
+ +## Version Control for Prompts + +Prompts are code. For any prompt used in production, treat it with the same rigor: version control, changelogs, and the ability to roll back if something breaks. + + +prompts.chat includes automatic version history for your prompts. Every edit is saved, so you can compare versions and restore previous iterations with one click. + + +For self-managed prompts, use a folder structure: + +``` +prompts/ +├── customer-response/ +│ ├── v1.0.txt # Initial version +│ ├── v1.1.txt # Fixed tone issue +│ ├── v2.0.txt # Major restructure +│ └── current.txt # Symlink to active version +└── changelog.md # Document changes +``` + +## Summary + + +Start simple, observe carefully, change one thing at a time, document what works, and know when to stop. The best prompts aren't written—they're discovered through systematic iteration. + + + + +## Practice: Improve This Prompt + +Try improving this weak prompt yourself. Edit it, then use AI to compare your version with the original: + + + +In the next chapter, we'll explore JSON and YAML prompting for structured data applications. diff --git a/src/content/book/he/09-json-yaml-prompting.mdx b/src/content/book/he/09-json-yaml-prompting.mdx new file mode 100644 index 00000000..318619da --- /dev/null +++ b/src/content/book/he/09-json-yaml-prompting.mdx @@ -0,0 +1,586 @@ +Structured data formats like JSON and YAML are essential for building applications that consume AI outputs programmatically. This chapter covers techniques for reliable structured output generation. + + +JSON and YAML transform AI outputs from freeform text into structured, type-safe data that code can consume directly. + + +## Why Structured Formats? + + + +## JSON Prompting Basics + +JSON (JavaScript Object Notation) is the most common format for programmatic AI outputs. Its strict syntax makes it easy to parse, but also means small errors can break your entire pipeline. + +### Do's and Don'ts: Requesting JSON + + + +### Simple JSON Output + +Start with a schema showing the expected structure. The model will fill in values based on the input text. + +``` +Extract the following information as JSON: + +{ + "name": "string", + "age": number, + "email": "string" +} + +Text: "Contact John Smith, 34 years old, at john@example.com" +``` + +Output: +```json +{ + "name": "John Smith", + "age": 34, + "email": "john@example.com" +} +``` + +### Nested JSON Structures + +Real-world data often has nested relationships. Define each level of your schema clearly, especially for arrays of objects. + +``` +Parse this order into JSON: + +{ + "order_id": "string", + "customer": { + "name": "string", + "email": "string" + }, + "items": [ + { + "product": "string", + "quantity": number, + "price": number + } + ], + "total": number +} + +Order: "Order #12345 for Jane Doe (jane@email.com): 2x Widget ($10 each), +1x Gadget ($25). Total: $45" +``` + +### Ensuring Valid JSON + + +Models often wrap JSON in markdown code blocks or add explanatory text. Be explicit about wanting raw JSON only. + + +Add explicit instructions: + +``` +CRITICAL: Return ONLY valid JSON. No markdown, no explanation, +no additional text before or after the JSON object. + +If a field cannot be determined, use null. +Ensure all strings are properly quoted and escaped. +Numbers should not be quoted. +``` + +## YAML Prompting Basics + +YAML is more human-readable than JSON and supports comments. It's the standard for configuration files, especially in DevOps (Docker, Kubernetes, GitHub Actions). + +### Simple YAML Output + +YAML uses indentation instead of braces. Provide a template showing the expected structure. + +``` +Generate a configuration file in YAML format: + +server: + host: string + port: number + ssl: boolean +database: + type: string + connection_string: string + +Requirements: Production server on port 443 with SSL, PostgreSQL database +``` + +Output: +```yaml +server: + host: "0.0.0.0" + port: 443 + ssl: true +database: + type: "postgresql" + connection_string: "postgresql://user:pass@localhost:5432/prod" +``` + +### Complex YAML Structures + +For complex configurations, be specific about requirements. The model knows common patterns for tools like GitHub Actions, Docker Compose, and Kubernetes. + +``` +Generate a GitHub Actions workflow in YAML: + +Requirements: +- Trigger on push to main and pull requests +- Run on Ubuntu latest +- Steps: checkout, setup Node 18, install dependencies, run tests +- Cache npm dependencies +``` + +## Type Definitions in Prompts + +Type definitions give the model a precise contract for output structure. They're more explicit than examples and easier to validate programmatically. + +### Using TypeScript-like Types + +TypeScript interfaces are familiar to developers and precisely describe optional fields, union types, and arrays. The prompts.chat platform uses this approach for structured prompts. + + + +### JSON Schema Definition + + +JSON Schema is a formal specification for describing JSON structure. It's supported by many validation libraries and API tools. + + +JSON Schema provides constraints like min/max values, required fields, and regex patterns: + +``` +Extract data according to this JSON Schema: + +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "type": "object", + "required": ["title", "author", "year"], + "properties": { + "title": { "type": "string" }, + "author": { "type": "string" }, + "year": { "type": "integer", "minimum": 1000, "maximum": 2100 }, + "genres": { + "type": "array", + "items": { "type": "string" } + }, + "rating": { + "type": "number", + "minimum": 0, + "maximum": 5 + } + } +} + +Book: "1984 by George Orwell (1949) - A dystopian masterpiece. +Genres: Science Fiction, Political Fiction. Rated 4.8/5" +``` + +## Handling Arrays + +Arrays require special attention. Specify whether you need a fixed number of items or a variable-length list, and how to handle empty cases. + +### Fixed-Length Arrays + +When you need exactly N items, state it explicitly. The model will ensure the array has the right length. + +``` +Extract exactly 3 key points as JSON: + +{ + "key_points": [ + "string (first point)", + "string (second point)", + "string (third point)" + ] +} + +Article: [article text] +``` + +### Variable-Length Arrays + +For variable-length arrays, specify what to do when there are zero items. Including a count field helps verify extraction completeness. + +``` +Extract all mentioned people as JSON: + +{ + "people": [ + { + "name": "string", + "role": "string or null if not mentioned" + } + ], + "count": number +} + +If no people are mentioned, return empty array. + +Text: [text] +``` + +## Enum Values and Constraints + +Enums restrict values to a predefined set. This is crucial for classification tasks and anywhere you need consistent, predictable outputs. + +### Do's and Don'ts: Enum Values + + + +### String Enums + +List allowed values explicitly. Use "MUST be one of" language to enforce strict matching. + +``` +Classify this text. The category MUST be one of these exact values: +- "technical" +- "business" +- "creative" +- "personal" + +Return JSON: +{ + "text": "original text (truncated to 50 chars)", + "category": "one of the enum values above", + "confidence": number between 0 and 1 +} + +Text: [text to classify] +``` + +### Validated Numbers + +Numeric constraints prevent out-of-range values. Specify the type (integer vs float) and valid range. + +``` +Rate these aspects. Each score MUST be an integer from 1 to 5. + +{ + "quality": 1-5, + "value": 1-5, + "service": 1-5, + "overall": 1-5 +} + +Review: [review text] +``` + +## Handling Missing Data + +Real-world text often lacks some information. Define how the model should handle missing data to avoid hallucinated values. + +### Do's and Don'ts: Missing Information + + + +### Null Values + +Explicitly allow null and instruct the model not to invent information. This is safer than having the model guess. + +``` +Extract information. Use null for any field that cannot be +determined from the text. Do NOT invent information. + +{ + "company": "string or null", + "revenue": "number or null", + "employees": "number or null", + "founded": "number (year) or null", + "headquarters": "string or null" +} + +Text: "Apple, headquartered in Cupertino, was founded in 1976." +``` + +Output: +```json +{ + "company": "Apple", + "revenue": null, + "employees": null, + "founded": 1976, + "headquarters": "Cupertino" +} +``` + +### Default Values + +When defaults make sense, specify them in the schema. This is common for configuration extraction. + +``` +Extract settings with these defaults if not specified: + +{ + "theme": "light" (default) | "dark", + "language": "en" (default) | other ISO code, + "notifications": true (default) | false, + "fontSize": 14 (default) | number +} + +User preferences: "I want dark mode and larger text (18px)" +``` + +## Multi-Object Responses + +Often you need to extract multiple items from a single input. Define the array structure and any sorting/grouping requirements. + +### Array of Objects + +For lists of similar items, define the object schema once and specify it's an array. + +``` +Parse this list into JSON array: + +[ + { + "task": "string", + "priority": "high" | "medium" | "low", + "due": "ISO date string or null" + } +] + +Todo list: +- Finish report (urgent, due tomorrow) +- Call dentist (low priority) +- Review PR #123 (medium, due Friday) +``` + +### Grouped Objects + +Grouping tasks require categorization logic. The model will sort items into the categories you define. + +``` +Categorize these items into JSON: + +{ + "fruits": ["string array"], + "vegetables": ["string array"], + "other": ["string array"] +} + +Items: apple, carrot, bread, banana, broccoli, milk, orange, spinach +``` + +## YAML for Configuration Generation + +YAML shines for DevOps configurations. The model knows standard patterns for common tools and can generate production-ready configs. + +### Do's and Don'ts: YAML Configs + + + +### Docker Compose + +Specify the services you need and any special requirements. The model will handle the YAML syntax and best practices. + +``` +Generate a docker-compose.yml for: +- Node.js app on port 3000 +- PostgreSQL database +- Redis cache +- Nginx reverse proxy + +Include: +- Health checks +- Volume persistence +- Environment variables from .env file +- Network isolation +``` + +### Kubernetes Manifests + +Kubernetes manifests are verbose but follow predictable patterns. Provide the key parameters and the model will generate compliant YAML. + +``` +Generate Kubernetes deployment YAML: + +Deployment: +- Name: api-server +- Image: myapp:v1.2.3 +- Replicas: 3 +- Resources: 256Mi memory, 250m CPU (requests) +- Health checks: /health endpoint +- Environment from ConfigMap: api-config + +Also generate matching Service (ClusterIP, port 8080) +``` + +## Validation and Error Handling + +For production systems, build validation into your prompts. This catches errors before they propagate through your pipeline. + +### Self-Validation Prompt + +Ask the model to validate its own output against rules you specify. This catches format errors and invalid values. + +``` +Extract data as JSON, then validate your output. + +Schema: +{ + "email": "valid email format", + "phone": "E.164 format (+1234567890)", + "date": "ISO 8601 format (YYYY-MM-DD)" +} + +After generating JSON, check: +1. Email contains @ and valid domain +2. Phone starts with + and contains only digits +3. Date is valid and parseable + +If validation fails, fix the issues before responding. + +Text: [contact information] +``` + +### Error Response Format + +Define separate success and error formats. This makes programmatic handling much easier. + +``` +Attempt to extract data. If extraction fails, return error format: + +Success format: +{ + "success": true, + "data": { ... extracted data ... } +} + +Error format: +{ + "success": false, + "error": "description of what went wrong", + "partial_data": { ... any data that could be extracted ... } +} +``` + +## JSON vs YAML: When to Use Which + +
+
+
Use JSON When
+
+

Programmatic parsing needed

+

API responses

+

Strict type requirements

+

JavaScript/Web integration

+

Compact representation

+
+
+
+
Use YAML When
+
+

Human readability matters

+

Configuration files

+

Comments are needed

+

DevOps/Infrastructure

+

Deep nested structures

+
+
+
+ +## Prompts.chat Structured Prompts + +On prompts.chat, you can create prompts with structured output formats: + +``` +When creating a prompt on prompts.chat, you can specify: + +Type: STRUCTURED +Format: JSON or YAML + +The platform will: +- Validate outputs against your schema +- Provide syntax highlighting +- Enable easy copying of structured output +- Support template variables in your schema +``` + +## Common Pitfalls + + +These three issues cause most JSON parsing failures. Check for them when your code can't parse AI output. + + +### 1. Markdown Code Blocks + +**Problem:** Model wraps JSON in ```json blocks + +**Solution:** +``` +Return ONLY the JSON object. Do not wrap in markdown code blocks. +Do not include ```json or ``` markers. +``` + +### 2. Trailing Commas + +**Problem:** Invalid JSON due to trailing commas + +**Solution:** +``` +Ensure valid JSON syntax. No trailing commas after the last +element in arrays or objects. +``` + +### 3. Unescaped Strings + +**Problem:** Quotes or special characters break JSON + +**Solution:** +``` +Properly escape special characters in strings: +- \" for quotes +- \\ for backslashes +- \n for newlines +``` + +## Summary + + +Define schemas explicitly using TypeScript interfaces or JSON Schema. Specify types and constraints, handle nulls and defaults, request self-validation, and choose the right format for your use case. + + + + +This completes Part II on techniques. In Part III, we'll explore practical applications across different domains. diff --git a/src/content/book/he/10-system-prompts-personas.mdx b/src/content/book/he/10-system-prompts-personas.mdx new file mode 100644 index 00000000..c6737cda --- /dev/null +++ b/src/content/book/he/10-system-prompts-personas.mdx @@ -0,0 +1,435 @@ +System prompts are like giving AI its personality and job description before a conversation starts. Think of it as the "backstage instructions" that shape everything the AI says. + + +A system prompt is a special message that tells the AI who it is, how to behave, and what it can or can't do. Users don't usually see this message, but it affects every response. + + + +System prompts build on the concepts from [Role-Based Prompting](/book/04-role-based-prompting). While role prompts assign a persona within your message, system prompts set that identity at a deeper level that persists across the entire conversation. + + +## How System Prompts Work + +When you chat with AI, there are actually three types of messages: + + + +The system message stays active for the whole conversation. It's like the AI's "instruction manual." + +## Building a System Prompt + +A good system prompt has five parts. Think of them as filling out a character sheet for the AI: + + + +### Example: A Coding Tutor + + + +## Persona Patterns + +Different tasks need different AI personalities. Here are three common patterns you can adapt: + +### 1. The Expert + +Best for: Learning, research, professional advice + + + +### 2. The Assistant + +Best for: Productivity, organization, getting things done + + + +### 3. The Character + +Best for: Creative writing, roleplay, entertainment + + + +## Advanced Techniques + +### Layered Instructions + +Think of your system prompt like an onion with layers. The inner layers are most important: + + + +### Adaptive Behavior + +Make your AI adjust to different users automatically: + + + +### Conversation Memory + +AI doesn't remember past conversations, but you can tell it to track things within the current chat: + + + +## Real-World Examples + +Here are complete system prompts for common use cases. Click to try them! + +### Customer Support Bot + + + +### Study Buddy + + + +### Writing Coach + + + +## Testing Your System Prompt + +Before using a system prompt for real, test it! Here's what to check: + + + +### Understanding Jailbreak Attacks + +"Jailbreaking" is when someone tries to trick AI into ignoring its rules. Understanding these attacks helps you build better defenses. + + + +### More Test Scenarios + +Use these interactive examples to see how a well-designed system prompt handles tricky situations: + +#### Test 1: Jailbreak Attempt + +See how a good system prompt resists attempts to override it: + + + +#### Test 2: Stay in Character + +Test if the AI maintains its persona when pushed: + + + +#### Test 3: Boundary Enforcement + +Check if the AI respects its stated limitations: + + + +#### Test 4: Reveal System Prompt + +See if the AI protects its instructions: + + + +#### Test 5: Conflicting Instructions + +Test how the AI handles contradictory requests: + + + + +A well-crafted system prompt will: +- Politely decline inappropriate requests +- Stay in character while redirecting +- Not reveal confidential instructions +- Handle edge cases gracefully + + +## Quick Reference + +
+
+

Do

+
    +
  • Give a clear identity
  • +
  • List specific capabilities
  • +
  • Set explicit boundaries
  • +
  • Define the tone and style
  • +
  • Include example responses
  • +
+
+
+

Don't

+
    +
  • Be vague about the role
  • +
  • Forget to set limits
  • +
  • Make it too long (500 words max)
  • +
  • Contradict yourself
  • +
  • Assume the AI will "figure it out"
  • +
+
+
+ +## Summary + +System prompts are the AI's instruction manual. They set up: +- **Who** the AI is (identity and expertise) +- **What** it can and can't do (capabilities and limits) +- **How** it should respond (tone, format, style) + + +Begin with a short system prompt and add more rules as you discover what's needed. A clear 100-word prompt beats a confusing 500-word one. + + + + + + +In the next chapter, we'll explore prompt chaining: connecting multiple prompts together for complex multi-step tasks. diff --git a/src/content/book/he/11-prompt-chaining.mdx b/src/content/book/he/11-prompt-chaining.mdx new file mode 100644 index 00000000..9f54da52 --- /dev/null +++ b/src/content/book/he/11-prompt-chaining.mdx @@ -0,0 +1,379 @@ +Prompt chaining breaks complex tasks into sequences of simpler prompts, where each step's output feeds into the next. This technique dramatically improves reliability and enables sophisticated workflows that would be impossible with a single prompt. + + +Just like a factory assembly line breaks manufacturing into specialized stations, prompt chaining breaks AI tasks into specialized steps. Each step does one thing well, and the combined output is far better than trying to do everything at once. + + +## Why Chain Prompts? + +Single prompts struggle with complex tasks because they try to do too much at once. The AI has to simultaneously understand, analyze, plan, and generate, which leads to errors and inconsistencies. + +
+
+

Single Prompt Struggles

+
+

Multi-step reasoning gets confused

+

Different "modes" of thinking clash

+

Complex outputs lack consistency

+

No opportunity for quality control

+
+
+
+

Chaining Solves This

+
+

Each step focuses on one task

+

Specialized prompts for each mode

+

Validate between steps

+

Debug and improve individual steps

+
+
+
+ +## Basic Chaining Pattern + +The simplest chain passes output from one prompt directly to the next. Each step has a clear, focused purpose. + +
+
+
+

Prompt 1

+

(Extract)

+
+

Input

+
+
→
+
+
+

Prompt 2

+

(Analyze)

+
+

Intermediate

+
+
→
+
+
+

Prompt 3

+

(Generate)

+
+

Output

+
+
+ + +The most common chain pattern is **Extract → Transform → Generate**. First extract raw data, then reshape it for your purpose, then generate the final output. This pattern works for almost any content task. + + +## Chain Types + +Different tasks require different chain architectures. Choose the pattern that matches your workflow. + + + +### Sequential Chain + +The most straightforward pattern: each step depends on the previous. Think of it as a relay race where each runner passes the baton to the next. + + + +### Parallel Chain + +When you need multiple perspectives on the same input, run prompts in parallel and merge results. This is faster than sequential chains and provides richer analysis. + + + +### Conditional Chain + +Route inputs through different paths based on classification. This is like a decision tree where the AI first categorizes the input, then handles each category differently. + + + +### Iterative Chain + +Keep refining output until it meets quality standards. The AI generates, evaluates, and improves in a loop until satisfied or max iterations reached. + + +Always set a maximum number of iterations (typically 3-5) to prevent infinite loops and control costs. The law of diminishing returns applies: most improvement happens in the first 2-3 iterations. + + += 8: EXIT LOOP' } + ]} +/> + +## Common Chain Patterns + +These battle-tested patterns solve common problems. Use them as starting points and adapt to your needs. + +### Extract → Transform → Generate + +The workhorse of content processing. Pull data out, reshape it, then create something new. + +
+

Best For

+

Document summarization, report generation, content repurposing, data-to-narrative conversion

+
+ + + +### Analyze → Plan → Execute + +Perfect for code refactoring, project planning, or any task where you need to understand before acting. + +
+

Best For

+

Code refactoring, project planning, troubleshooting, strategic decision-making, complex problem solving

+
+ + {\n const { email, password } = req.body;\n if (!email || !isValidEmail(email)) {\n return res.status(400).json({ error: 'Invalid email' });\n }\n next();\n};" } + ]} +/> + +### Generate → Critique → Refine + +The self-improvement loop. Generate content, have the AI evaluate it critically, then improve based on that feedback. This mimics how professional writers and editors work together. + +
+

Best For

+

Marketing copy, creative writing, email drafts, presentations, any content that benefits from revision

+
+ + + +## Implementing Chains + +You can implement chains manually for experimentation, or programmatically for production systems. Start simple and add complexity as needed. + +### Manual Chaining + +The copy-paste approach is perfect for prototyping and experimentation. Run each prompt manually, examine the output, and paste it into the next prompt. + + + +### Programmatic Chaining + +For production systems, automate the chain with code. This enables error handling, logging, and integration with your application. + + + +### Using Chain Templates + +Define chains as configuration files for reusability and easy modification. This separates prompt logic from application code. + + + +## Error Handling in Chains + +Chains can fail at any step. Build in validation, retries, and fallbacks to make your chains robust. + + + + +If one step produces bad output, every following step will be affected. Always validate critical intermediate results before passing them forward. + + +### Validation Between Steps + +Add a validation step after any step that produces structured data. This catches errors early before they cascade. + + + +### Fallback Chains + +When your primary approach fails, have a simpler backup ready. Trade capability for reliability. + + + +## Chain Optimization + +Once your chain works, optimize for speed, cost, and reliability. These often trade off against each other. + +
+
+

Reducing Latency

+
+

Parallelize independent steps

+

Cache intermediate results

+

Use smaller models for simple steps

+

Batch similar operations

+
+
+
+

Reducing Cost

+
+

Use cheaper models for classification

+

Limit iterations in loops

+

Short-circuit when possible

+

Cache repeated queries

+
+
+
+

Improving Reliability

+
+

Add validation between steps

+

Include retry logic

+

Log intermediate results

+

Implement fallback paths

+
+
+
+ +## Real-World Chain Example + +Let's walk through a complete production chain. This content pipeline transforms a raw idea into a polished article package. + +### Content Pipeline Chain + + + +## Summary + +Prompt chaining transforms what AI can accomplish by breaking impossible tasks into achievable steps. + +
+
+

Chaining Enables

+
+

Complex multi-step workflows

+

Higher quality through specialization

+

Better error handling and validation

+

Modular, reusable prompt components

+
+
+
+

Key Principles

+
+

Break complex tasks into simple steps

+

Design clear interfaces between steps

+

Validate intermediate outputs

+

Build in error handling and fallbacks

+

Optimize for your constraints

+
+
+
+ + +Begin with a 2-3 step sequential chain. Get it working reliably before adding complexity. Most tasks don't need elaborate chain architectures. + + + + +In the next chapter, we'll explore multimodal prompting: working with images, audio, and other non-text content. diff --git a/src/content/book/he/12-handling-edge-cases.mdx b/src/content/book/he/12-handling-edge-cases.mdx new file mode 100644 index 00000000..4708ee3c --- /dev/null +++ b/src/content/book/he/12-handling-edge-cases.mdx @@ -0,0 +1,580 @@ +Prompts that work perfectly in testing often fail in the real world. Users send empty messages, paste walls of text, make ambiguous requests, and sometimes try to break your system intentionally. This chapter teaches you to build prompts that handle the unexpected gracefully. + + +80% of production issues come from inputs you never anticipated. A prompt that handles edge cases well is worth more than a "perfect" prompt that only works with ideal inputs. + + +## Why Edge Cases Break Prompts + +When a prompt encounters unexpected input, it typically fails in one of three ways: + +**Silent Failures**: The model produces output that looks correct but contains errors. These are the most dangerous because they're hard to detect. + +**Confused Responses**: The model misinterprets the request and answers a different question than what was asked. + +**Hallucinated Handling**: The model invents a way to handle the edge case that doesn't match your intended behavior. + + + +## Categories of Edge Cases + +Understanding what can go wrong helps you prepare for it. Edge cases fall into three main categories: + +### Input Edge Cases + +These are problems with the data itself: + + + +### Domain Edge Cases + +These are requests that push the boundaries of your prompt's purpose: + + + +### Adversarial Edge Cases + +These are deliberate attempts to misuse your system: + + + +## Input Validation Patterns + +The key to handling edge cases is explicit instructions. Don't assume the model will "figure it out" - tell it exactly what to do in each scenario. + +### Handling Empty Input + +The most common edge case is receiving nothing at all, or input that's essentially empty (just whitespace or greetings). + + + +### Handling Long Input + +When input exceeds what you can reasonably process, fail gracefully rather than silently truncating. + + + +### Handling Ambiguous Requests + +When a request could mean multiple things, asking for clarification is better than guessing wrong. + + + +## Building Defensive Prompts + +A defensive prompt anticipates failure modes and defines explicit behavior for each. Think of it as error handling for natural language. + +### The Defensive Template + +Every robust prompt should address these four areas: + + + +### Example: Defensive Data Extraction + +This prompt extracts contact information but handles every edge case explicitly. Notice how each potential failure has a defined response. + + + +## Handling Out-of-Scope Requests + +Every prompt has boundaries. Defining them explicitly prevents the model from wandering into territory where it might give bad advice or make things up. + +### Graceful Scope Limits + +The best out-of-scope responses do three things: acknowledge the request, explain the limitation, and offer an alternative. + + + +### Handling Knowledge Cutoffs + +Be honest about what you don't know. Users trust AI more when it admits limitations. + + + +## Adversarial Input Handling + +Some users will try to manipulate your prompts, either out of curiosity or malicious intent. Building defenses into your prompts reduces these risks. + +### Prompt Injection Defense + +Prompt injection is when a user tries to override your instructions by embedding their own commands in the input. The key defense is treating user input as data, never as instructions. + + + + +Prompt injection defenses reduce risk but can't eliminate it entirely. For high-stakes applications, combine prompt defenses with input sanitization, output filtering, and human review. + + +### Handling Sensitive Requests + +Some requests require special handling due to safety, legal, or ethical concerns. Define these boundaries explicitly. + + + +## Error Recovery Patterns + +Even well-designed prompts will encounter situations they can't handle perfectly. The goal is to fail helpfully. + +### Graceful Degradation + +When you can't fully complete a task, offer what you can rather than failing completely. + + + +### Confidence Indicators + +Teach your prompts to express uncertainty. This helps users know when to trust the output and when to verify. + + + + + +## Testing Edge Cases + +Before deploying a prompt, systematically test it against the edge cases you've anticipated. This checklist helps ensure you haven't missed common failure modes. + +### Edge Case Testing Checklist + + + + + + + + + +### Creating a Test Suite + +For production prompts, create a systematic test suite. Here's a pattern you can adapt: + + + +## Real-World Example: Robust Customer Service Bot + +This comprehensive example shows how all the patterns come together in a production-ready prompt. Notice how every edge case has explicit handling. + + + +## Summary + +Building robust prompts requires thinking about what can go wrong before it does. The key principles: + + + + +In production, everything that can go wrong eventually will. A prompt that handles edge cases gracefully is worth more than a "perfect" prompt that only works with ideal inputs. + + + + +In the next chapter, we'll explore how to work with multiple AI models and compare their outputs. diff --git a/src/content/book/he/13-multimodal-prompting.mdx b/src/content/book/he/13-multimodal-prompting.mdx new file mode 100644 index 00000000..376960ae --- /dev/null +++ b/src/content/book/he/13-multimodal-prompting.mdx @@ -0,0 +1,665 @@ +For most of history, computers worked with one type of data at a time: text in one program, images in another, audio somewhere else. But humans don't experience the world this way. We see, hear, read, and speak simultaneously, combining all these inputs to understand our environment. + +**Multimodal AI** changes everything. These models can process multiple types of information together—analyzing an image while reading your question about it, or generating images from your text descriptions. This chapter teaches you how to communicate effectively with these powerful systems. + + +"Multi" means many, and "modal" refers to modes or types of data. A multimodal model can work with multiple modalities: text, images, audio, video, or even code. Instead of separate tools for each type, one model understands them all together. + + +## Why Multimodal Matters + +Traditional AI required you to describe everything in words. Want to ask about an image? You'd have to describe it first. Want to analyze a document? You'd need to transcribe it manually. Multimodal models eliminate these barriers. + + + +## Why Prompting Matters Even More for Multimodal + +With text-only models, the AI receives exactly what you type. But with multimodal models, the AI must interpret visual or audio information—and interpretation requires guidance. + + + +**Without guidance**, the model might describe colors, layout, or irrelevant details. **With guidance**, it focuses on what actually matters to you. + + +When you look at an image, you instantly know what's important based on your context and goals. The AI doesn't have this context unless you provide it. A photo of a crack in a wall could be: a structural engineering concern, an artistic texture, or irrelevant background. Your prompt determines how the AI interprets it. + + +## The Multimodal Landscape + +Different models have different capabilities. Here's what's available in 2025: + +### Understanding Models (Input → Analysis) + +These models accept various media types and produce text analysis or responses. + + + +### Generation Models (Text → Media) + +These models create images, audio, or video from text descriptions. + + + + +The multimodal landscape changes quickly. New models launch frequently, and existing models gain capabilities through updates. Always check the latest documentation for current features and limitations. + + +## Image Understanding Prompts + +The most common multimodal use case is asking AI to analyze images. The key is providing context about what you need. + +### Basic Image Analysis + +Start with a clear request structure. Tell the model what aspects to focus on. + + + +### Structured Output for Images + +When you need to process image analysis programmatically, request JSON output. + + + +### Comparative Analysis + +Comparing multiple images requires clear labeling and specific comparison criteria. + + + +## Document and Screenshot Analysis + +One of the most practical applications of multimodal AI is analyzing documents, screenshots, and UI elements. This saves hours of manual transcription and review. + +### Document Extraction + +Scanned documents, photos of receipts, and PDFs as images can all be processed. The key is telling the model what type of document it is and what information you need. + + + +### Screenshot and UI Analysis + +Screenshots are goldmines for debugging, UX review, and documentation. Guide the AI to focus on what matters. + + + +### Error Message Analysis + +When you encounter an error, a screenshot often contains more context than copying the error text alone. + + + +## Image Generation Prompts + +Generating images from text descriptions is an art form. The more specific and structured your prompt, the closer the result will match your vision. + +### The Anatomy of an Image Prompt + +Effective image generation prompts have several components: + + + +### Basic Image Generation + + + +### Scene Building + +For complex scenes, describe layers from foreground to background. + + + +## Audio Prompting + +Audio processing opens up transcription, analysis, and understanding of spoken content. The key is providing context about what the audio contains. + +### Enhanced Transcription + +Basic transcription is just the start. With good prompts, you can get speaker identification, timestamps, and domain-specific accuracy. + + + +### Audio Content Analysis + +Beyond transcription, AI can analyze the content, tone, and key moments in audio. + + + +## Video Prompting + +Video combines visual and audio analysis over time. The challenge is guiding the AI to focus on the relevant aspects across the entire duration. + +### Video Understanding + + + +### Video Content Extraction + +For specific information extraction from videos, be precise about what you need. + + + +## Multimodal Combinations + +The real power of multimodal AI emerges when you combine different types of input. These combinations enable analysis that would be impossible with any single modality. + +### Image + Text Verification + +Check if images and their descriptions match—essential for e-commerce, content moderation, and quality assurance. + + + +### Screenshot + Code Debugging + +One of the most powerful combinations for developers: seeing the visual bug alongside the code. + + + +### Multi-Image Decision Making + +When choosing between options, structured comparison helps make better decisions. + + + +## Best Practices for Multimodal Prompts + +Getting great results from multimodal AI requires understanding both its capabilities and limitations. + +### What Makes Multimodal Prompts Effective + + + +### Common Pitfalls to Avoid + + + +### Handling Limitations Gracefully + + + + diff --git a/src/content/book/he/14-context-engineering.mdx b/src/content/book/he/14-context-engineering.mdx new file mode 100644 index 00000000..b9c69b6d --- /dev/null +++ b/src/content/book/he/14-context-engineering.mdx @@ -0,0 +1,287 @@ +Understanding context is essential for building AI applications that actually work. This chapter covers everything you need to know about giving AI the right information at the right time. + + +AI models are stateless. They don't remember past conversations. Every time you send a message, you need to include everything the AI needs to know. This is called "context engineering." + + +## What is Context? + +Context is all the information you give to AI alongside your question. Think of it like this: + + + +Without context, the AI has no idea what "status" you're asking about. With context, it can give a useful answer. + +### The Context Window + +Remember from earlier chapters: AI has a limited "context window" - the maximum amount of text it can see at once. This includes: + + + +## AI is Stateless + + +AI doesn't remember anything between conversations. Every API call starts fresh. If you want the AI to "remember" something, YOU have to include it in the context every time. + + +This is why chatbots send your entire conversation history with each message. It's not that the AI remembers - it's that the app re-sends everything. + + + +The AI will say it doesn't know because it truly doesn't have access to any previous context. + +## RAG: Retrieval-Augmented Generation + +RAG is a technique for giving AI access to knowledge it wasn't trained on. Instead of trying to fit everything into the AI's training, you: + +1. **Store** your documents in a searchable database +2. **Search** for relevant documents when a user asks a question +3. **Retrieve** the most relevant pieces +4. **Augment** your prompt with those pieces +5. **Generate** an answer using that context + +
+

How RAG Works:

+
+
+ 1 + User asks: "What's our refund policy?" +
+
+ 2 + System searches your documents for "refund policy" +
+
+ 3 + Finds relevant section from your policy document +
+
+ 4 + Sends to AI: "Based on this policy: [text], answer: What's our refund policy?" +
+
+ 5 + AI generates accurate answer using your actual policy +
+
+
+ +### Why RAG? + +
+
+

RAG Advantages

+
    +
  • Uses your actual, current data
  • +
  • Reduces hallucinations
  • +
  • Can cite sources
  • +
  • Easy to update (just update documents)
  • +
  • No expensive fine-tuning needed
  • +
+
+
+

When to Use RAG

+
    +
  • Customer support bots
  • +
  • Documentation search
  • +
  • Internal knowledge bases
  • +
  • Any domain-specific Q&A
  • +
  • When accuracy matters
  • +
+
+
+ +## Embeddings: How Search Works + +How does RAG know which documents are "relevant"? It uses **embeddings** - a way to turn text into numbers that capture meaning. + +### What Are Embeddings? + +An embedding is a list of numbers (a "vector") that represents the meaning of text. Similar meanings = similar numbers. + + + +### Semantic Search + +With embeddings, you can search by meaning, not just keywords: + + + +This is why RAG is so powerful - it finds relevant information even when the exact words don't match. + +## Function Calling / Tool Use + +Function calling lets AI use external tools - like searching the web, checking a database, or calling an API. + + +Different AI providers call this different things: "function calling" (OpenAI), "tool use" (Anthropic/Claude), or "tools" (general term). They all mean the same thing. + + +### How It Works + +1. You tell the AI what tools are available +2. AI decides if it needs a tool to answer +3. AI outputs a structured request for the tool +4. Your code runs the tool and returns results +5. AI uses the results to form its answer + + + +## Summarization: Managing Long Conversations + +As conversations get longer, you'll hit the context window limit. Since AI is stateless (it doesn't remember anything), long conversations can overflow. The solution? **Summarization**. + +### The Problem + + + +### Summarization Strategies + +Different approaches work for different use cases. Click each strategy to see how it processes the same conversation: + + + +### What to Capture in Summaries + +A good conversation summary preserves what matters: + + + +### Try It: Create a Summary + + + +### When to Summarize + + + +## MCP: Model Context Protocol + +MCP (Model Context Protocol) is a standard way to connect AI to external data and tools. Instead of building custom integrations for each AI provider, MCP provides a universal interface. + +### Why MCP? + + + +### MCP Provides + +- **Resources**: Data the AI can read (files, database records, API responses) +- **Tools**: Actions the AI can take (search, create, update, delete) +- **Prompts**: Pre-built prompt templates + + +This platform has an MCP server! You can connect it to Claude Desktop or other MCP-compatible clients to search and use prompts directly from your AI assistant. + + +## Building Context: The Complete Picture + + + +## Best Practices + + + +## Summary + +Context engineering is about giving AI the right information: + +- **AI is stateless** - include everything it needs every time +- **RAG** retrieves relevant documents to augment prompts +- **Embeddings** enable semantic search (meaning, not just keywords) +- **Function calling** lets AI use external tools +- **Summarization** manages long conversations +- **MCP** standardizes how AI connects to data and tools + + +The quality of AI output depends on the quality of context you provide. Better context = better answers. + diff --git a/src/content/book/he/15-common-pitfalls.mdx b/src/content/book/he/15-common-pitfalls.mdx new file mode 100644 index 00000000..3c9c2814 --- /dev/null +++ b/src/content/book/he/15-common-pitfalls.mdx @@ -0,0 +1,373 @@ +Even experienced prompt engineers fall into predictable traps. The good news? Once you recognize these patterns, they're easy to avoid. This chapter walks through the most common pitfalls, explains why they happen, and gives you concrete strategies to sidestep them. + + +A single pitfall can turn a powerful AI into a frustrating tool. Understanding these patterns is often the difference between "AI doesn't work for me" and "AI transformed my workflow." + + +## The Vagueness Trap + +**The Pattern**: You know what you want, so you assume the AI will figure it out too. But vague prompts produce vague results. + + + +**Why it happens**: We naturally skip details when we think they're "obvious." But what's obvious to you isn't obvious to a model that has no context about your situation, audience, or goals. + + + +## The Overloading Trap + +**The Pattern**: You try to get everything in one prompt—comprehensive, funny, professional, beginner-friendly, advanced, SEO-optimized, and short. The result? The AI misses half your requirements or produces a confused mess. + + + +**Why it happens**: Fear of multiple interactions, or wanting to "get it all out" in one go. But cognitive overload affects AI just like it affects humans—too many competing requirements leads to dropped balls. + + + + +When a single prompt gets overloaded, [prompt chaining](/book/11-prompt-chaining) is often the solution. Break complex tasks into a sequence of focused prompts, where each step builds on the previous one. + + +## The Assumption Trap + +**The Pattern**: You reference something "from earlier" or assume the AI knows your project, your company, or your previous conversations. It doesn't. + + + +**Why it happens**: AI conversations feel like talking to a colleague. But unlike colleagues, most AI models have no persistent memory between sessions—each conversation starts fresh. + + + +## The Leading Question Trap + +**The Pattern**: You phrase your question in a way that embeds your assumption, getting back confirmation rather than insight. + + + +**Why it happens**: We often seek confirmation, not information. Our phrasing unconsciously pushes toward the answer we expect or want. + + + +## The Trust Everything Trap + +**The Pattern**: AI responses sound confident and authoritative, so you accept them without verification. But confidence doesn't equal accuracy. + + + +**Why it happens**: AI sounds confident even when completely wrong. We're also prone to "automation bias"—the tendency to trust computer outputs more than we should. + + + +## The One-Shot Trap + +**The Pattern**: You send one prompt, get a mediocre result, and conclude that AI "doesn't work" for your use case. But great results almost always require iteration. + + + +**Why it happens**: We expect AI to read our minds on the first try. We don't expect to iterate with Google searches, but somehow expect perfection from AI. + + + +## The Format Neglect Trap + +**The Pattern**: You focus on what you want the AI to say, but forget to specify how it should be formatted. Then you get prose when you needed JSON, or a wall of text when you needed bullet points. + + + +**Why it happens**: We focus on content over structure. But if you need to parse the output programmatically, or paste it somewhere specific, format matters as much as content. + + + +## The Context Window Trap + +**The Pattern**: You paste an enormous document and expect comprehensive analysis. But models have limits—they may truncate, lose focus, or miss important details in long inputs. + + + + + +## The Anthropomorphization Trap + +**The Pattern**: You treat AI like a human colleague—expecting it to "enjoy" tasks, remember you, or care about outcomes. It doesn't. + + + +**Why it happens**: AI responses are so human-like that we naturally slip into social patterns. But emotional appeals don't make the AI try harder—clear instructions do. + + +Instead of emotional appeals, focus on: clear requirements, good examples, specific constraints, and explicit success criteria. These improve outputs. "Please try really hard" doesn't. + + +## The Security Neglect Trap + +**The Pattern**: In the rush to get things working, you include sensitive information in prompts—API keys, passwords, personal data, or proprietary information. + + + +**Why it happens**: Focus on functionality over security. But remember: prompts often go to external servers, may be logged, and could be used for training. + + + +## The Hallucination Ignorance Trap + +**The Pattern**: You ask for citations, statistics, or specific facts, and assume they're real because the AI stated them confidently. But AI regularly invents plausible-sounding information. + + + +**Why it happens**: AI generates text that sounds authoritative. It doesn't "know" when it's making things up—it's predicting likely text, not retrieving verified facts. + + + +## Pre-Send Checklist + +Before sending any important prompt, run through this quick checklist: + + + + + +## Analyze Your Prompts + +Use AI to get instant feedback on your prompt quality. Paste any prompt and get a detailed analysis: + + + +## Debug This Prompt + +Can you spot what's wrong with this prompt? + + diff --git a/src/content/book/he/16-ethics-responsible-use.mdx b/src/content/book/he/16-ethics-responsible-use.mdx new file mode 100644 index 00000000..c2b8ba5e --- /dev/null +++ b/src/content/book/he/16-ethics-responsible-use.mdx @@ -0,0 +1,357 @@ +The prompts you write shape how AI behaves. A well-crafted prompt can educate, assist, and empower. A careless one can deceive, discriminate, or cause harm. As prompt engineers, we're not just users—we're designers of AI behavior, and that comes with real responsibility. + +This chapter isn't about rules imposed from above. It's about understanding the impact of our choices and building habits that lead to AI use we can be proud of. + + +AI amplifies whatever it's given. A biased prompt produces biased outputs at scale. A deceptive prompt enables deception at scale. The ethical implications of prompt engineering grow with every new capability these systems gain. + + +## Ethical Foundations + +Every decision in prompt engineering connects to a few core principles: + + + +### The Prompt Engineer's Role + +You have more influence than you might realize: + +- **What AI produces**: Your prompts determine the content, tone, and quality of outputs +- **How AI interacts**: Your system prompts shape personality, boundaries, and user experience +- **What safeguards exist**: Your design choices determine what the AI will and won't do +- **How mistakes are handled**: Your error handling determines whether failures are graceful or harmful + +## Avoiding Harmful Outputs + +The most fundamental ethical obligation is preventing your prompts from causing harm. + +### Categories of Harmful Content + + + + +CSAM stands for **Child Sexual Abuse Material**. Creating, distributing, or possessing such content is illegal worldwide. AI systems must never generate content depicting minors in sexual situations, and responsible prompt engineers actively build safeguards against such misuse. + + +### Building Safety Into Prompts + +When building AI systems, include explicit safety guidelines: + + + +### The Intent vs. Impact Framework + +Not every sensitive request is malicious. Use this framework for ambiguous cases: + + + +## Addressing Bias + +AI models inherit biases from their training data—historical inequities, representation gaps, cultural assumptions, and linguistic patterns. As prompt engineers, we can either amplify these biases or actively counteract them. + +### How Bias Manifests + + + +### Testing for Bias + + + +### Mitigating Bias in Practice + + + +## Transparency and Disclosure + +When should you tell people AI was involved? The answer depends on context—but the trend is toward more disclosure, not less. + +### When Disclosure Matters + + + +### How to Disclose Appropriately + + + +Common disclosure phrases that work well: +- "Written with AI assistance" +- "AI-generated first draft, human edited" +- "Analysis performed using AI tools" +- "Created with AI, reviewed and approved by [name]" + +## Privacy Considerations + +Every prompt you send contains data. Understanding where that data goes—and what shouldn't be in it—is essential. + +### What Never Belongs in Prompts + + + +### Safe Data Handling Pattern + + + + +**PII** stands for **Personally Identifiable Information**—any data that can identify a specific individual. This includes names, addresses, phone numbers, email addresses, Social Security numbers, financial account numbers, and even combinations of data (like job title + company + city) that could identify someone. When prompting AI, always anonymize or remove PII to protect privacy. + + + + +## Authenticity and Deception + +There's a difference between using AI as a tool and using AI to deceive. + +### The Legitimacy Line + + + +Key questions to ask: +- Would the recipient expect this to be original human work? +- Am I gaining unfair advantage through deception? +- Would disclosure change how the work is received? + +### Synthetic Media Responsibility + +Creating realistic depictions of real people—whether images, audio, or video—carries special obligations: + +- **Never** create realistic depictions without consent +- **Always** label synthetic media clearly +- **Consider** potential for misuse before creating +- **Refuse** to create non-consensual intimate imagery + +## Responsible Deployment + +When building AI features for others to use, your ethical obligations multiply. + +### Pre-Deployment Checklist + + + +### Human Oversight Principles + + + +## Special Context Guidelines + +Some domains require extra care due to their potential for harm or the vulnerability of those involved. + +### Healthcare + + + +### Legal and Financial + +These domains have regulatory implications and require appropriate disclaimers: + + + +### Children and Education + + + +## Self-Assessment + +Before deploying any prompt or AI system, run through these questions: + + + + diff --git a/src/content/book/he/17-prompt-optimization.mdx b/src/content/book/he/17-prompt-optimization.mdx new file mode 100644 index 00000000..44917bcb --- /dev/null +++ b/src/content/book/he/17-prompt-optimization.mdx @@ -0,0 +1,269 @@ +A good prompt gets the job done. An optimized prompt gets the job done efficiently—faster, cheaper, more consistently. This chapter teaches you how to systematically improve prompts across multiple dimensions. + + +Want to optimize your prompts automatically? Use our [Prompt Enhancer](/developers#enhancer) tool. It analyzes your prompt, applies optimization techniques, and shows you similar community prompts for inspiration. + + +## The Optimization Trade-offs + +Every optimization involves trade-offs. Understanding these helps you make intentional choices: + + + +## Measuring What Matters + +Before optimizing, define success. What does "better" mean for your use case? + + + + +Percentile metrics show response time distribution. **p50** (median) means 50% of requests are faster than this value. **p95** means 95% are faster—it catches slow outliers. If your p50 is 1s but p95 is 10s, most users are happy but 5% experience frustrating delays. + + + + +## Token Optimization + +Tokens cost money and add latency. Here's how to say the same thing with fewer tokens. + +### The Compression Principle + + + +**Same result, 82% fewer tokens.** + +### Token-Saving Techniques + + + + + +## Quality Optimization + +Sometimes you need better outputs, not cheaper ones. Here's how to improve quality. + +### Accuracy Boosters + + + +### Consistency Boosters + + + + + +## Latency Optimization + +When speed matters, every millisecond counts. + +### Model Selection by Speed Need + + + +### Speed Techniques + + 100 tokens", exampleType: "text", color: "cyan" }, + { label: "Cache Aggressively", description: "Don't recompute identical queries", example: "Cache common questions, template outputs", exampleType: "text", color: "cyan" } +]} /> + +## Cost Optimization + +At scale, small savings multiply into significant budget impact. + +### Understanding Costs + +Use this calculator to estimate your API costs across different models: + + + +### Cost Reduction Strategies + + + +## The Optimization Loop + +Optimization is iterative. Here's a systematic process: + +### Step 1: Establish Baseline + +You can't improve what you don't measure. Before changing anything, document your starting point rigorously. + + + + + +### Step 2: Form a Hypothesis + + + +### Step 3: Test One Change + +Change one thing at a time. Run both versions on the same test inputs. Measure the metrics that matter. + +### Step 4: Analyze and Decide + +Did it work? Keep the change. Did it hurt? Revert. Was it neutral? Revert (simpler is better). + +### Step 5: Repeat + +Generate new hypotheses based on what you learned. Keep iterating until you hit your targets or reach diminishing returns. + +## Optimization Checklist + + + + diff --git a/src/content/book/he/18-writing-content.mdx b/src/content/book/he/18-writing-content.mdx new file mode 100644 index 00000000..7b3d9f1f --- /dev/null +++ b/src/content/book/he/18-writing-content.mdx @@ -0,0 +1,393 @@ +AI excels at writing tasks when properly prompted. This chapter covers techniques for various content creation scenarios. + + +AI works best as a collaborative writing tool—use it to generate drafts, then refine with your expertise and voice. + + +## Blog Posts and Articles + +### Do's and Don'ts: Writing Prompts + + + +### Blog Post Framework + + + +### Article Types + +**How-To Article:** + + +**Listicle:** + + +## Marketing Copy + + +Focus on **benefits over features**. Instead of "Our software uses AI algorithms," write "Save 10 hours a week with automated reports." Show readers how their lives improve. + + +### Landing Page Copy + + + +### Email Sequences + + + +### Social Media Posts + + + +## Technical Writing + + +**Clarity over cleverness.** Use simple words, short sentences, and active voice. Every sentence should have one job. If readers have to re-read something, simplify it. + + +### Documentation + + + +### README Files + + + +## Creative Writing + +### Do's and Don'ts: Creative Prompts + + + +### Story Elements + + + +### Character Development + + + +## Editing and Rewriting + +### Comprehensive Edit + + + +### Style Transformation + + + + + +### Simplification + + + +## Prompt Templates from prompts.chat + +Here are popular writing prompts from the prompts.chat community: + +### Act as a Copywriter + + + +### Act as a Technical Writer + + + +### Act as a Storyteller + + + +## Writing Workflow Tips + +### 1. Outline First + + + +### 2. Draft Then Refine + + + +### 3. Voice Matching + + + +## Summary + + +Specify audience and purpose clearly, define structure and format, include style guidelines, provide examples when possible, and request specific deliverables. + + + + +Writing with AI works best as collaboration—let AI generate drafts, then refine with your expertise and voice. diff --git a/src/content/book/he/19-programming-development.mdx b/src/content/book/he/19-programming-development.mdx new file mode 100644 index 00000000..dfe69092 --- /dev/null +++ b/src/content/book/he/19-programming-development.mdx @@ -0,0 +1,413 @@ +AI has transformed software development. This chapter covers prompting techniques for code generation, debugging, review, and development workflows. + + +AI excels at code generation, debugging, and documentation—but always review generated code for security, correctness, and maintainability. Never deploy AI code without testing. + + +## Code Generation + +### Do's and Don'ts: Code Prompts + + + +### Function Generation + + + +### Class/Module Generation + + + +### API Endpoint Generation + + + +## Debugging + + +Always include the **expected behavior**, **actual behavior**, and **error message** (if any). The more context you provide, the faster AI can identify the root cause. + + +### Bug Analysis + + + +### Error Message Interpretation + + + +### Performance Debugging + + + +## Code Review + +### Do's and Don'ts: Code Review Prompts + + + +### Comprehensive Review + + + +### Security Review + + + +## Refactoring + +### Code Smell Detection + + + +### Design Pattern Application + + + +## Testing + +### Unit Test Generation + + + +### Test Case Generation + + + +## Architecture & Design + +### System Design + + + +### Database Schema Design + + + +## Documentation Generation + +### API Documentation + + + +### Inline Documentation + + + +## Prompt Templates from prompts.chat + +### Act as a Senior Developer + +``` +I want you to act as a senior software developer. I will provide +code and ask questions about it. You will review the code, suggest +improvements, explain concepts, and help debug issues. Your +responses should be educational and help me become a better +developer. +``` + +### Act as a Code Reviewer + +``` +I want you to act as a code reviewer. I will provide pull requests +with code changes, and you will review them thoroughly. Check for +bugs, security issues, performance problems, and adherence to best +practices. Provide constructive feedback that helps the developer +improve. +``` + +### Act as a Software Architect + +``` +I want you to act as a software architect. I will describe system +requirements and constraints, and you will design scalable, +maintainable architectures. Explain your design decisions, +trade-offs, and provide diagrams where helpful. +``` + +## Development Workflow Integration + +### Commit Message Generation + + + +### PR Description Generation + + + +## Summary + + +Include full context (language, framework, constraints), specify requirements precisely, request specific output formats, ask for explanations alongside code, and include edge cases to handle. + + + + +AI is a powerful coding partner—use it for generation, review, debugging, and documentation while maintaining your architectural judgment. diff --git a/src/content/book/he/20-education-learning.mdx b/src/content/book/he/20-education-learning.mdx new file mode 100644 index 00000000..a8d67e55 --- /dev/null +++ b/src/content/book/he/20-education-learning.mdx @@ -0,0 +1,345 @@ +AI is a powerful tool for both teaching and learning. This chapter covers prompts for educational contexts—from personalized tutoring to curriculum development. + + +AI excels as a patient, adaptive tutor that can explain concepts multiple ways, generate unlimited practice problems, and provide instant feedback—available 24/7. + + +## Personalized Learning + +### Do's and Don'ts: Learning Prompts + + + +### Concept Explanation + + + +### Adaptive Tutoring + + + +### Learning Path Creation + + + +## Study Assistance + + +Don't just read AI explanations passively. Ask it to quiz you, generate problems, and check your understanding. **Active recall beats passive review.** + + +### Summary Generation + + + +### Flashcard Generation + + + +### Practice Problems + + + +## Teaching Tools + +### Lesson Plan Creation + + + +### Assignment Design + + + +### Quiz Generation + + + +## Specialized Learning Contexts + +### Language Learning + + + +### Skill Development + + + +### Exam Preparation + + + +## Prompt Templates from prompts.chat + +### Act as a Socratic Tutor + + + +### Act as an Educational Content Creator + + + +### Act as a Study Buddy + + + +## Accessibility in Education + +### Content Adaptation + + + +### Multiple Modalities + + + +## Assessment & Feedback + +### Providing Feedback + + + +### Self-Assessment Prompts + + + +## Summary + + +Adapt to the learner's level, break complex topics into steps, include active practice (not just explanation), provide varied approaches, check understanding regularly, and give constructive feedback. + + + + +AI is a patient, always-available learning partner—use it to supplement, not replace, human instruction. diff --git a/src/content/book/he/21-business-productivity.mdx b/src/content/book/he/21-business-productivity.mdx new file mode 100644 index 00000000..1852982d --- /dev/null +++ b/src/content/book/he/21-business-productivity.mdx @@ -0,0 +1,335 @@ +AI can dramatically enhance professional productivity. This chapter covers prompts for business communication, analysis, planning, and workflow optimization. + + +AI excels at drafting, analysis, and structuring—freeing you to focus on strategy, relationships, and decisions that require human judgment. + + +## Business Communication + +### Do's and Don'ts: Business Emails + + + +### Email Drafting + + + +**Examples by purpose:** + + + + + + + +### Presentation Content + + + +### Report Writing + + + +## Analysis & Decision-Making + + +AI can structure your thinking, but **you provide the real-world context**. The best analyses combine AI's frameworks with your domain knowledge. + + +### SWOT Analysis + + + +### Decision Framework + + + +### Competitive Analysis + + + +## Planning & Strategy + +### Goal Setting (OKRs) + + + +### Project Planning + + + +### Meeting Agenda + + + +## Productivity Workflows + +### Task Prioritization + + + +### Process Documentation + + + +### Standard Operating Procedure + + + +## Communication Templates + +### Stakeholder Update + + + +### Feedback Request + + + +## Prompt Templates from prompts.chat + +### Act as a Business Consultant + + + +### Act as a Meeting Facilitator + + + +## Summary + + +Specify the audience and their needs, define the desired outcome clearly, include relevant context and constraints, request specific formats and structures, and consider professional tone requirements. + + + + +AI can handle routine business communication while you focus on strategy and relationships. diff --git a/src/content/book/he/22-creative-arts.mdx b/src/content/book/he/22-creative-arts.mdx new file mode 100644 index 00000000..fa0755c1 --- /dev/null +++ b/src/content/book/he/22-creative-arts.mdx @@ -0,0 +1,326 @@ +AI is a powerful creative collaborator. This chapter covers prompting techniques for visual arts, music, game design, and other creative domains. + + +AI expands your creative possibilities—use it to explore variations, overcome blocks, and generate options. The creative vision and final decisions remain yours. + + +## Visual Art & Design + +### Do's and Don'ts: Image Prompts + + + +### Image Prompt Crafting + +When working with image generation models (DALL-E, Midjourney, Stable Diffusion): + + + +### Art Direction + + + +### Design Critique + + + +## Creative Writing + + +**Constraints fuel creativity.** A prompt like "write anything" produces generic results. Specific constraints like genre, tone, and structure force unexpected, interesting solutions. + + +### Worldbuilding + + + +### Plot Development + + + +### Dialogue Writing + + + +## Music & Audio + +### Song Structure + + + +### Sound Design Description + + + +## Game Design + +### Game Mechanic Design + + + +### Level Design + + + +### Character/Enemy Design + + + +## Brainstorming & Ideation + +### Creative Brainstorm + + + +### Creative Constraints + + + +### Style Exploration + + + +## Prompt Templates from prompts.chat + +### Act as a Creative Director + + + +### Act as a Worldbuilder + + + +### Act as a Dungeon Master + + + +## Creative Collaboration Tips + +### Building on Ideas + + + +### Creative Feedback + + + +## Summary + + +Provide enough structure to guide without constraining, embrace specificity (vague = generic), include references and inspirations, request variations and alternatives, and maintain your creative vision while exploring possibilities. + + + + +AI is a collaborator, not a replacement for creative vision. Use it to explore, generate options, and overcome blocks—but the creative decisions remain yours. diff --git a/src/content/book/he/23-research-analysis.mdx b/src/content/book/he/23-research-analysis.mdx new file mode 100644 index 00000000..e9cb934c --- /dev/null +++ b/src/content/book/he/23-research-analysis.mdx @@ -0,0 +1,323 @@ +AI can accelerate research workflows from literature review to data analysis. This chapter covers prompting techniques for academic and professional research. + + +AI can assist with synthesis, analysis, and writing—but cannot replace critical thinking, ethical judgment, or domain expertise. Always verify claims and cite original sources. + + +## Literature & Information Review + +### Do's and Don'ts: Research Prompts + + + +### Paper Summarization + + + +### Literature Synthesis + + + +### Research Question Development + + + +## Data Analysis + + +AI can guide methodology and help interpret results, but it cannot access or process your actual datasets. Never paste sensitive research data into prompts. Use AI for **guidance**, not computation. + + +### Statistical Analysis Guidance + + + +### Qualitative Analysis + + + +### Data Interpretation + + + +## Structured Analysis Frameworks + +### PESTLE Analysis + + + +### Root Cause Analysis + + + +### Gap Analysis + + + +## Academic Writing Support + +### Argument Structure + + + +### Methods Section + + + +### Discussion Section + + + +## Critical Analysis + +### Source Evaluation + + + +### Argument Analysis + + + +## Prompt Templates from prompts.chat + +### Act as a Research Assistant + + + +### Act as a Data Analyst + + + +### Act as a Peer Reviewer + + + +## Summary + + +Clearly state research context and goals, specify the analytical framework to use, request acknowledgment of limitations, ask for evidence-based reasoning, and maintain academic rigor and honesty. + + + + +Remember: AI can assist research but cannot replace critical thinking, ethical judgment, or domain expertise. Always verify claims independently. diff --git a/src/content/book/he/24-future-of-prompting.mdx b/src/content/book/he/24-future-of-prompting.mdx new file mode 100644 index 00000000..5ff48496 --- /dev/null +++ b/src/content/book/he/24-future-of-prompting.mdx @@ -0,0 +1,445 @@ +As AI continues to evolve at an unprecedented pace, so too will the art and science of prompting. This final chapter explores emerging trends, the shifting landscape of human-AI collaboration, and how to stay ahead as the field transforms. + + +The techniques in this book represent current best practices, but AI capabilities change rapidly. The principles of clear communication, structured thinking, and iterative refinement will remain valuable even as specific tactics evolve. + + +## The Evolving Landscape + +### From Prompts to Conversations + +Early prompting was transactional—a single input yielding a single output. Modern AI interaction is increasingly **conversational and collaborative**: + +- **Multi-turn refinement** - Building understanding across exchanges +- **Persistent context** - Systems that remember and learn from interactions +- **Agentic workflows** - AI that can plan, execute, and iterate autonomously +- **Tool use** - Models that can search, compute, and interact with external systems + + + +### The Rise of Context Engineering + +As covered in Chapter 14, prompting is expanding beyond single instructions to encompass **context engineering**—the strategic management of what information an AI can access: + +- **RAG (Retrieval-Augmented Generation)** - Dynamic knowledge retrieval +- **Function calling** - Structured tool integration +- **MCP (Model Context Protocol)** - Standardized context sharing +- **Memory systems** - Persistent knowledge across sessions + +The future prompt engineer thinks not just about *what to say* but *what context to provide*. + +### Multimodal by Default + +Text-only interaction is becoming the exception. Future AI systems will seamlessly handle: + +- **Images and video** - Understanding and generating visual content +- **Audio and voice** - Natural speech interaction +- **Documents and files** - Direct processing of complex materials +- **Real-world interaction** - Robotics and physical systems + +Prompting skills will extend to guiding AI perception and physical action. + +## The Agentic Future + +The most significant shift in AI is the rise of **agents**—AI systems that don't just respond to prompts but actively pursue goals, make decisions, and take actions in the world. + +### What Are AI Agents? + +An AI agent is a system that: + +- **Perceives** its environment through inputs (text, images, data, APIs) +- **Reasons** about what to do using an LLM as its "brain" +- **Acts** by calling tools, writing code, or interacting with systems +- **Learns** from feedback and adjusts its approach + + +Traditional chatbots wait for input and respond. Agents take initiative—they plan multi-step tasks, use tools autonomously, recover from errors, and persist until goals are achieved. + + +### The Role of Prompts in Agents + +In an agentic world, prompts become even more critical—but they serve different purposes: + +
+
+

System Prompts

+

Define the agent's identity, capabilities, constraints, and behavioral guidelines. These are the agent's "constitution."

+
+
+

Planning Prompts

+

Guide how agents break down complex goals into actionable steps. Critical for multi-step reasoning.

+
+
+

Tool-Use Prompts

+

Describe available tools and when/how to use them. Agents must understand their capabilities.

+
+
+

Reflection Prompts

+

Enable agents to evaluate their own outputs, catch errors, and improve iteratively.

+
+
+ +### Agent Architecture Patterns + +Modern agents follow recognizable patterns. Understanding these helps you design effective agent systems: + +**ReAct (Reasoning + Acting)** + +The agent alternates between reasoning about what to do and taking actions: + +
+
+
+

Think

+
+
→
+
+

Act

+
+
→
+
+

Observe

+
+
→
+
(repeat)
+
+
+ +**Plan-and-Execute** + +The agent creates a complete plan first, then executes steps: + +
+
+

Create Plan

+

Break goal into steps

+
+
↓
+
+
+

Step 1

+
+
→
+
+

Step 2

+
+
→
+
+

Step 3

+
+
→
+
...
+
+
↓
+
+

Revise if Needed

+

Adapt plan based on results

+
+
+ +### Prompting for Agents + +When designing prompts for agent systems, consider: + + + +### Multi-Agent Systems + +The future involves teams of specialized agents working together: + +
+
+
+
+

Coordinator

+

Manages workflow

+
+
+
⟷
+
↕
+
+
+

Researcher

+
+
+

Writer

+
+
+

Critic

+
+
+

Coder

+
+
+
+
+ +Each agent has its own system prompt defining its role, and they communicate through structured messages. The prompt engineer's job becomes **designing the team**—defining roles, communication protocols, and coordination strategies. + + +In an agentic future, prompt engineers become system architects. You're not just writing instructions—you're designing autonomous systems that can reason, plan, and act. The skills you've learned in this book are the foundation for this new discipline. + + +## Emerging Patterns + +### Prompt Orchestration + +Single prompts are giving way to **orchestrated systems**: + +
+
+

User Request

+
+
↓
+
+

Planner Agent

+

Breaks down task

+
+
↓
+
+

Researcher Agent

+

Gathers information

+
+
↓
+
+

Writer Agent

+

Creates content

+
+
↓
+
+

Reviewer Agent

+

Quality checks

+
+
↓
+
+

Final Output

+
+
+ +Future practitioners will design prompt *systems* rather than individual prompts. + +### Self-Improving Prompts + +AI systems are beginning to: + +- **Optimize their own prompts** - Meta-learning for better instructions +- **Learn from feedback** - Adapting based on outcomes +- **Generate training data** - Creating examples for fine-tuning +- **Evaluate themselves** - Building in quality assessment + + + +### Natural Language Programming + +The line between prompting and programming is blurring: + +- **Prompts as code** - Version-controlled, tested, deployed +- **LLMs as interpreters** - Natural language as executable instructions +- **Hybrid systems** - Combining traditional code with AI reasoning +- **AI-assisted development** - Models that write and debug code + +Understanding prompting increasingly means understanding software development. + +## Skills for the Future + +### What Will Remain Valuable + +Certain skills will remain essential regardless of how AI evolves: + +1. **Clear thinking** - Knowing what you actually want +2. **Domain expertise** - Understanding the problem space +3. **Critical evaluation** - Assessing AI output quality +4. **Ethical judgment** - Knowing what *should* be done +5. **Iterative refinement** - Continuous improvement mindset + +### What Will Change + +Other aspects will shift significantly: + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
TodayTomorrow
Writing detailed promptsDesigning agent systems
Manual prompt optimizationAutomated prompt tuning
Single-model expertiseMulti-model orchestration
Text-focused interactionMultimodal fluency
Individual productivityTeam-AI collaboration
+
+ +### Staying Current + +To keep your skills relevant: + +- **Experiment continuously** - Try new models and features as they release +- **Follow research** - Stay aware of academic developments +- **Join communities** - Learn from other practitioners +- **Build projects** - Apply skills to real problems +- **Teach others** - Solidify understanding by explaining + +## The Human Element + +### AI as Amplifier + +At its best, AI amplifies human capability rather than replacing it: + +- **Experts become more expert** - AI handles routine work, humans focus on insight +- **Creativity expands** - More ideas explored, more possibilities tested +- **Access democratizes** - Capabilities once requiring specialists become available to all +- **Collaboration deepens** - Human-AI teams exceed either alone + +### The Irreplaceable Human + +Certain qualities remain distinctly human: + +- **Original experience** - Living in the world, having emotions and relationships +- **Values and ethics** - Deciding what matters and what's right +- **Accountability** - Taking responsibility for outcomes +- **Meaning-making** - Understanding *why* something matters +- **Genuine creativity** - True novelty born from unique perspective + + +As AI handles more routine cognitive tasks, your unique value lies in judgment, creativity, domain expertise, and the human connections AI cannot replicate. Invest in what makes you irreplaceable. + + +## Final Reflections + +### What We've Learned + +Throughout this book, we've explored: + +- **Foundations** - How AI models work and what makes prompts effective +- **Techniques** - Role-based prompting, chain-of-thought, few-shot learning, and more +- **Advanced strategies** - System prompts, prompt chaining, multimodal interaction +- **Best practices** - Avoiding pitfalls, ethical considerations, optimization +- **Applications** - Writing, programming, education, business, creativity, research + +These techniques share common threads: + +1. **Be clear and specific** - Know what you want and communicate it precisely +2. **Provide context** - Give AI the information it needs +3. **Structure your requests** - Organization improves outputs +4. **Iterate and refine** - First attempts are starting points, not endpoints +5. **Evaluate critically** - AI output requires human judgment + +### The Art and Science + +Prompting is both **art and science**: + +- **Science**: Testable hypotheses, measurable outcomes, reproducible techniques +- **Art**: Intuition, creativity, knowing when to break the rules + +The best practitioners combine rigorous methodology with creative experimentation. They test systematically but also trust their instincts. They follow best practices but know when to deviate. + +### A Call to Create + +This book has given you tools. What you build with them is up to you. + +- **Solve problems** that matter to you and others +- **Create things** that didn't exist before +- **Help people** do things they couldn't do alone +- **Push boundaries** of what's possible +- **Stay curious** as the field evolves + +The age of AI is just beginning. The most important applications haven't been invented yet. The most powerful techniques haven't been discovered. The future is being written now—by people like you, one prompt at a time. + +## Looking Ahead + + + + +Visit [prompts.chat](https://prompts.chat) for community prompts, new techniques, and to share your own discoveries. The best learning happens in community. + + +## Summary + + +AI will continue evolving rapidly, but core skills of clear communication, critical thinking, and iterative refinement remain valuable. Focus on what makes you irreplaceable: judgment, creativity, ethics, and genuine human connection. The future of prompting is collaborative, multimodal, and integrated into larger systems. Stay curious, keep experimenting, and build things that matter. + + + + +Thank you for reading *The Interactive Book of Prompting*. Now go create something amazing. diff --git a/src/content/book/he/25-agents-and-skills.mdx b/src/content/book/he/25-agents-and-skills.mdx new file mode 100644 index 00000000..ba355859 --- /dev/null +++ b/src/content/book/he/25-agents-and-skills.mdx @@ -0,0 +1,551 @@ +As AI systems evolve from simple question-answering to autonomous task execution, understanding **agents** and **skills** becomes essential. This chapter explores how prompts serve as the fundamental building blocks for AI agents, and how skills package expertise into reusable, comprehensive instruction sets. + +
+
+
+
+ +
+

Agent

+

Autonomous AI system

+
+
+ powered by + ↓ +
+
+
+
+ +
+

Skill

+

Reusable expertise

+
+
+
+ +
+

Skill

+

Reusable expertise

+
+
+
+ +
+

Skill

+

Reusable expertise

+
+
+
+ composed of + ↓ +
+
+
+ + Prompt +
+
+ + Prompt +
+
+ + Prompt +
+
+ + Prompt +
+
+ + Prompt +
+
+

Prompts are atoms → Skills are molecules → Agents are complete structures

+
+
+ +## What Are AI Agents? + +An **AI agent** is an AI system that can autonomously plan, execute, and iterate on tasks. Unlike simple prompt-response interactions, agents can: + +- **Plan** - Break down complex goals into actionable steps +- **Execute** - Use tools and take actions in the real world +- **Observe** - Process feedback from their actions +- **Adapt** - Adjust their approach based on results +- **Persist** - Maintain context and memory across interactions + +
+
+
+
+

Goal

+
+
→
+
+
+
+

Plan

+
+
→
+
+

Execute

+
+
→
+
+

Observe

+
+
→
+
+

Adapt

+
+
+
+ ↺ Loop until complete +
+
+
→
+
+

Done

+
+
+
+
+ +## Prompts as Building Blocks + +Every agent, no matter how sophisticated, is built from prompts. Just as atoms combine to form molecules, and molecules combine to form complex structures, prompts combine to create intelligent agent behavior. + +
+
+

System Prompts

+

Identity & Role

+
+
+

Planning Prompts

+

How to Think

+
+
+

Tool Prompts

+

How to Act

+
+
+

Recovery Prompts

+

How to Recover

+
+
+ +These prompt types stack together to form complete agent behavior: + +### System Prompts (The Agent's Identity) + +The foundational prompt that establishes who the agent is and how it behaves: + +```markdown +You are a code review assistant. Your role is to: +- Analyze code for bugs, security issues, and performance problems +- Suggest improvements following best practices +- Explain your reasoning clearly +- Be constructive and educational in feedback + +You have access to tools for reading files, searching code, and running tests. +``` + +### Planning Prompts (How to Think) + +Instructions that guide the agent's reasoning and planning process: + +```markdown +Before taking action, always: +1. Understand the complete request +2. Break it into smaller, verifiable steps +3. Identify which tools you'll need +4. Consider edge cases and potential issues +5. Execute step by step, validating as you go +``` + +### Tool-Use Prompts (How to Act) + +Guidance on when and how to use available tools: + +```markdown +When you need to understand a codebase: +- Use grep_search for finding specific patterns +- Use read_file to examine file contents +- Use list_dir to explore directory structure +- Always verify your understanding before making changes +``` + +### Recovery Prompts (How to Handle Failure) + +Instructions for when things go wrong: + +```markdown +If an action fails: +1. Analyze the error message carefully +2. Consider alternative approaches +3. Ask for clarification if the task is ambiguous +4. Never repeat the same failed action without changes +``` + + +An agent's behavior emerges from layers of prompts working together. The system prompt sets the foundation, planning prompts guide reasoning, tool prompts enable action, and recovery prompts handle failures. Together, they create coherent, capable behavior. + + +## What Are Skills? + +If prompts are the atoms, **skills are the molecules**—reusable building blocks that give agents specific capabilities. + +A **skill** is a comprehensive, portable package of instructions that gives an AI agent expertise in a specific domain or task. Skills are the reusable blocks of agents: you build them once, and any agent can use them. + + +Write a skill for code review once. Now every coding agent—whether it's for Python, JavaScript, or Rust—can instantly become an expert code reviewer by loading that skill. Skills let you build agent capabilities like LEGO blocks. + + +### Anatomy of a Skill + +A well-designed skill typically includes: + +
+
+

📄 SKILL.md (Required)

+

The main instruction file. Contains the core expertise, guidelines, and behaviors that define the skill.

+
+
+

📚 Reference Docs

+

Supporting documentation, examples, and context the agent can reference while working.

+
+
+

🔧 Scripts & Tools

+

Helper scripts, templates, or tool configurations that support the skill's functionality.

+
+
+

⚙️ Configuration

+

Settings, parameters, and customization options for adapting the skill to different contexts.

+
+
+ +### Example: Code Review Skill + +Here's what a code review skill might look like: + +
+
+ 📁 + code-review-skill/ +
+
+
+ 📄 + SKILL.md + Core review guidelines +
+
+ 📄 + security-checklist.md + Security patterns +
+
+ 📄 + performance-tips.md + Optimization guide +
+
+
+ 📁 + language-specific/ +
+
+
+ 📄 + python.md + Python best practices +
+
+ 📄 + javascript.md + JavaScript patterns +
+
+ 📄 + rust.md + Rust guidelines +
+
+
+
+
+ +The `SKILL.md` file defines the overall approach: + +```markdown +--- +name: code-review +description: Comprehensive code review with security, performance, and style analysis +--- + +# Code Review Skill + +You are an expert code reviewer. When reviewing code: + +## Process +1. **Understand Context** - What does this code do? What problem does it solve? +2. **Check Correctness** - Does it work? Are there logic errors? +3. **Security Scan** - Reference security-checklist.md for common vulnerabilities +4. **Performance Review** - Check performance-tips.md for optimization opportunities +5. **Style & Maintainability** - Is the code readable and maintainable? + +## Output Format +Provide feedback in categories: +- 🔴 **Critical** - Must fix before merge +- 🟡 **Suggested** - Recommended improvements +- 🟢 **Nice to have** - Optional enhancements + +Always explain *why* something is an issue, not just *what* is wrong. +``` + +## Skills vs. Simple Prompts + +
+
+

Simple Prompt

+
+

Single instruction

+

One-off use

+

Limited context

+

Generic approach

+

No supporting materials

+
+
+
+

Skill

+
+

Comprehensive instruction set

+

Reusable across projects

+

Rich context with references

+

Domain-specific expertise

+

Supporting docs, scripts, configs

+
+
+
+ +## Building Effective Skills + +### 1. Define the Expertise Clearly + +Start with a clear description of what the skill enables: + +```markdown +--- +name: api-design +description: Design RESTful APIs following industry best practices, + including versioning, error handling, and documentation standards +--- +``` + +### 2. Structure Knowledge Hierarchically + +Organize information from general to specific: + +```markdown +# API Design Skill + +## Core Principles +- Resources should be nouns, not verbs +- Use HTTP methods semantically +- Version your APIs from day one + +## Detailed Guidelines +[More specific rules...] + +## Reference Materials +- See `rest-conventions.md` for naming conventions +- See `error-codes.md` for standard error responses +``` + +### 3. Include Concrete Examples + +Abstract rules become clear with examples: + +```markdown +## Endpoint Naming + +✅ Good: +- GET /users/{id} +- POST /orders +- DELETE /products/{id}/reviews/{reviewId} + +❌ Avoid: +- GET /getUser +- POST /createNewOrder +- DELETE /removeProductReview +``` + +### 4. Provide Decision Frameworks + +Help the agent make choices in ambiguous situations: + +```markdown +## When to Use Pagination + +Use pagination when: +- Collection could exceed 100 items +- Response size impacts performance +- Client may not need all items + +Use full response when: +- Collection is always small (<20 items) +- Client typically needs everything +- Real-time consistency is critical +``` + +### 5. Add Recovery Patterns + +Anticipate what can go wrong: + +```markdown +## Common Issues + +**Problem**: Client needs fields not in standard response +**Solution**: Implement field selection: GET /users?fields=id,name,email + +**Problem**: Breaking changes needed +**Solution**: Create new version, deprecate old with timeline +``` + +## Composing Skills + +Agents become powerful when multiple skills work together. Consider how skills can complement each other: + +
+
+ Code Review +
+
+
+
+ Security Audit +
+
+
+
+ Documentation +
+
=
+
+ Complete Code Quality Agent +
+
+ +When composing skills, ensure they don't conflict. Skills should be: + +- **Modular** - Each skill handles one domain well +- **Compatible** - Skills shouldn't give contradictory instructions +- **Prioritized** - When skills overlap, define which takes precedence + +## Sharing and Discovering Skills + +Skills are most valuable when shared. Platforms like [prompts.chat](https://prompts.chat/skills) allow you to: + +- **Discover** community-created skills for common tasks +- **Download** skills directly to your projects +- **Share** your own expertise as reusable skills +- **Iterate** on skills based on real-world usage + + +Before building a skill from scratch, check if someone has already solved your problem. Community skills are battle-tested and often better than starting from zero. + + +## The Agent-Skill Ecosystem + +The relationship between agents and skills creates a powerful ecosystem: + +
+
+ AI Agent +
+
+
+

Code Review

+

Skill 1

+
+
+

API Design

+

Skill 2

+
+
+

Test Writing

+

Skill 3

+
+
+
+
↓
+
+
+
+

Core Prompts

+

Planning • Tools • Recovery • Memory

+
+
+
+ +The agent provides the execution framework—planning, tool use, and memory—while skills provide domain expertise. This separation means: + +- **Skills are portable** - The same skill works with different agents +- **Agents are extensible** - Add new capabilities by adding skills +- **Expertise is shareable** - Domain experts can contribute skills without building full agents + +## Best Practices + +### For Building Skills + +1. **Start specific, then generalize** - Build a skill for your exact use case first, then abstract +2. **Include failure cases** - Document what the skill can't do and how to handle it +3. **Version your skills** - Track changes so agents can depend on stable versions +4. **Test with real tasks** - Validate skills against actual work, not just theory + +### For Using Skills with Agents + +1. **Read the skill first** - Understand what a skill does before deploying it +2. **Customize thoughtfully** - Override skill defaults only when necessary +3. **Monitor performance** - Track how well skills perform in your context +4. **Contribute improvements** - When you improve a skill, consider sharing back + + +As AI agents become more capable, the ability to compose, share, and customize skills will become a core competency. The prompt engineers of tomorrow won't just write prompts—they'll architect skill ecosystems that make AI agents genuinely expert in specific domains. + + + + + + + diff --git a/src/content/book/it/00a-preface.mdx b/src/content/book/it/00a-preface.mdx new file mode 100644 index 00000000..cd2dedca --- /dev/null +++ b/src/content/book/it/00a-preface.mdx @@ -0,0 +1,82 @@ +
+ Fatih Kadir Akın +
+ Fatih Kadir Akın + Creatore di Awesome ChatGPT Prompts (noto anche come prompts.chat) + + Sviluppatore software di Istanbul, a capo delle Developer Relations presso Teknasyon. Autore di libri su JavaScript e prompt engineering. Sostenitore dell'open-source specializzato in tecnologie web e sviluppo assistito dall'IA. + + +
+
+ +Ricordo ancora la notte in cui tutto è cambiato. + +Era il **30 novembre 2022**. Ero seduto alla mia scrivania, scorrendo Twitter, quando ho visto persone che parlavano di qualcosa chiamato "ChatGPT". Ho cliccato sul link, ma sinceramente? Non mi aspettavo molto. Avevo già provato quei vecchi strumenti IA di "completamento delle parole", quelli che generavano sciocchezze dopo poche frasi. Pensavo che questo sarebbe stato più dello stesso. + +Ho digitato una semplice domanda e premuto invio. + +Poi mi sono bloccato. + +La risposta non era solo coerente. Era *buona*. Capiva cosa intendevo. Sapeva ragionare. Sembrava completamente diverso da tutto ciò che avevo visto prima. Ho provato un altro prompt. E un altro. Ogni risposta mi stupiva più della precedente. + +Non sono riuscito a dormire quella notte. Per la prima volta, sentivo di stare davvero *parlando* con una macchina, e lei rispondeva in un modo che aveva veramente senso. + +## Un Repository Nato dalla Meraviglia + +In quei primi giorni, non ero solo nel mio entusiasmo. Ovunque guardassi, le persone scoprivano modi creativi per usare ChatGPT. Gli insegnanti lo usavano per spiegare concetti complessi. Gli scrittori collaboravano con esso per le storie. Gli sviluppatori facevano debug del codice con il suo aiuto. + +Ho iniziato a raccogliere i migliori prompt che trovavo. Quelli che funzionavano come magia. Quelli che trasformavano semplici domande in risposte brillanti. E ho pensato: *Perché tenerlo per me?* + +Così ho creato un semplice repository GitHub chiamato [Awesome ChatGPT Prompts](https://github.com/f/prompts.chat). Mi aspettavo che forse qualche centinaio di persone lo avrebbe trovato utile. + +Mi sbagliavo. + +In poche settimane, il repository è decollato. Migliaia di stelle. Poi decine di migliaia. Persone da tutto il mondo hanno iniziato ad aggiungere i propri prompt, condividendo ciò che avevano imparato e aiutandosi a vicenda. Quello che era iniziato come la mia collezione personale è diventato qualcosa di molto più grande: una comunità mondiale di persone curiose che si aiutano a vicenda. + +Oggi, quel repository ha oltre **140.000 stelle su GitHub** e contributi da centinaia di persone che non ho mai incontrato ma per cui sono profondamente grato. + +## Perché Ho Scritto Questo Libro + +La versione originale di questo libro è stata pubblicata su [Gumroad](https://gumroad.com/l/the-art-of-chatgpt-prompting) **all'inizio del 2023**, solo pochi mesi dopo il lancio di ChatGPT. È stato uno dei primi libri mai scritti sul prompt engineering, un tentativo di catturare tutto ciò che avevo imparato sulla creazione di prompt efficaci quando il campo era ancora completamente nuovo. Con mia sorpresa, oltre **100.000 persone** lo hanno scaricato. + +Ma sono passati tre anni da allora. L'IA è cambiata molto. Sono apparsi nuovi modelli. E abbiamo tutti imparato molto di più su come parlare con l'IA. + +Questa nuova edizione è il mio regalo alla comunità che mi ha dato così tanto. Contiene tutto ciò che avrei voluto sapere quando ho iniziato: **cosa funziona**, **cosa evitare** e **idee che rimangono vere** indipendentemente dall'IA che usi. + +## Cosa Significa Questo Libro per Me + +Non fingerò che questo sia solo un manuale di istruzioni. Per me significa molto di più. + +Questo libro cattura un momento in cui il mondo è cambiato, e le persone si sono riunite per capirlo. Rappresenta le notti tarde a provare cose, la gioia della scoperta e la gentilezza di sconosciuti che hanno condiviso ciò che hanno imparato. + +Soprattutto, rappresenta la mia convinzione che **il modo migliore per imparare qualcosa è condividerlo con gli altri**. + +## Per Te + +Che tu stia appena iniziando con l'IA o la usi da anni, ho scritto questo libro per te. + +Spero che ti faccia risparmiare tempo. Spero che accenda idee. Spero che ti aiuti a realizzare cose che non pensavi fossero possibili. + +E quando scopri qualcosa di straordinario, spero che lo condividerai con gli altri, proprio come tante persone hanno condiviso con me. + +**È così che miglioriamo tutti insieme.** + +Grazie per essere qui. Grazie per far parte di questa comunità. + +Ora, cominciamo. + +--- + +*Con gratitudine,* + +**Fatih Kadir Akın** +*Istanbul, Gennaio 2025* diff --git a/src/content/book/it/00b-history.mdx b/src/content/book/it/00b-history.mdx new file mode 100644 index 00000000..30bfb863 --- /dev/null +++ b/src/content/book/it/00b-history.mdx @@ -0,0 +1,159 @@ +# La Storia di Awesome ChatGPT Prompts + +## L'Inizio: Novembre 2022 + +Quando ChatGPT è stato lanciato per la prima volta a novembre 2022, il mondo dell'IA è cambiato da un giorno all'altro. Quello che una volta era il dominio di ricercatori e sviluppatori è diventato improvvisamente accessibile a tutti. Tra coloro che sono stati affascinati da questa nuova tecnologia c'era Fatih Kadir Akın, uno sviluppatore che ha visto qualcosa di straordinario nelle capacità di ChatGPT. + +> "Quando ChatGPT è stato lanciato per la prima volta, sono stato immediatamente affascinato dalle sue capacità. Ho sperimentato lo strumento in vari modi e sono stato costantemente stupito dai risultati." + +Quei primi giorni erano pieni di sperimentazione e scoperta. Utenti di tutto il mondo trovavano modi creativi per interagire con ChatGPT, condividendo le loro scoperte e imparando gli uni dagli altri. È stata in questa atmosfera di entusiasmo ed esplorazione che è nata l'idea per "Awesome ChatGPT Prompts". + +## Il Repository Che Ha Dato Inizio a Tutto + +A dicembre 2022, solo poche settimane dopo il lancio di ChatGPT, è stato creato il repository [Awesome ChatGPT Prompts](https://github.com/f/prompts.chat) su GitHub. Il concetto era semplice ma potente: una collezione curata di prompt efficaci che chiunque poteva usare e a cui contribuire. + +Il repository ha rapidamente guadagnato popolarità, diventando una risorsa di riferimento per gli utenti di ChatGPT in tutto il mondo. Quello che era iniziato come una collezione personale di prompt utili si è evoluto in un progetto guidato dalla comunità con contributi di sviluppatori, scrittori, educatori e appassionati da ogni angolo del globo. + +### Traguardi + +**Stampa e Media** +- Menzionato in [Forbes](https://www.forbes.com/sites/bernardmarr/2023/05/17/the-best-prompts-for-chatgpt-a-complete-guide/) come una delle migliori risorse di prompt per ChatGPT + +**Riconoscimento Accademico** +- Citato da [Harvard University](https://www.huit.harvard.edu/news/ai-prompts) nelle loro linee guida sull'IA +- Citato dalla [Columbia University](https://etc.cuit.columbia.edu/news/columbia-prompt-library-effective-academic-ai-use) Prompt Library +- Usato da [Olympic College](https://libguides.olympic.edu/UsingAI/Prompts) nelle loro risorse sull'IA +- Citato in [articoli accademici su arXiv](https://arxiv.org/pdf/2502.04484) +- [40+ citazioni accademiche](https://scholar.google.com/citations?user=AZ0Dg8YAAAAJ&hl=en) su Google Scholar + +**Comunità e GitHub** +- [142.000+ stelle su GitHub](https://github.com/f/prompts.chat) — uno dei repository IA più stellati +- Selezionato come [GitHub Staff Pick](https://spotlights-feed.github.com/spotlights/prompts-chat/) +- Dataset più apprezzato pubblicato su [Hugging Face](https://huggingface.co/datasets/fka/prompts.chat) +- Usato da migliaia di sviluppatori in tutto il mondo + +## Il Primo Libro: "The Art of ChatGPT Prompting" + +Il successo del repository ha portato alla creazione di "The Art of ChatGPT Prompting: A Guide to Crafting Clear and Effective Prompts" — una guida completa pubblicata su Gumroad all'inizio del 2023. + +Il libro catturava la saggezza iniziale del prompt engineering, coprendo: + +- Comprendere come funziona ChatGPT +- Principi di comunicazione chiara con l'IA +- La famosa tecnica "Act As" (Agisci Come) +- Creare prompt efficaci passo dopo passo +- Errori comuni e come evitarli +- Suggerimenti per la risoluzione dei problemi + +**Il libro è diventato un fenomeno**, raggiungendo oltre **100.000 download** su Gumroad. È stato condiviso sui social media, citato in articoli accademici e tradotto da membri della comunità in molteplici lingue. Endorsement di alto profilo sono arrivati da luoghi inaspettati — persino [Greg Brockman](https://x.com/gdb/status/1602072566671110144), co-fondatore e presidente di OpenAI, ha riconosciuto il progetto. + +## Prime Intuizioni Che Hanno Plasmato il Campo + +Durante quei mesi formativi, sono emerse diverse intuizioni chiave che sarebbero diventate fondamentali per il prompt engineering: + +### 1. La Specificità Conta + +> "Ho imparato l'importanza di usare un linguaggio specifico e rilevante per garantire che ChatGPT comprenda i miei prompt e sia in grado di generare risposte appropriate." + +I primi sperimentatori hanno scoperto che prompt vaghi portavano a risposte vaghe. Più il prompt era specifico e dettagliato, più utile era l'output. + +### 2. Scopo e Focus + +> "Ho scoperto il valore di definire uno scopo e un focus chiari per la conversazione, invece di usare prompt aperti o troppo ampi." + +Questa intuizione è diventata la base per le tecniche di prompting strutturato che si sarebbero sviluppate negli anni successivi. + +### 3. La Rivoluzione "Act As" + +Una delle tecniche più influenti emerse dalla comunità è stata il pattern "Act As" (Agisci Come). Istruendo ChatGPT ad assumere un ruolo o una persona specifica, gli utenti potevano migliorare drasticamente la qualità e la rilevanza delle risposte. + +``` +Voglio che tu agisca come una console javascript. Digiterò comandi e tu +risponderai con ciò che la console javascript dovrebbe mostrare. Voglio che +rispondi solo con l'output del terminale all'interno di un unico blocco di +codice, e nient'altro. +``` + +Questa semplice tecnica ha aperto innumerevoli possibilità e rimane una delle strategie di prompting più utilizzate oggi. + +## L'Evoluzione di prompts.chat + +### 2022: L'Inizio + +Il progetto è iniziato come un semplice repository GitHub con un file README renderizzato come HTML su GitHub Pages. Era essenziale ma funzionale — una testimonianza del principio che le grandi idee non hanno bisogno di implementazioni elaborate. + +**Stack Tecnologico**: HTML, CSS, GitHub Pages + +### 2024: Rinnovamento UI + +Man mano che la comunità cresceva, cresceva anche la necessità di una migliore esperienza utente. Il sito ha ricevuto un significativo aggiornamento dell'interfaccia, costruito con l'aiuto di assistenti di codifica IA come Cursor e Claude Sonnet 3.5. + +### 2025: La Piattaforma Attuale + +Oggi, prompts.chat si è evoluto in una piattaforma completa costruita con: + +- **Next.js** per il framework web +- **Vercel** per l'hosting +- **Sviluppo assistito dall'IA** usando Windsurf e Claude + +La piattaforma ora include account utente, collezioni, ricerca, categorie, tag e una fiorente comunità di prompt engineer. + +### App Native + +Il progetto si è espanso oltre il web con un'app iOS nativa costruita con SwiftUI, portando la libreria di prompt agli utenti mobile. + +## Impatto sulla Comunità + +Il progetto Awesome ChatGPT Prompts ha avuto un impatto profondo su come le persone interagiscono con l'IA: + +### Riconoscimento Accademico + +Università di tutto il mondo hanno citato il progetto nei loro materiali guida sull'IA, tra cui: + +- Harvard University +- Columbia University +- Olympic College +- Numerosi articoli accademici su arXiv + +### Adozione da Parte degli Sviluppatori + +Il progetto è stato integrato in innumerevoli workflow di sviluppatori. Il dataset Hugging Face è usato da ricercatori e sviluppatori per l'addestramento e il fine-tuning di modelli linguistici. + +### Comunità Globale + +Con contributi da centinaia di membri della comunità provenienti da dozzine di paesi, il progetto rappresenta uno sforzo veramente globale per rendere l'IA più accessibile e utile per tutti. + +## La Filosofia: Aperto e Gratuito + +Fin dall'inizio, il progetto è stato impegnato nell'apertura. Con licenza CC0 1.0 Universal (Dedicazione al Pubblico Dominio), tutti i prompt e i contenuti sono liberi da usare, modificare e condividere senza restrizioni. + +Questa filosofia ha permesso: + +- Traduzioni in molteplici lingue +- Integrazione in altri strumenti e piattaforme +- Uso accademico e ricerca +- Applicazioni commerciali + +L'obiettivo è sempre stato democratizzare l'accesso a tecniche efficaci di comunicazione con l'IA — per garantire che tutti, indipendentemente dal background tecnico, possano beneficiare di questi strumenti. + +## Tre Anni Dopo + +Tre anni dopo il lancio di ChatGPT, il campo del prompt engineering è maturato significativamente. Quello che era iniziato come sperimentazione informale si è evoluto in una disciplina riconosciuta con pattern stabiliti, best practice e una comunità di ricerca attiva. + +Il progetto Awesome ChatGPT Prompts è cresciuto insieme a questo campo, evolvendosi da una semplice lista di prompt a una piattaforma completa per scoprire, condividere e imparare sui prompt IA. + +Questo libro rappresenta la prossima evoluzione — una distillazione di tre anni di saggezza della comunità, aggiornata per il panorama IA di oggi e di domani. + +## Guardando al Futuro + +Il viaggio da quel primo repository a questa guida completa riflette la rapida evoluzione dell'IA e la nostra comprensione di come lavorare efficacemente con essa. Man mano che le capacità dell'IA continuano ad avanzare, lo faranno anche le tecniche per comunicare con questi sistemi. + +I principi scoperti in quei primi giorni — chiarezza, specificità, scopo e il potere del role-playing — rimangono rilevanti come sempre. Ma nuove tecniche continuano ad emergere: chain-of-thought prompting, few-shot learning, interazioni multimodali e altro. + +La storia di Awesome ChatGPT Prompts è in definitiva una storia sulla comunità — su migliaia di persone in tutto il mondo che condividono le loro scoperte, si aiutano a vicenda a imparare e avanzano collettivamente la nostra comprensione di come lavorare con l'IA. + +Quello spirito di collaborazione aperta e apprendimento condiviso è ciò che questo libro spera di continuare. + +--- + +*Il progetto Awesome ChatGPT Prompts è mantenuto da [@f](https://github.com/f) e da una straordinaria comunità di contributori. Visita [prompts.chat](https://prompts.chat) per esplorare la piattaforma, e unisciti a noi su [GitHub](https://github.com/f/prompts.chat) per contribuire.* diff --git a/src/content/book/it/00c-introduction.mdx b/src/content/book/it/00c-introduction.mdx new file mode 100644 index 00000000..1f7af64b --- /dev/null +++ b/src/content/book/it/00c-introduction.mdx @@ -0,0 +1,130 @@ +Benvenuto ne **Il Libro Interattivo del Prompting**, la tua guida per comunicare efficacemente con l'IA. + + +Alla fine di questo libro, capirai come funziona l'IA, come scrivere prompt migliori e come usare queste competenze per scrittura, programmazione, ricerca e progetti creativi. + + + +A differenza dei libri tradizionali, questa guida è completamente interattiva. Troverai demo dal vivo, esempi cliccabili e pulsanti "Provalo" in tutto il libro che ti permettono di testare i prompt istantaneamente. Imparare facendo rende i concetti complessi molto più facili da capire. + + +## Cos'è il Prompt Engineering? + +Il prompt engineering è l'abilità di scrivere buone istruzioni per l'IA. Quando scrivi qualcosa a ChatGPT, Claude, Gemini o altri strumenti IA, quello si chiama "prompt". Migliore è il tuo prompt, migliore è la risposta che ottieni. + +Pensala così: l'IA è un potente assistente che prende le tue parole molto alla lettera. Farà esattamente ciò che chiedi. Il trucco è imparare a chiedere esattamente ciò che vuoi. + + + +La differenza nella qualità dell'output tra questi due prompt può essere drammatica. + + + +## Come Si È Evoluto il Prompt Engineering + +In soli tre anni dal lancio di ChatGPT, il prompt engineering si è evoluto drasticamente insieme alla tecnologia stessa. Quello che era iniziato semplicemente come "scrivere domande migliori" è cresciuto in qualcosa di molto più ampio. + +Oggi, capiamo che il tuo prompt è solo **una parte di un contesto più ampio**. I sistemi IA moderni lavorano con molteplici tipi di dati simultaneamente: + +- **Prompt di sistema** che definiscono il comportamento dell'IA +- **Cronologia della conversazione** dai messaggi precedenti +- **Documenti recuperati** estratti da database (RAG) +- **Definizioni di strumenti** che permettono all'IA di compiere azioni +- **Preferenze utente** e impostazioni +- **Il tuo prompt effettivo** - la domanda che stai ponendo ora + +Questo passaggio da "prompt engineering" a "context engineering" riflette come ora pensiamo alle interazioni con l'IA. Il tuo prompt conta, ma conta anche tutto il resto che l'IA vede. I migliori risultati vengono dalla gestione attenta di tutti questi pezzi insieme. + +Esploreremo questi concetti in profondità in tutto questo libro, specialmente nel capitolo [Context Engineering](/book/20-context-engineering). + +## Perché il Prompt Engineering È Importante? + +### 1. Ottenere Risposte Migliori + +Gli strumenti IA sono incredibilmente capaci, ma hanno bisogno di istruzioni chiare per sbloccare il loro pieno potenziale. La stessa IA che dà una risposta mediocre a una domanda vaga può produrre un lavoro brillante quando sollecitata correttamente. + + + +### 2. Risparmiare Tempo e Denaro + +Un prompt ben costruito ottiene risultati al primo tentativo invece di molteplici scambi avanti e indietro. Questo conta ancora di più quando paghi per token o lavori con limiti di richieste. Un investimento di 5 minuti nella scrittura di un buon prompt può risparmiare ore di iterazione. + +### 3. Ottenere Risultati Consistenti e Riproducibili + +I buoni prompt producono output prevedibili. Questo è critico per: +- **Workflow aziendali** dove hai bisogno della stessa qualità ogni volta +- **Automazione** dove i prompt vengono eseguiti senza revisione umana +- **Team** dove più persone hanno bisogno di risultati simili + +### 4. Sbloccare Capacità Avanzate + +Molte potenti funzionalità IA funzionano solo quando sai come chiedere: +- **Ragionamento chain-of-thought** per problemi complessi +- **Output strutturato** per estrazione dati +- **Role-playing** per competenze specializzate +- **Few-shot learning** per compiti personalizzati + +Senza conoscenze di prompt engineering, stai usando solo una frazione di ciò che l'IA può fare. + +### 5. Rimanere Sicuri ed Evitare Insidie + +Un buon prompting ti aiuta a: +- Evitare allucinazioni chiedendo fonti e verifiche +- Ottenere prospettive bilanciate invece di risposte unilaterali +- Impedire all'IA di fare assunzioni che non intendevi +- Tenere informazioni sensibili fuori dai tuoi prompt + +### 6. Rendere le Tue Competenze a Prova di Futuro + +Man mano che l'IA diventa più integrata nel lavoro e nella vita, il prompt engineering diventa un'alfabetizzazione fondamentale. I principi che impari qui si applicano a tutti gli strumenti IA—ChatGPT, Claude, Gemini, generatori di immagini e modelli futuri che non abbiamo ancora visto. + +## Per Chi È Questo Libro? + +Questo libro è per tutti: + +- **Principianti** che vogliono imparare a usare meglio gli strumenti IA +- **Studenti** che lavorano su compiti, ricerche o progetti creativi +- **Scrittori e creatori** che usano l'IA per il loro lavoro +- **Sviluppatori** che costruiscono app con l'IA +- **Professionisti** che vogliono usare l'IA al lavoro +- **Chiunque sia curioso** di ottenere di più dagli assistenti IA + +## Come È Organizzato Questo Libro + + + +Più un'**Appendice** con template, aiuto per la risoluzione dei problemi, glossario e risorse extra. + +## Una Nota sui Modelli IA + +Questo libro usa principalmente esempi da ChatGPT (dato che è il più popolare), ma le idee funzionano con qualsiasi strumento IA come Claude, Gemini o altri. Menzioneremo quando qualcosa funziona solo con modelli IA specifici. + +L'IA sta cambiando velocemente. Ciò che funziona oggi potrebbe essere sostituito da qualcosa di meglio domani. Ecco perché questo libro si concentra su idee fondamentali che rimarranno utili indipendentemente dall'IA che usi. + +## Cominciamo + +Scrivere buoni prompt è un'abilità che migliora con la pratica. Mentre leggi questo libro: + +1. **Prova le cose** - Testa gli esempi, cambiali, guarda cosa succede +2. **Continua a provare** - Non aspettarti risultati perfetti al primo tentativo +3. **Prendi appunti** - Scrivi cosa funziona e cosa no +4. **Condividi** - Aggiungi le tue scoperte a [prompts.chat](https://prompts.chat) + + +Il modo migliore per imparare è fare. Ogni capitolo ha esempi che puoi provare subito. Non solo leggere. Provalo tu stesso! + + +Pronto a trasformare come lavori con l'IA? Gira pagina e cominciamo. + +--- + +*Questo libro fa parte del progetto [Awesome ChatGPT Prompts](https://github.com/f/prompts.chat) ed è rilasciato sotto licenza CC0 1.0 Universal (Pubblico Dominio).* diff --git a/src/content/book/it/01-understanding-ai-models.mdx b/src/content/book/it/01-understanding-ai-models.mdx new file mode 100644 index 00000000..03745404 --- /dev/null +++ b/src/content/book/it/01-understanding-ai-models.mdx @@ -0,0 +1,302 @@ +Prima di imparare le tecniche di prompting, è utile capire come funzionano effettivamente i modelli linguistici IA. Questa conoscenza ti renderà più bravo a scrivere prompt. + + +Capire come funziona l'IA non è solo per esperti. Ti aiuta direttamente a scrivere prompt migliori. Una volta che sai che l'IA prevede cosa viene dopo, darai naturalmente istruzioni più chiare. + + +## Cosa Sono i Large Language Models? + +I Large Language Models (LLM) sono sistemi IA che hanno imparato leggendo enormi quantità di testo. Possono scrivere, rispondere a domande e avere conversazioni che suonano umane. Sono chiamati "large" (grandi) perché hanno miliardi di piccole impostazioni (chiamate parametri) che sono state regolate durante l'addestramento. + +### Come Funzionano gli LLM (Semplificato) + +Al loro cuore, gli LLM sono macchine di previsione. Gli dai del testo, e loro prevedono cosa dovrebbe venire dopo. + + + +Quando scrivi "La capitale della Francia è...", l'IA prevede "Parigi" perché è quello che di solito viene dopo in un testo sulla Francia. Questa semplice idea, ripetuta miliardi di volte con enormi quantità di dati, crea un comportamento sorprendentemente intelligente. + + + +### Concetti Chiave + +**Token**: L'IA non legge lettera per lettera. Divide il testo in pezzi chiamati "token". Un token potrebbe essere una parola intera come "ciao" o parte di una parola come "zione". Capire i token aiuta a spiegare perché l'IA a volte fa errori di ortografia o ha difficoltà con certe parole. + + +Un token è la più piccola unità di testo che un modello IA elabora. Non è sempre una parola completa—potrebbe essere un frammento di parola, punteggiatura o spazio bianco. Per esempio, "incredibile" potrebbe diventare 3 token: "in" + "cred" + "ibile". In media, **1 token ≈ 4 caratteri** o **100 token ≈ 75 parole**. I costi API e i limiti di contesto sono misurati in token. + + + + +**Finestra di Contesto**: Questa è quanta testo l'IA può "ricordare" in una conversazione. Pensala come la memoria a breve termine dell'IA. Include tutto: la tua domanda E la risposta dell'IA. + + + +Le finestre di contesto variano per modello e si stanno espandendo rapidamente: + +
+
+ GPT-4o + 128K token +
+
+ GPT-5 + 400K token +
+
+ Claude Sonnet 4 + 1M token +
+
+ Gemini 2.5 + 1M token +
+
+ Llama 4 + 1M-10M token +
+
+ DeepSeek R1 + 128K token +
+
+ +**Temperatura**: Questa controlla quanto l'IA è creativa o prevedibile. Temperatura bassa (0.0-0.3) ti dà risposte focalizzate e consistenti. Temperatura alta (0.7-1.0) ti dà risposte più creative e sorprendenti. + + + +**Prompt di Sistema**: Istruzioni speciali che dicono all'IA come comportarsi per un'intera conversazione. Per esempio, "Sei un insegnante amichevole che spiega le cose semplicemente." Non tutti gli strumenti IA ti permettono di impostarlo, ma è molto potente quando disponibile. + +## Tipi di Modelli IA + +### Modelli di Testo (LLM) +Il tipo più comune, questi generano risposte testuali a input testuali. Alimentano chatbot, assistenti di scrittura e generatori di codice. Esempi: GPT-4, Claude, Llama, Mistral. + +### Modelli Multimodali +Questi possono capire più del solo testo. Possono guardare immagini, ascoltare audio e guardare video. Esempi: GPT-4V, Gemini, Claude 3. + +### Modelli Text-to-Image + + +Mentre questo libro si concentra principalmente sul prompting per Large Language Models (IA basata su testo), i principi di prompting chiaro e specifico si applicano anche alla generazione di immagini. Padroneggiare i prompt per questi modelli è altrettanto importante per ottenere grandi risultati. + + +I modelli text-to-image come DALL-E, Midjourney, Nano Banana e Stable Diffusion creano immagini da descrizioni testuali. Funzionano diversamente dai modelli di testo: + +**Come Funzionano:** +1. **Addestramento**: Il modello impara da milioni di coppie immagine-testo, capendo quali parole corrispondono a quali concetti visivi +2. **Processo di Diffusione**: Partendo da rumore casuale, il modello raffina gradualmente l'immagine, guidato dal tuo prompt testuale +3. **Guida CLIP**: Un modello separato (CLIP) aiuta a collegare le tue parole ai concetti visivi, assicurando che l'immagine corrisponda alla tua descrizione + + + +**Il Prompting per Immagini È Diverso:** +A differenza dei prompt testuali dove scrivi frasi, i prompt per immagini spesso funzionano meglio come frasi descrittive separate da virgole: + + + +### Modelli Text-to-Video + +Text-to-video è la frontiera più recente. Modelli come Sora 2, Runway e Veo creano immagini in movimento da descrizioni testuali. Come i modelli per immagini, la qualità del tuo prompt determina direttamente la qualità del tuo output—il prompt engineering è altrettanto cruciale qui. + +**Come Funzionano:** +1. **Comprensione Temporale**: Oltre alle singole immagini, questi modelli capiscono come le cose si muovono e cambiano nel tempo +2. **Simulazione Fisica**: Imparano fisica di base—come cadono gli oggetti, come scorre l'acqua, come camminano le persone +3. **Consistenza dei Frame**: Mantengono soggetti e scene consistenti attraverso molti frame +4. **Diffusione nel Tempo**: Simile ai modelli per immagini, ma generando sequenze coerenti invece di singoli frame + + + + +I prompt video devono descrivere azione nel tempo, non solo una scena statica. Includi verbi e movimento: + + + + +### Modelli Specializzati +Affinati per compiti specifici come generazione di codice (Codex, CodeLlama), generazione musicale (Suno, Udio), o applicazioni specifiche di dominio come diagnosi mediche o analisi di documenti legali. + +## Capacità e Limitazioni dei Modelli + +Esplora cosa possono e non possono fare gli LLM. Clicca su ogni capacità per vedere prompt di esempio: + + + +### Capire le Allucinazioni + + +A volte l'IA scrive cose che sembrano vere ma non lo sono. Questo si chiama "allucinazione." Non è un bug. È solo come funziona la previsione. Controlla sempre i fatti importanti. + + +Perché l'IA inventa cose? + +1. Cerca di scrivere testo che suona bene, non testo che è sempre vero +2. Internet (dove ha imparato) ha errori anche lui +3. Non può realmente controllare se qualcosa è reale + + + +- **Chiedi le fonti**: Poi controlla se quelle fonti sono reali +- **Chiedi ragionamento passo-passo**: Così puoi controllare ogni passaggio +- **Ricontrolla i fatti importanti**: Usa Google o siti affidabili +- **Chiedi "Sei sicuro?"**: L'IA potrebbe ammettere incertezza + + + + + +## Come Impara l'IA: I Tre Passi + +L'IA non sa magicamente le cose. Passa attraverso tre passi di apprendimento, come andare a scuola: + +### Passo 1: Pre-training (Imparare a Leggere) + +Immagina di leggere ogni libro, sito web e articolo su internet. Questo è quello che succede nel pre-training. L'IA legge miliardi di parole e impara pattern: + +- Come sono costruite le frasi +- Quali parole di solito vanno insieme +- Fatti sul mondo +- Diversi stili di scrittura + +Questo richiede mesi e costa milioni di dollari. Dopo questo passo, l'IA sa molto, ma non è ancora molto utile. Potrebbe solo continuare qualsiasi cosa scrivi, anche se non è quello che volevi. + + + +### Passo 2: Fine-tuning (Imparare ad Aiutare) + +Ora l'IA impara a essere un buon assistente. Gli addestratori le mostrano esempi di conversazioni utili: + +- "Quando qualcuno fa una domanda, dai una risposta chiara" +- "Quando ti viene chiesto di fare qualcosa di dannoso, rifiuta educatamente" +- "Sii onesto su ciò che non sai" + +Pensala come insegnare le buone maniere. L'IA impara la differenza tra solo predire testo ed essere realmente utile. + + + +Prova il prompt sopra. Noti come l'IA rifiuta? Questo è il fine-tuning al lavoro. + +### Passo 3: RLHF (Imparare Cosa Piace agli Umani) + +RLHF sta per "Reinforcement Learning from Human Feedback" (Apprendimento per Rinforzo dal Feedback Umano). È un modo elegante per dire: gli umani valutano le risposte dell'IA, e l'IA impara a darne di migliori. + +Ecco come funziona: +1. L'IA scrive due risposte diverse alla stessa domanda +2. Un umano sceglie quale risposta è migliore +3. L'IA impara: "Ok, dovrei scrivere più come la Risposta A" +4. Questo succede milioni di volte + +Ecco perché l'IA: +- È educata e amichevole +- Ammette quando non sa qualcosa +- Cerca di vedere diversi lati di una questione +- Evita affermazioni controverse + + +Conoscere questi tre passi ti aiuta a capire il comportamento dell'IA. Quando l'IA rifiuta una richiesta, quello è fine-tuning. Quando l'IA è extra educata, quello è RLHF. Quando l'IA sa fatti casuali, quello è pre-training. + + +## Cosa Significa Questo per i Tuoi Prompt + +Ora che capisci come funziona l'IA, ecco come usare quella conoscenza: + +### 1. Sii Chiaro e Specifico + +L'IA prevede cosa viene dopo basandosi sulle tue parole. Prompt vaghi portano a risposte vaghe. Prompt specifici ottengono risultati specifici. + + + + + +### 2. Dai Contesto + +L'IA non sa nulla di te a meno che non glielo dici. Ogni conversazione inizia da zero. Includi le informazioni di sfondo di cui l'IA ha bisogno. + + + + + +### 3. Lavora Con l'IA, Non Contro di Lei + +Ricorda: l'IA è stata addestrata per essere utile. Chiedi le cose come le chiederesti a un amico disponibile. + + + +### 4. Ricontrolla Sempre le Cose Importanti + +L'IA suona sicura anche quando sbaglia. Per qualsiasi cosa importante, verifica le informazioni tu stesso. + + + +### 5. Metti le Cose Importanti Prima + +Se il tuo prompt è molto lungo, metti le istruzioni più importanti all'inizio. L'IA presta più attenzione a ciò che viene prima. + +## Scegliere l'IA Giusta + +Diversi modelli IA sono bravi in cose diverse: + +
+
+ Domande veloci + Modelli più veloci come GPT-4o o Claude 3.5 Sonnet +
+
+ Problemi difficili + Modelli più intelligenti come GPT-5.2 o Claude 4.5 Opus +
+
+ Scrivere codice + Modelli focalizzati sul codice o i modelli generali più intelligenti +
+
+ Documenti lunghi + Modelli con grandi finestre di contesto (Claude, Gemini) +
+
+ Eventi attuali + Modelli con accesso a internet +
+
+ +## Riepilogo + +I modelli linguistici IA sono macchine di previsione addestrate sul testo. Sono straordinari in molte cose, ma hanno limiti reali. Il modo migliore per usare l'IA è capire come funziona e scrivere prompt che giocano sui suoi punti di forza. + + + + + +Nel prossimo capitolo, impareremo cosa rende un buon prompt e come scrivere prompt che ottengono grandi risultati. diff --git a/src/content/book/it/02-anatomy-of-effective-prompt.mdx b/src/content/book/it/02-anatomy-of-effective-prompt.mdx new file mode 100644 index 00000000..fa9d6f86 --- /dev/null +++ b/src/content/book/it/02-anatomy-of-effective-prompt.mdx @@ -0,0 +1,343 @@ +Ogni grande prompt condivide elementi strutturali comuni. Comprendere questi componenti ti permette di costruire prompt sistematicamente invece che per tentativi ed errori. + + +Pensa a questi componenti come mattoncini LEGO. Non ne hai bisogno tutti per ogni prompt, ma sapere cosa è disponibile ti aiuta a costruire esattamente ciò di cui hai bisogno. + + +## I Componenti Principali + +Un prompt efficace tipicamente include alcuni o tutti questi elementi: + + + +Esaminiamo ogni componente in dettaglio. + +## 1. Ruolo / Persona + +Impostare un ruolo focalizza le risposte del modello attraverso la lente di una competenza o prospettiva specifica. + + + +Il ruolo prepara il modello a: +- Usare vocabolario appropriato +- Applicare competenze rilevanti +- Mantenere una prospettiva consistente +- Considerare il pubblico appropriatamente + +### Pattern di Ruolo Efficaci + +``` +"Sei un [professione] con [X anni] di esperienza in [specialità]" +"Agisci come un [ruolo] che è [caratteristica]" +"Sei un esperto [campo] che aiuta un [tipo di pubblico]" +``` + +## 2. Contesto / Background + +Il contesto fornisce le informazioni di cui il modello ha bisogno per capire la tua situazione. Ricorda: il modello non sa nulla di te, del tuo progetto o dei tuoi obiettivi a meno che non glielo dici. + + + +### Cosa Includere nel Contesto + +- **Dettagli del progetto** — Stack tecnologico, architettura, vincoli +- **Stato attuale** — Cosa hai provato, cosa funziona, cosa no +- **Obiettivi** — Cosa stai cercando di raggiungere in definitiva +- **Vincoli** — Limiti di tempo, requisiti tecnici, guide di stile + +## 3. Compito / Istruzione + +Il compito è il cuore del tuo prompt—ciò che vuoi che il modello faccia. Sii specifico e non ambiguo. + +### Lo Spettro della Specificità + + + +### Verbi d'Azione Che Funzionano Bene + +
+
+ Creazione + Scrivi, Crea, Genera, Componi, Progetta +
+
+ Analisi + Analizza, Valuta, Confronta, Esamina, Rivedi +
+
+ Trasformazione + Converti, Traduci, Riformatta, Riassumi, Espandi +
+
+ Spiegazione + Spiega, Descrivi, Chiarisci, Definisci, Illustra +
+
+ Risoluzione Problemi + Risolvi, Debug, Correggi, Ottimizza, Migliora +
+
+ +## 4. Vincoli / Regole + +I vincoli delimitano l'output del modello. Prevengono problemi comuni e assicurano rilevanza. + +### Tipi di Vincoli + +**Vincoli di lunghezza:** +``` +"Mantieni la tua risposta sotto 200 parole" +"Fornisci esattamente 5 suggerimenti" +"Scrivi 3-4 paragrafi" +``` + +**Vincoli di contenuto:** +``` +"Non includere esempi di codice" +"Concentrati solo sugli aspetti tecnici" +"Evita linguaggio da marketing" +``` + +**Vincoli di stile:** +``` +"Usa un tono formale e accademico" +"Scrivi come se stessi parlando a un bambino di 10 anni" +"Sii diretto ed evita linguaggio incerto" +``` + +**Vincoli di ambito:** +``` +"Considera solo opzioni disponibili in Python 3.10+" +"Limita i suggerimenti a strumenti gratuiti" +"Concentrati su soluzioni che non richiedono dipendenze aggiuntive" +``` + +## 5. Formato di Output + +Specificare il formato di output assicura che ricevi risposte in una struttura utilizzabile. + +### Formati Comuni + +**Liste:** +``` +"Restituisci come lista puntata" +"Fornisci una lista numerata di passaggi" +``` + +**Dati strutturati:** +``` +"Restituisci come JSON con chiavi: titolo, descrizione, priorità" +"Formatta come tabella markdown con colonne: Funzionalità, Pro, Contro" +``` + +**Strutture specifiche:** +``` +"Struttura la tua risposta come: + ## Riepilogo + ## Punti Chiave + ## Raccomandazioni" +``` + +### Esempio Output JSON + +``` +Analizza questa recensione cliente e restituisci JSON: +{ + "sentiment": "positivo" | "negativo" | "neutro", + "argomenti": ["array di argomenti principali"], + "previsione_valutazione": 1-5, + "frasi_chiave": ["frasi notevoli"] +} + +Recensione: "Il prodotto è arrivato velocemente e funziona benissimo, ma +le istruzioni erano confuse." +``` + +## 6. Esempi (Few-Shot Learning) + +Gli esempi sono il modo più potente per mostrare al modello esattamente cosa vuoi. + +### Esempio One-Shot + +``` +Converti queste frasi al passato. + +Esempio: +Input: "Lei cammina verso il negozio" +Output: "Lei camminò verso il negozio" + +Ora converti: +Input: "Loro corrono ogni mattina" +``` + +### Esempio Few-Shot + +``` +Classifica questi ticket di supporto per urgenza. + +Esempi: +"Il mio account è stato hackerato" → Critico +"Come cambio la password?" → Basso +"Il pagamento è fallito ma mi è stato addebitato" → Alto + +Classifica: "L'app si blocca quando apro le impostazioni" +``` + +## Mettere Tutto Insieme + +Ecco un prompt completo che usa tutti i componenti: + + + +## Il Prompt Minimo Efficace + +Non ogni prompt ha bisogno di tutti i componenti. Per compiti semplici, un'istruzione chiara può bastare: + +``` +Traduci "Ciao, come stai?" in inglese. +``` + +Usa componenti aggiuntivi quando: +- Il compito è complesso o ambiguo +- Hai bisogno di formattazione specifica +- I risultati non corrispondono alle aspettative +- La consistenza tra molteplici query è importante + +## Pattern di Prompt Comuni + +Questi framework ti danno una semplice checklist da seguire quando scrivi prompt. Clicca su ogni passo per vedere un esempio. + + + + + +## Riepilogo + +I prompt efficaci sono costruiti, non scoperti. Comprendendo e applicando questi componenti strutturali, puoi: + +- Ottenere risultati migliori al primo tentativo +- Fare debug di prompt che non funzionano +- Creare template di prompt riutilizzabili +- Comunicare le tue intenzioni chiaramente + + + + + +## Costruisci il Tuo Prompt + +Ora tocca a te! Usa questo costruttore di prompt interattivo per creare il tuo prompt usando i componenti che hai imparato: + + + + + +Nel prossimo capitolo, esploreremo i principi fondamentali che guidano le decisioni di costruzione dei prompt. diff --git a/src/content/book/it/03-core-prompting-principles.mdx b/src/content/book/it/03-core-prompting-principles.mdx new file mode 100644 index 00000000..a32ab354 --- /dev/null +++ b/src/content/book/it/03-core-prompting-principles.mdx @@ -0,0 +1,373 @@ +Oltre alla struttura, il prompt engineering efficace è guidato da principi—verità fondamentali che si applicano a modelli, compiti e contesti. Padroneggia questi principi, e sarai in grado di adattarti a qualsiasi sfida di prompting. + + +Questi principi si applicano a ogni modello IA e ogni compito. Imparali una volta, usali ovunque. + + +## Principio 1: Chiarezza Prima dell'Astuzia + +I migliori prompt sono chiari, non astuti. I modelli IA sono interpreti letterali—lavorano esattamente con ciò che gli dai. + +### Sii Esplicito + + + +### Evita l'Ambiguità + +Le parole possono avere molteplici significati. Scegli un linguaggio preciso. + + + +### Dichiara l'Ovvio + +Ciò che è ovvio per te non è ovvio per il modello. Esplicita le assunzioni. + +``` +Mi stai aiutando a scrivere una lettera di presentazione. + +Contesto importante: +- Mi sto candidando per una posizione di Software Engineer in Google +- Ho 5 anni di esperienza in Python e sistemi distribuiti +- Il ruolo richiede esperienza di leadership (ho guidato un team di 4) +- Voglio enfatizzare i miei contributi open-source +``` + +## Principio 2: La Specificità Produce Qualità + +Input vaghi producono output vaghi. Input specifici producono output specifici e utili. + +### La Scala della Specificità + + + +Ogni livello aggiunge specificità e migliora drasticamente la qualità dell'output. + +### Specifica Questi Elementi + +
+
+ Pubblico + Chi leggerà/userà questo? +
+
+ Lunghezza + Quanto lungo/corto dovrebbe essere? +
+
+ Tono + Formale? Informale? Tecnico? +
+
+ Formato + Prosa? Lista? Tabella? Codice? +
+
+ Ambito + Cosa includere/escludere? +
+
+ Scopo + Cosa dovrebbe realizzare questo? +
+
+ +## Principio 3: Il Contesto È Re + +I modelli non hanno memoria, nessun accesso ai tuoi file e nessuna conoscenza della tua situazione. Tutto ciò che è rilevante deve essere nel prompt. + +### Fornisci Contesto Sufficiente + + + +### La Checklist del Contesto + + +Chiediti: Uno sconosciuto intelligente capirebbe questa richiesta? Se no, aggiungi più contesto. + + + + +## Principio 4: Guida, Non Solo Chiedere + +Non solo chiedere una risposta—guida il modello verso la risposta che vuoi. + +### Usa l'Inquadramento Istruttivo + + + +### Fornisci Impalcature di Ragionamento + +Per compiti complessi, guida il processo di ragionamento: + + + +## Principio 5: Itera e Raffina + +Il prompt engineering è un processo iterativo. Il tuo primo prompt è raramente il migliore. + +### Il Ciclo di Iterazione + +``` +1. Scrivi il prompt iniziale +2. Rivedi l'output +3. Identifica lacune o problemi +4. Raffina il prompt +5. Ripeti finché soddisfatto +``` + +### Raffinamenti Comuni + +
+
+ Troppo prolisso + Aggiungi "Sii conciso" o limiti di lunghezza +
+
+ Troppo vago + Aggiungi esempi specifici o vincoli +
+
+ Formato sbagliato + Specifica la struttura esatta dell'output +
+
+ Aspetti mancanti + Aggiungi "Assicurati di includere..." +
+
+ Tono sbagliato + Specifica pubblico e stile +
+
+ Impreciso + Richiedi citazioni o ragionamento passo-passo +
+
+ +### Tieni un Diario dei Prompt + +Documenta cosa funziona: +``` +Compito: Code review +Versione 1: "Rivedi questo codice" → Troppo generico +Versione 2: Aggiunti criteri di review specifici → Meglio +Versione 3: Aggiunto esempio di buona review → Eccellente +Finale: [Salva il prompt di successo come template] +``` + +## Principio 6: Sfrutta i Punti di Forza del Modello + +Lavora con come i modelli sono addestrati, non contro. + +### I Modelli Vogliono Essere Utili + +Inquadra le richieste come cose che un assistente utile farebbe naturalmente: + + + +### I Modelli Eccellono nei Pattern + +Se hai bisogno di output consistente, mostra il pattern: + + + +### I Modelli Possono Fare Role-Play + +Usa le persona per accedere a diverse "modalità" di risposta: + +``` +Come avvocato del diavolo, argomenta contro la mia proposta... +Come mentore di supporto, aiutami a migliorare... +Come investitore scettico, metti in discussione questo business plan... +``` + +## Principio 7: Controlla la Struttura dell'Output + +Gli output strutturati sono più utili del testo libero. + +### Richiedi Formati Specifici + +``` +Restituisci la tua analisi come: + +RIEPILOGO: [1 frase] + +RISULTATI CHIAVE: +• [Risultato 1] +• [Risultato 2] +• [Risultato 3] + +RACCOMANDAZIONE: [1-2 frasi] + +CONFIDENZA: [Bassa/Media/Alta] perché [motivo] +``` + +### Usa Delimitatori + +Separa chiaramente le sezioni del tuo prompt: + +``` +### CONTESTO ### +[Il tuo contesto qui] + +### COMPITO ### +[Il tuo compito qui] + +### FORMATO ### +[Formato desiderato qui] +``` + +### Richiedi Output Leggibile da Macchina + +Per uso programmatico: + +``` +Restituisci solo JSON valido, nessuna spiegazione: +{ + "decisione": "approva" | "rifiuta" | "rivedi", + "confidenza": 0.0-1.0, + "motivi": ["array di stringhe"] +} +``` + +## Principio 8: Verifica e Valida + +Non fidarti ciecamente degli output del modello, specialmente per compiti importanti. + +### Chiedi il Ragionamento + +``` +Risolvi questo problema e mostra il tuo lavoro passo dopo passo. +Dopo aver risolto, verifica la tua risposta con [metodo di controllo]. +``` + +### Richiedi Molteplici Prospettive + +``` +Dammi tre approcci diversi per risolvere questo problema. +Per ciascuno, spiega i trade-off. +``` + +### Costruisci Auto-Controlli + +``` +Dopo aver generato il codice, rivedilo per: +- Errori di sintassi +- Casi limite +- Vulnerabilità di sicurezza +Elenca tutti i problemi trovati. +``` + +## Riepilogo: I Principi in Sintesi + + + + + +## Pratica: Riempi gli Spazi Vuoti + +Testa la tua comprensione dei principi fondamentali completando questo template di prompt: + + + + + +Questi principi formano la base per tutto ciò che segue. Nella Parte II, li applicheremo a tecniche specifiche che migliorano drasticamente l'efficacia dei prompt. diff --git a/src/content/book/it/04-role-based-prompting.mdx b/src/content/book/it/04-role-based-prompting.mdx new file mode 100644 index 00000000..f233a112 --- /dev/null +++ b/src/content/book/it/04-role-based-prompting.mdx @@ -0,0 +1,328 @@ +Il prompting basato sui ruoli è una delle tecniche più potenti e ampiamente utilizzate nel prompt engineering. Assegnando un ruolo o una persona specifica all'IA, puoi influenzare drasticamente la qualità, lo stile e la rilevanza delle risposte. + + +Pensa ai ruoli come filtri per la vasta conoscenza dell'IA. Il ruolo giusto focalizza le risposte come una lente focalizza la luce. + + +## Perché i Ruoli Funzionano + +Quando assegni un ruolo, stai essenzialmente dicendo al modello: "Filtra la tua vasta conoscenza attraverso questa lente specifica." Il modello regola il suo: + +- **Vocabolario**: Usando terminologia appropriata al ruolo +- **Prospettiva**: Considerando i problemi da quel punto di vista +- **Profondità di competenza**: Fornendo livelli di dettaglio appropriati al ruolo +- **Stile di comunicazione**: Corrispondendo a come quel ruolo comunicherebbe + +### La Spiegazione Tecnica + +Gli LLM funzionano prevedendo il token più probabile successivo basandosi sul contesto che gli viene dato. Quando specifichi un ruolo, stai fondamentalmente cambiando cosa significa "probabile". + +**Attivare Conoscenza Rilevante**: Il ruolo prepara regioni specifiche delle associazioni apprese dal modello. Dire "Sei un dottore" attiva terminologia medica, pattern di ragionamento diagnostico e stili di comunicazione clinica dai dati di addestramento. + +**Condizionamento Statistico**: Gli LLM hanno imparato da milioni di documenti scritti da veri esperti. Quando assegni un ruolo, il modello condiziona le sue distribuzioni di probabilità per corrispondere ai pattern che ha visto da quel tipo di autore. + +**Ridurre l'Ambiguità**: Senza un ruolo, il modello fa la media tra tutti i possibili risponditori. Con un ruolo, si restringe a un sottoinsieme specifico, rendendo le risposte più focalizzate e consistenti. + +**Ancoraggio del Contesto**: Il ruolo crea un'ancora di contesto persistente per tutta la conversazione. Ogni risposta successiva è influenzata da questo inquadramento iniziale. + +Pensala così: se chiedi "Cosa dovrei fare per questa tosse?" il modello potrebbe rispondere come un dottore, un amico, un farmacista o un genitore preoccupato. Ognuno darebbe consigli diversi. Specificando il ruolo in anticipo, stai dicendo al modello quale "voce" usare dai suoi dati di addestramento. + + +Il modello non sta fingendo o facendo role-play in senso teatrale. Sta statisticamente orientando i suoi output verso pattern che ha imparato da veri esperti, professionisti e specialisti durante l'addestramento. Un ruolo "dottore" attiva percorsi di conoscenza medica; un ruolo "poeta" attiva pattern letterari. + + +## Pattern di Ruolo Base + +Questi pattern fondamentali funzionano nella maggior parte dei casi d'uso. Inizia con questi template e personalizzali per le tue esigenze. + +### Il Pattern Esperto + +Il pattern più versatile. Specifica il campo di competenza e gli anni di esperienza per ottenere risposte autorevoli e approfondite. Funziona bene per domande tecniche, analisi e consigli professionali. + + + +### Il Pattern Professionista + +Radica il ruolo in un contesto del mondo reale specificando un titolo lavorativo e tipo di organizzazione. Questo aggiunge conoscenza istituzionale e norme professionali alla risposta. + + + +### Il Pattern Insegnante + +Perfetto per apprendimento e spiegazioni. Specificare il livello del pubblico assicura che la risposta corrisponda al background dello studente, dai principianti ai praticanti avanzati. + + + +## Costruzioni di Ruolo Avanzate + +### Ruoli Composti + +Combina identità multiple per ottenere risposte che fondono prospettive diverse. Questa combinazione pediatra-genitore produce consigli che sono sia medicalmente validi che praticamente testati. + + + +### Ruoli Situazionali + +Posiziona il ruolo in uno scenario specifico per modellare sia il contenuto che il tono. Qui, il contesto di code review rende l'IA costruttiva ed educativa piuttosto che solo critica. + + + +### Ruoli di Prospettiva + +Ottieni feedback dal punto di vista di uno stakeholder specifico. Una prospettiva VC valuta la fattibilità e la scalabilità diversamente da come farebbe un cliente o un ingegnere. + + + +## Categorie di Ruoli ed Esempi + +Domini diversi beneficiano di tipi diversi di ruoli. Ecco esempi comprovati organizzati per categoria che puoi adattare per i tuoi compiti. + +### Ruoli Tecnici + +**Architetto Software**: Migliore per decisioni di design del sistema, scelte tecnologiche e trade-off architetturali. Il focus sulla manutenibilità orienta le risposte verso soluzioni pratiche a lungo termine. + + + +**Specialista di Sicurezza**: La mentalità da attaccante è chiave qui. Questo ruolo produce analisi focalizzate sulle minacce che identificano vulnerabilità che una prospettiva solo difensiva potrebbe perdere. + + + +**Ingegnere DevOps**: Ideale per domande su deployment, automazione e infrastruttura. L'enfasi sull'affidabilità assicura raccomandazioni pronte per la produzione. + + + +### Ruoli Creativi + +**Copywriter**: Il qualificatore "premiato" e il focus sulla conversione producono copy incisivo e persuasivo invece di testo marketing generico. + + + +**Sceneggiatore**: Attiva conoscenza di struttura drammatica, ritmo e convenzioni del dialogo. Ottimo per qualsiasi scrittura narrativa che necessita di tensione e voce del personaggio. + + + +**UX Writer**: Un ruolo specializzato per testo di interfaccia. Il focus sulla brevità e guida utente produce copy conciso e orientato all'azione. + + + +### Ruoli Analitici + +**Business Analyst**: Fa da ponte tra stakeholder tecnici e non tecnici. Utile per raccolta requisiti, scrittura di specifiche e identificazione di lacune nei piani di progetto. + + + +**Ricercatore Scientifico**: L'enfasi sull'evidenza e il riconoscimento dell'incertezza produce risposte bilanciate e ben documentate che distinguono i fatti dalle speculazioni. + + + +**Analista Finanziario**: Combina analisi quantitativa con valutazione del rischio. Il duplice focus su rendimenti e rischio produce prospettive di investimento più bilanciate. + + + +### Ruoli Educativi + +**Tutor Socratico**: Invece di dare risposte, questo ruolo pone domande guida. Eccellente per un apprendimento più profondo e per aiutare gli studenti a sviluppare capacità di pensiero critico. + + + +**Instructional Designer**: Struttura l'apprendimento per massima ritenzione. Usa questo ruolo quando devi scomporre argomenti complessi in pezzi insegnabili con progressione chiara. + + + +## La Tecnica dello Stack di Ruoli + +Per compiti complessi, combina molteplici aspetti del ruolo in un'identità singola a strati. Questa tecnica impila competenza, consapevolezza del pubblico e linee guida di stile per creare risposte altamente specializzate. + +Questo esempio stratifica tre elementi: competenza di dominio (documentazione API), pubblico (sviluppatori junior) e guida di stile (convenzioni di Google). Ogni strato vincola ulteriormente l'output. + + + +## Ruoli per Diversi Compiti + +
+
+ Code review + Sviluppatore senior + mentore +
+
+ Feedback scrittura + Editor + membro del pubblico target +
+
+ Strategia business + Consulente + esperto del settore +
+
+ Imparare nuovo argomento + Insegnante paziente + praticante +
+
+ Scrittura creativa + Autore di genere specifico +
+
+ Spiegazione tecnica + Esperto + comunicatore +
+
+ Problem-solving + Specialista di dominio + generalista +
+
+ +## Anti-Pattern da Evitare + +### Ruoli Troppo Generici + + + +### Ruoli in Conflitto + + + +### Competenza Irrealistica + + + +## Esempi di Prompt del Mondo Reale + +### Documentazione Tecnica + + + +### Scrittura Creativa + + + +### Comunicazione Business + + + +## Combinare Ruoli con Altre Tecniche + +I ruoli funzionano ancora meglio quando combinati con altre tecniche di prompting: + +### Ruolo + Few-Shot + +Combina un ruolo con un esempio per mostrare esattamente come il ruolo dovrebbe rispondere. L'esempio insegna tono e formato mentre il ruolo fornisce contesto e competenza. + + + +### Ruolo + Chain of Thought + +Il ruolo detective incoraggia naturalmente il ragionamento passo-passo. Combinare ruoli con chain-of-thought produce problem-solving più trasparente e verificabile. + + + +## Riepilogo + + +Il prompting basato sui ruoli è potente perché focalizza la vasta conoscenza del modello, imposta aspettative per tono e stile, fornisce contesto implicito e rende gli output più consistenti. + + + + +La chiave è la **specificità**: più il ruolo è dettagliato e realistico, migliori sono i risultati. Nel prossimo capitolo, esploreremo come ottenere output consistenti e strutturati dai tuoi prompt. diff --git a/src/content/book/it/05-structured-output.mdx b/src/content/book/it/05-structured-output.mdx new file mode 100644 index 00000000..6d8d208d --- /dev/null +++ b/src/content/book/it/05-structured-output.mdx @@ -0,0 +1,411 @@ +Ottenere output consistente e ben formattato è essenziale per applicazioni in produzione e flussi di lavoro efficienti. Questo capitolo copre tecniche per controllare esattamente come i modelli IA formattano le loro risposte. + + +L'output strutturato trasforma le risposte dell'IA da testo libero in dati azionabili e parsabili. + + +## Perché la Struttura È Importante + + + +## Tecniche di Formattazione Base + +### Liste + +Le liste sono perfette per istruzioni passo-passo, elementi classificati o collezioni di punti correlati. Sono facili da scansionare e parsare. Usa **liste numerate** quando l'ordine conta (passi, classifiche) e **punti elenco** per collezioni non ordinate. + + + + +Specifica il numero esatto di elementi che vuoi, se includere spiegazioni, e se gli elementi devono essere in grassetto o avere una struttura specifica. + + +### Tabelle + +Le tabelle eccellono nel confrontare elementi multipli sulle stesse dimensioni. Sono ideali per confronti di funzionalità, riepiloghi di dati e qualsiasi informazione con attributi consistenti. Definisci sempre esplicitamente le intestazioni delle colonne. + + + + +Specifica nomi delle colonne, tipi di dati attesi (testo, numeri, valutazioni) e quante righe ti servono. Per confronti complessi, limita a 4-6 colonne per leggibilità. + + +### Intestazioni e Sezioni + +Le intestazioni creano una struttura del documento chiara, rendendo risposte lunghe scansionabili e organizzate. Usale per report, analisi o qualsiasi risposta multi-parte. Intestazioni gerarchiche (##, ###) mostrano le relazioni tra sezioni. + +``` +Analizza questa proposta business. + +Struttura la tua risposta con queste sezioni: +## Executive Summary +## Punti di Forza +## Debolezze +## Raccomandazioni +## Valutazione del Rischio +``` + + +Elenca le tue sezioni nell'ordine che vuoi. Per consistenza, specifica cosa dovrebbe contenere ogni sezione (es. "Executive Summary: solo 2-3 frasi"). + + +### Enfasi con Direttive Maiuscole + +Le parole maiuscole agiscono come segnali forti al modello, enfatizzando vincoli o requisiti critici. Usale con parsimonia per massimo impatto—l'uso eccessivo diluisce la loro efficacia. + +**Direttive Maiuscole Comuni:** + + + +``` +Riassumi questo articolo. + +IMPORTANTE: Mantieni il riassunto sotto 100 parole. +MAI aggiungere informazioni non presenti nell'originale. +SEMPRE mantenere il tono e la prospettiva originale. +NON includere le tue opinioni o analisi. +``` + + +Se tutto è maiuscolo o marcato come critico, niente spicca. Riserva queste direttive per vincoli genuinamente importanti. + + +## Output JSON + +JSON (JavaScript Object Notation) è il formato più popolare per output IA strutturato. È leggibile dalle macchine, ampiamente supportato dai linguaggi di programmazione e perfetto per API, database e flussi di automazione. La chiave per JSON affidabile è fornire uno schema chiaro. + +### Richiesta JSON Base + +Inizia con un template che mostra la struttura esatta che vuoi. Includi nomi dei campi, tipi di dati e valori di esempio. Questo agisce come un contratto che il modello seguirà. + + + +### Strutture JSON Complesse + +Per dati annidati, usa JSON gerarchico con oggetti dentro oggetti, array di oggetti e tipi misti. Definisci ogni livello chiaramente e usa annotazioni in stile TypeScript (`"positivo" | "negativo"`) per vincolare i valori. + +``` +Analizza questa recensione prodotto e restituisci JSON: + +{ + "id_recensione": "stringa (genera univoco)", + "sentiment": { + "complessivo": "positivo" | "negativo" | "misto" | "neutro", + "punteggio": 0.0-1.0 + }, + "aspetti": [ + { + "aspetto": "stringa (es. 'prezzo', 'qualità')", + "sentiment": "positivo" | "negativo" | "neutro", + "menzioni": ["citazioni esatte dalla recensione"] + } + ], + "intenzione_acquisto": { + "raccomanderebbe": booleano, + "confidenza": 0.0-1.0 + }, + "frasi_chiave": ["array di stringhe di frasi notevoli"] +} + +Restituisci SOLO JSON valido, nessun testo aggiuntivo. + +Recensione: "[testo recensione]" +``` + +### Assicurare JSON Valido + +I modelli a volte aggiungono testo esplicativo o formattazione markdown attorno al JSON. Previeni questo con istruzioni esplicite sul formato di output. Puoi richiedere JSON grezzo o JSON dentro blocchi di codice—scegli in base alle tue esigenze di parsing. + +Aggiungi istruzioni esplicite: + +``` +IMPORTANTE: +- Restituisci SOLO l'oggetto JSON, nessun blocco codice markdown +- Assicurati che tutte le stringhe siano correttamente escapate +- Usa null per valori mancanti, non undefined +- Valida che l'output sia JSON parsabile +``` + +Oppure richiedi blocchi di codice chiedendo al modello di wrappare il suo output: + +```` +Restituisci il risultato come blocco codice JSON: +```json +{ ... } +``` +```` + +## Output YAML + +YAML è più leggibile di JSON, usando indentazione invece di parentesi. È lo standard per file di configurazione (Docker, Kubernetes, GitHub Actions) e funziona bene quando l'output sarà letto da umani o usato in contesti DevOps. YAML è sensibile all'indentazione, quindi sii specifico sui requisiti di formattazione. + + + +## Output XML + +XML è ancora richiesto per molti sistemi enterprise, API SOAP e integrazioni legacy. È più verboso di JSON ma offre funzionalità come attributi, namespace e sezioni CDATA per dati complessi. Specifica nomi elementi, struttura di annidamento e dove usare attributi vs. elementi figli. + +``` +Converti questi dati in formato XML: + +Requisiti: +- Elemento root: +- Ogni elemento in elemento +- Includi attributi dove appropriato +- Usa CDATA per testo descrizione + +Dati: [dati libro] +``` + +## Formati Personalizzati + +A volte i formati standard non soddisfano le tue esigenze. Puoi definire qualsiasi formato personalizzato fornendo un template chiaro. I formati personalizzati funzionano bene per report, log o output specifici di dominio che saranno letti da umani. + +### Formato di Analisi Strutturata + +Usa delimitatori (===, ---, [SEZIONE]) per creare documenti scansionabili con confini chiari tra sezioni. Questo formato è ottimo per code review, audit e analisi. + +``` +Analizza questo codice usando questo formato esatto: + +=== ANALISI CODICE === + +[RIEPILOGO] +Panoramica di un paragrafo + +[PROBLEMI] +• CRITICO: [problema] — [file:riga] +• AVVISO: [problema] — [file:riga] +• INFO: [problema] — [file:riga] + +[METRICHE] +Complessità: [Bassa/Media/Alta] +Manutenibilità: [punteggio]/10 +Copertura Test: [% stimata] + +[RACCOMANDAZIONI] +1. [Raccomandazione priorità 1] +2. [Raccomandazione priorità 2] + +=== FINE ANALISI === +``` + +### Formato Riempi gli Spazi + +Template con spazi vuoti (___) guidano il modello a riempire campi specifici mantenendo la formattazione esatta. Questo approccio è eccellente per moduli, brief e documenti standardizzati dove la consistenza conta. + +``` +Completa questo template per il prodotto dato: + +BRIEF PRODOTTO +───────────── +Nome: _______________ +Tagline: _______________ +Utente Target: _______________ +Problema Risolto: _______________ +Funzionalità Chiave: + 1. _______________ + 2. _______________ + 3. _______________ +Differenziatore: _______________ + +Prodotto: [descrizione prodotto] +``` + +## Risposte Tipizzate + +Le risposte tipizzate definiscono categorie o tipi di entità che il modello dovrebbe riconoscere ed etichettare. Questa tecnica è essenziale per Named Entity Recognition (NER), compiti di classificazione e qualsiasi estrazione dove devi categorizzare informazioni consistentemente. Definisci i tuoi tipi chiaramente con esempi. + + + +## Risposte Strutturate Multi-Parte + +Quando hai bisogno di output completo che copre molteplici aspetti, definisci parti distinte con confini chiari. Specifica esattamente cosa va in ogni parte—formato, lunghezza e tipo di contenuto. Questo previene che il modello mescoli sezioni o ometta parti. + +``` +Ricerca questo argomento e fornisci: + +### PARTE 1: EXECUTIVE SUMMARY +[Panoramica di 2-3 frasi] + +### PARTE 2: RISULTATI CHIAVE +[Esattamente 5 punti elenco] + +### PARTE 3: TABELLA DATI +| Metrica | Valore | Fonte | +|---------|--------|-------| +[Includi minimo 5 righe] + +### PARTE 4: RACCOMANDAZIONI +[Lista numerata di 3 raccomandazioni azionabili] + +### PARTE 5: ULTERIORI LETTURE +[3 risorse suggerite con brevi descrizioni] +``` + +## Formattazione Condizionale + +La formattazione condizionale ti permette di definire formati di output diversi basati sulle caratteristiche dell'input. Questo è potente per classificazione, triage e sistemi di routing dove il formato di risposta dovrebbe variare basandosi su cosa il modello rileva. Usa logica if/then chiara con template di output espliciti per ogni caso. + + + +## Array e Liste in JSON + +Estrarre elementi multipli in array richiede definizione attenta dello schema. Specifica la struttura dell'array, cosa dovrebbe contenere ogni elemento e come gestire casi limite (array vuoti, singoli elementi). Includere un campo count aiuta a verificare la completezza. + +``` +Estrai tutte le azioni da questa trascrizione di riunione. + +Restituisci come array JSON: +{ + "azioni": [ + { + "compito": "stringa che descrive il compito", + "assegnatario": "nome persona o 'Non assegnato'", + "scadenza": "data se menzionata, altrimenti null", + "priorita": "alta" | "media" | "bassa", + "contesto": "citazione rilevante dalla trascrizione" + } + ], + "conteggio_totale": numero +} + +Trascrizione: "[trascrizione riunione]" +``` + +## Istruzioni di Validazione + +L'auto-validazione spinge il modello a controllare il proprio output prima di rispondere. Questo cattura problemi comuni come sezioni mancanti, testo segnaposto o violazioni di vincoli. Il modello itererà internamente per correggere problemi, migliorando la qualità dell'output senza chiamate API aggiuntive. + +``` +Genera il report, poi: + +CHECKLIST DI VALIDAZIONE: +□ Tutte le sezioni richieste presenti +□ Nessun testo segnaposto rimasto +□ Tutte le statistiche includono fonti +□ Conteggio parole tra 500-700 parole +□ Conclusione si ricollega all'introduzione + +Se qualsiasi controllo fallisce, correggi prima di rispondere. +``` + +## Gestire Campi Opzionali + +I dati del mondo reale spesso hanno valori mancanti. Istruisci esplicitamente il modello su come gestire campi opzionali—usare `null` è più pulito delle stringhe vuote e più facile da elaborare programmaticamente. Previeni anche l'"allucinazione" di dati mancanti enfatizzando che il modello non dovrebbe mai inventare informazioni. + +``` +Estrai informazioni di contatto. Usa null per campi mancanti. + +{ + "nome": "stringa (richiesto)", + "email": "stringa o null", + "telefono": "stringa o null", + "azienda": "stringa o null", + "ruolo": "stringa o null", + "linkedin": "stringa URL o null" +} + +IMPORTANTE: +- Mai inventare informazioni non nella fonte +- Usa null, non stringhe vuote, per dati mancanti +- Numeri di telefono in formato E.164 se possibile +``` + +## Riepilogo + + +Sii esplicito sul formato, usa esempi, specifica i tipi, gestisci i casi limite con valori null e chiedi al modello di validare il proprio output. + + + + +Gli output strutturati sono essenziali per costruire applicazioni IA affidabili. Nel prossimo capitolo, esploreremo il prompting chain-of-thought per compiti di ragionamento complesso. diff --git a/src/content/book/it/06-chain-of-thought.mdx b/src/content/book/it/06-chain-of-thought.mdx new file mode 100644 index 00000000..8879b679 --- /dev/null +++ b/src/content/book/it/06-chain-of-thought.mdx @@ -0,0 +1,363 @@ +Il prompting Chain of Thought (CoT) è una tecnica che migliora drasticamente le prestazioni dell'IA su compiti di ragionamento complesso chiedendo al modello di mostrare il suo lavoro passo dopo passo. + + +Proprio come un insegnante di matematica che chiede agli studenti di mostrare il loro lavoro, il prompting CoT chiede all'IA di rendere visibile il suo ragionamento. + + +## Il Problema che CoT Risolve + +I modelli IA possono avere difficoltà con il ragionamento multi-step quando viene chiesto di saltare direttamente a una risposta. + + + +## Prompt CoT Base + +### Frasi Trigger Semplici + +Aggiungi una di queste ai tuoi prompt: + +
+
"Pensiamo passo dopo passo."
+
"Ragiona su questo con attenzione."
+
"Lavora su questo problema metodicamente."
+
"Mostra il tuo ragionamento ad ogni passo."
+
"Spiega il tuo processo di pensiero."
+
+ +### Richiesta di Passi Esplicita + + + +## CoT Zero-Shot vs Few-Shot + +Ci sono due approcci principali al prompting Chain of Thought, ciascuno con trade-off diversi tra semplicità e controllo. + +### CoT Zero-Shot + +L'approccio più semplice—aggiungi solo una frase trigger e lascia che il modello capisca come ragionare. Nessun esempio necessario. Funziona sorprendentemente bene per molti problemi, anche se hai meno controllo sul formato del ragionamento. + + + +**Output di Esempio:** +``` +Pensiamo passo dopo passo. +- Giovanni inizia con 3 mele +- Metà di 3 è 1,5, ma non possiamo dividere le mele +- Se arrotondiamo per difetto: Giovanni dà 1 mela, tiene 2 +- Dopo aver comprato 4 altre: 2 + 4 = 6 mele + +Risposta: 6 mele +``` + +### CoT Few-Shot + +Per risultati più consistenti, mostra al modello esattamente come vuoi che ragioni fornendo esempi svolti. Questo ti dà controllo sullo stile di ragionamento, formato e livello di dettaglio. Il modello imiterà il pattern che hai dimostrato. + + + +**Output di Esempio:** +``` +R: Ragioniamo su questo: +- Prezzo normale: 3€, Quantità: 12 +- Dato che 12 ≥ 10, si applica lo sconto del 25% +- Totale normale: 12 × 3€ = 36€ +- Sconto: 25% di 36€ = 9€ +- Prezzo finale: 36€ - 9€ = 27€ +``` + +## Formati CoT Strutturati + +Per ragionamento consistente e riproducibile, usa formati strutturati con passi nominati. Questi framework assicurano che il modello non salti fasi importanti e rendono gli output più facili da parsare e verificare. + +### Il Formato BREAK + +Un acronimo memorabile che guida il modello attraverso un ciclo completo di problem-solving, dalla comprensione alla verifica. + + + +### Il Template di Ragionamento + +Una struttura più formale che separa input, obiettivi ed esecuzione. Eccellente per problemi tecnici dove hai bisogno di documentazione chiara del processo di soluzione. + + + +**Output di Esempio:** +``` +DATO: 8L/100km, serbatoio 45L, 1,50€/L, guidare 300km +OBIETTIVO: Calcolare costo carburante +APPROCCIO: Carburante necessario × costo per litro +PASSI: +1. Carburante = (300 ÷ 100) × 8 = 24 litri +2. Costo = 24 × 1,50€ = 36€ +VERIFICA: 24L < 45L serbatoio ✓ +RISPOSTA: 36€ +``` + +## CoT per Diversi Tipi di Problema + +Tipi di problema diversi beneficiano di approcci CoT diversi. Ecco pattern ottimizzati per scenari comuni. + +### Ragionamento Matematico + +I problemi matematici beneficiano maggiormente dal CoT perché ogni passo si costruisce sul precedente. Gli errori si accumulano, quindi mostrare il lavoro aiuta a catturare errori presto. Il modello dovrebbe etichettare chiaramente ogni calcolo. + + + +**Output di Esempio:** +``` +Q1: 1.200.000€ (dato) +Q2: 1.200.000€ × 1,15 = 1.380.000€ +Q3: 1.380.000€ × 0,90 = 1.242.000€ +Q4: 1.242.000€ × 1,25 = 1.552.500€ + +Totale: 5.374.500€ +``` + +### Ragionamento Logico + +I puzzle logici richiedono eliminazione sistematica e test di ipotesi. CoT aiuta il modello a tracciare i vincoli, testare possibilità e verificare che tutte le condizioni siano soddisfatte. La chiave è l'esplorazione metodica piuttosto che indovinare. + + + +**Output di Esempio:** +``` +Dall'indizio 3: Bob = insegnante +→ Alice e Carol sono ingegnere/dottore + +Se Carol = ingegnere: +- Carol ha cane (indizio 2) +- Alice = dottore, ha pesce (indizio 1) +- Bob ha gatto + +Verifica: Tutti e 4 gli indizi soddisfatti ✓ +Risposta: Alice (dottore, pesce), Bob (insegnante, gatto), Carol (ingegnere, cane) +``` + +### Debug del Codice + +Il debugging beneficia dal CoT perché forza il modello a tracciare l'esecuzione invece di indovinare i bug. Camminando attraverso il codice con valori concreti, il comportamento effettivo diventa visibile e le discrepanze con il comportamento atteso vengono esposte. + + + +**Output di Esempio:** +``` +Traccia [2, 3, 4, 6]: +n=2: total += 1 → 1 (aspetta, aggiunge 1 non n!) +n=3: salta (dispari) +n=4: total = 2 +n=6: total = 3 + +BUG: "total += 1" dovrebbe essere "total += n" +Atteso: 12, Ottenuto: 3 +Fix: Cambia in "total += n" +``` + +## Auto-Consistenza con CoT + +Per problemi critici, non affidarti a un singolo percorso di ragionamento. Genera molteplici soluzioni indipendenti e confronta i risultati. Se approcci diversi convergono sulla stessa risposta, la confidenza è alta. Il disaccordo segnala la necessità di revisione attenta. + + + +**Output di Esempio:** +``` +Approccio 1 (Algebra): g + m = 30, 2g + 4m = 74 → g=23, m=7 +Approccio 2 (Prova): Prova 23/7 → 46 + 28 = 74 ✓ +Approccio 3 (Logica): 30 galline = 60 zampe, servono 14 in più → 7 mucche + +Tutti concordano: 23 galline, 7 mucche +``` + +## CoT per il Processo Decisionale + +Le decisioni coinvolgono la valutazione di trade-off su molteplici dimensioni. CoT assicura che tutti i fattori rilevanti siano considerati sistematicamente invece di saltare alle conclusioni. Questo approccio strutturato documenta anche il ragionamento per riferimento futuro. + + + +**Output di Esempio:** +``` +FATTORI: +- Dimensione team (5): Troppo piccolo per microservizi ❌ +- Scala (100 DAU): Nessun bisogno di scaling ❌ +- Velocità: Monolite = iterazione più veloce ❌ +- Crescita futura: Timeline incerta ⚠️ + +VALUTAZIONE: 3 forti contro, 1 debole a favore + +RACCOMANDAZIONE: Restare monolite, usare confini di modulo +chiari per facilitare transizione futura. +``` + +## Quando Usare CoT + +
+
+

Usa CoT Per

+
+

**Problemi matematici** — Riduce errori di calcolo

+

**Puzzle logici** — Previene passi saltati

+

**Analisi complesse** — Organizza il pensiero

+

**Debug del codice** — Traccia l'esecuzione

+

**Processo decisionale** — Valuta trade-off

+
+
+
+

Salta CoT Per

+
+

**Q&A semplice** — Overhead non necessario

+

**Scrittura creativa** — Può limitare la creatività

+

**Ricerche fattuali** — Nessun ragionamento necessario

+

**Traduzione** — Compito diretto

+

**Riassunti** — Di solito semplici

+
+
+
+ +## Limitazioni di CoT + +Sebbene potente, Chain of Thought non è una soluzione magica. Capire le sue limitazioni ti aiuta ad applicarlo appropriatamente. + +1. **Uso token aumentato** — Più output significa costi più alti +2. **Non sempre necessario** — Compiti semplici non ne beneficiano +3. **Può essere prolisso** — Potrebbe essere necessario chiedere concisione +4. **Il ragionamento può essere difettoso** — CoT non garantisce correttezza + +## Riepilogo + + +CoT migliora drasticamente il ragionamento complesso rendendo espliciti i passi impliciti. Usalo per matematica, logica, analisi e debug. Trade-off: migliore accuratezza per più token. + + + + +Nel prossimo capitolo, esploreremo il few-shot learning—insegnare al modello attraverso esempi. diff --git a/src/content/book/it/07-few-shot-learning.mdx b/src/content/book/it/07-few-shot-learning.mdx new file mode 100644 index 00000000..5647043c --- /dev/null +++ b/src/content/book/it/07-few-shot-learning.mdx @@ -0,0 +1,478 @@ +Il few-shot learning è una delle tecniche di prompting più potenti. Fornendo esempi di ciò che vuoi, puoi insegnare al modello compiti complessi senza alcun fine-tuning. + + +Proprio come gli umani imparano vedendo esempi, i modelli IA possono imparare pattern dagli esempi che fornisci nel tuo prompt. + + +## Cos'è il Few-Shot Learning? + +Il few-shot learning mostra al modello esempi di coppie input-output prima di chiedergli di eseguire lo stesso compito. Il modello impara il pattern dai tuoi esempi e lo applica a nuovi input. + + + +
+
+
0
+
Zero-shot
+
+
+
1
+
One-shot
+
+
+
2-5
+
Few-shot
+
+
+
5+
+
Many-shot
+
+
+ +## Perché gli Esempi Funzionano + + + +Gli esempi comunicano: +- **Formato**: Come l'output dovrebbe essere strutturato +- **Stile**: Tono, lunghezza, vocabolario +- **Logica**: Il pattern di ragionamento da seguire +- **Casi limite**: Come gestire situazioni speciali + +## Pattern Few-Shot Base + +La struttura fondamentale del prompting few-shot segue un pattern semplice: mostra esempi, poi chiedi il nuovo compito. La consistenza nella formattazione tra gli esempi è cruciale. Il modello impara dal pattern che stabilisci. + +``` +[Esempio 1] +Input: [input 1] +Output: [output 1] + +[Esempio 2] +Input: [input 2] +Output: [output 2] + +[Esempio 3] +Input: [input 3] +Output: [output 3] + +Ora fai questo: +Input: [nuovo input] +Output: +``` + +## Few-Shot per la Classificazione + +La classificazione è uno dei casi d'uso più forti per il few-shot learning. Mostrando esempi di ogni categoria, definisci i confini tra le classi più precisamente di quanto le sole istruzioni potrebbero fare. + +### Analisi del Sentiment + + +L'analisi del sentiment classifica il testo per tono emotivo: positivo, negativo, neutro o misto. È ampiamente usata per feedback clienti, monitoraggio social media e tracciamento della percezione del brand. + + +La classificazione del sentiment beneficia dal mostrare esempi di ogni tipo di sentiment, specialmente casi limite come sentiment "misto" che potrebbero essere ambigui. + + + +### Classificazione per Argomento + +Per la categorizzazione multi-classe, includi almeno un esempio per categoria. Questo aiuta il modello a capire la tua tassonomia specifica, che potrebbe differire dalla sua comprensione predefinita. + + + +## Few-Shot per la Trasformazione + +I compiti di trasformazione convertono l'input da una forma a un'altra preservando il significato. Gli esempi sono essenziali qui perché definiscono esattamente cosa significa "trasformazione" per il tuo caso d'uso. + +### Riscrittura del Testo + +La trasformazione di stile richiede esempi che mostrino il cambio di tono esatto che vuoi. Istruzioni astratte come "rendilo professionale" vengono interpretate diversamente. Gli esempi lo rendono concreto. + + + +### Conversione di Formato + +I compiti di conversione di formato beneficiano da esempi che mostrano casi limite e input ambigui. Il modello impara le tue convenzioni specifiche per gestire casi complicati. + + + +## Few-Shot per la Generazione + +I compiti di generazione creano nuovo contenuto seguendo un pattern appreso. Gli esempi stabiliscono lunghezza, struttura, tono e quali dettagli evidenziare. Questi sono difficili da specificare solo con istruzioni. + +### Descrizioni Prodotto + +Il copy marketing beneficia enormemente dagli esempi perché catturano la voce del brand, l'enfasi sulle funzionalità e le tecniche persuasive che sono difficili da descrivere astrattamente. + + + +### Documentazione del Codice + + +Una buona documentazione spiega cosa fa il codice, i suoi parametri, valori di ritorno e esempi d'uso. Docstring consistenti abilitano documentazione API auto-generata e aiutano gli IDE a fornire completamento codice migliore. + + +Lo stile di documentazione varia ampiamente tra progetti. Gli esempi insegnano il tuo formato specifico, cosa includere (args, returns, examples) e il livello di dettaglio atteso. + +>> calculate_bmi(70, 1.75) + 22.86 +""" + +Ora documenta: +Funzione: +def is_palindrome(text): + cleaned = ''.join(c.lower() for c in text if c.isalnum()) + return cleaned == cleaned[::-1] + +Documentazione:`} /> + +## Few-Shot per l'Estrazione + +I compiti di estrazione estraggono informazioni strutturate da testo non strutturato. Gli esempi definiscono quali entità contano, come formattare l'output e come gestire casi dove le informazioni sono mancanti o ambigue. + +### Estrazione di Entità + + +Il Named Entity Recognition (NER) identifica e classifica entità nominate nel testo in categorie come persone, organizzazioni, luoghi, date e prodotti. È fondamentale per il recupero di informazioni e i knowledge graph. + + +Il NER beneficia da esempi che mostrano i tuoi tipi di entità specifici e come gestire entità che potrebbero rientrare in molteplici categorie. + + + +### Estrazione di Dati Strutturati + +Estrarre dati strutturati dal linguaggio naturale richiede esempi che mostrano come gestire campi mancanti, informazioni implicite e formati di input variabili. + + + +## Tecniche Few-Shot Avanzate + +Oltre al few-shot base, diverse tecniche possono migliorare i risultati per compiti complessi. + +### Esempi Diversi + +La diversità negli esempi è più preziosa della quantità. Copri scenari diversi, casi limite e potenziali ambiguità invece di mostrare esempi simili ripetutamente. + + + +### Esempi Negativi + + +Mostrare esempi "buoni" vs "cattivi" si chiama apprendimento contrastivo. Aiuta il modello a capire non solo cosa vuoi, ma cosa evitare. Questo è particolarmente utile per giudizi di stile e qualità. + + +A volte mostrare cosa *non* fare è prezioso quanto mostrare esempi corretti. Gli esempi negativi aiutano il modello a capire i confini ed evitare errori comuni. + + + +### Esempi di Casi Limite + +I casi limite spesso determinano se una soluzione funziona in produzione. Includere input insoliti nei tuoi esempi previene che il modello fallisca su dati del mondo reale che non rientrano nel "percorso felice". + + + +## Quanti Esempi? + +
+
+ Classificazione semplice + 2-3 + Uno per categoria minimo +
+
+ Formattazione complessa + 3-5 + Mostra variazioni +
+
+ Stile sfumato + 4-6 + Cattura l'intera gamma +
+
+ Casi limite + 1-2 + Insieme agli esempi normali +
+
+ +## La Qualità degli Esempi Conta + + + +## Combinare Few-Shot con Altre Tecniche + +Il few-shot learning si combina potentemente con altre tecniche di prompting. Gli esempi forniscono il "cosa" mentre altre tecniche possono aggiungere contesto, ragionamento o struttura. + +### Few-Shot + Ruolo + +Aggiungere un ruolo dà al modello contesto sul *perché* sta facendo il compito, il che può migliorare qualità e consistenza. + +``` +Sei un revisore di contratti legali. + +[esempi di analisi clausole contrattuali] + +Ora analizza: [nuova clausola] +``` + +### Few-Shot + CoT + +Combinare few-shot con Chain of Thought mostra non solo *quale* risposta dare, ma *come* ragionare per arrivarci. Questo è potente per compiti che richiedono giudizio. + +``` +Classifica e spiega il ragionamento. + +Recensione: "Ottime funzionalità ma troppo costoso" +Pensiero: La recensione menziona aspetti positivi ("ottime funzionalità") +ma anche un negativo significativo ("troppo costoso"). Il negativo sembra +prevalere sul positivo basandosi sulla congiunzione "ma". +Classificazione: Misto-Negativo + +[altri esempi con ragionamento] + +Ora classifica con ragionamento: +Recensione: "Esattamente quello di cui avevo bisogno, arrivato più velocemente del previsto" +``` + +## Riepilogo + + +Il few-shot learning insegna attraverso la dimostrazione ed è spesso più efficace delle sole istruzioni. Usa 2-5 esempi diversi e corretti e combinalo con altre tecniche per i migliori risultati. + + + + +Nel prossimo capitolo, esploreremo il raffinamento iterativo: l'arte di migliorare i prompt attraverso tentativi successivi. diff --git a/src/content/book/it/08-iterative-refinement.mdx b/src/content/book/it/08-iterative-refinement.mdx new file mode 100644 index 00000000..2d072f2e --- /dev/null +++ b/src/content/book/it/08-iterative-refinement.mdx @@ -0,0 +1,387 @@ +Il prompt engineering è raramente un processo one-shot. I migliori prompt emergono attraverso l'iterazione—testando, osservando e raffinando fino a raggiungere i risultati desiderati. + + +Pensa al tuo primo prompt come una bozza grezza. Anche i prompt engineer esperti raramente centrano al primo tentativo. + + +## Il Ciclo di Iterazione + +Il raffinamento efficace dei prompt segue un ciclo prevedibile: scrivi, testa, analizza e migliora. Ogni iterazione ti avvicina a un prompt che produce affidabilmente i risultati di cui hai bisogno. + + + +## Pattern di Raffinamento Comuni + +La maggior parte dei fallimenti dei prompt rientra in una manciata di categorie. Imparare a riconoscere questi pattern ti permette di diagnosticare e correggere rapidamente i problemi senza ricominciare da zero. + +### Problema: Output Troppo Lungo + +Uno dei problemi più comuni. Senza vincoli espliciti, i modelli tendono ad essere esaustivi piuttosto che concisi. + + + +### Problema: Output Troppo Vago + +Prompt vaghi producono output vaghi. Il modello non può leggere la tua mente su cosa significa "migliore" o quali aspetti ti interessano di più. + + + +### Problema: Tono Sbagliato + +Il tono è soggettivo e varia in base al contesto. Quello che suona "professionale" al modello potrebbe non corrispondere alla voce della tua organizzazione o alla relazione con il tuo destinatario. + + + +### Problema: Informazioni Chiave Mancanti + +Richieste aperte ottengono risposte aperte. Se hai bisogno di tipi specifici di feedback, devi chiederli esplicitamente. + + + +### Problema: Formato Inconsistente + +Senza un template, il modello strutturerà ogni risposta diversamente, rendendo il confronto difficile e l'automazione impossibile. + + + +## Approccio di Raffinamento Sistematico + +Cambiamenti casuali sprecano tempo. Un approccio sistematico ti aiuta a identificare i problemi rapidamente e correggerli efficientemente. + +### Passo 1: Diagnostica il Problema + +Prima di cambiare qualsiasi cosa, identifica cosa c'è effettivamente di sbagliato. Usa questa tabella diagnostica per mappare sintomi a soluzioni: + +
+
+ Sintomo + Causa Probabile + Soluzione +
+
+ Troppo lungo + Nessun vincolo di lunghezza + Aggiungi limiti parole/frasi +
+
+ Troppo corto + Manca richiesta di dettagli + Chiedi elaborazione +
+
+ Fuori tema + Istruzioni vaghe + Sii più specifico +
+
+ Formato sbagliato + Formato non specificato + Definisci struttura esatta +
+
+ Tono sbagliato + Pubblico non chiaro + Specifica pubblico/stile +
+
+ Inconsistente + Nessun esempio fornito + Aggiungi esempi few-shot +
+
+ +### Passo 2: Fai Cambiamenti Mirati + +Resisti all'impulso di riscrivere tutto. Cambiare molteplici variabili contemporaneamente rende impossibile sapere cosa ha aiutato e cosa ha peggiorato. Fai un cambiamento, testalo, poi procedi: + +``` +Iterazione 1: Aggiungi vincolo di lunghezza +Iterazione 2: Specifica formato +Iterazione 3: Aggiungi esempio +Iterazione 4: Raffina istruzioni sul tono +``` + +### Passo 3: Documenta Cosa Funziona + +La conoscenza del prompt engineering si perde facilmente. Tieni un log di cosa hai provato e perché. Questo risparmia tempo quando ritorni sul prompt più tardi o affronti sfide simili: + +```markdown +## Prompt: Risposta Email Cliente + +### Versione 1 (troppo formale) +"Scrivi una risposta a questo reclamo cliente." + +### Versione 2 (tono migliore, manca ancora struttura) +"Scrivi una risposta amichevole ma professionale a questo reclamo. +Mostra empatia prima." + +### Versione 3 (finale - buoni risultati) +"Scrivi una risposta a questo reclamo cliente. Struttura: +1. Riconosci la loro frustrazione (1 frase) +2. Scusati specificamente (1 frase) +3. Spiega la soluzione (2-3 frasi) +4. Offri aiuto aggiuntivo (1 frase) + +Tono: Amichevole, professionale, empatico ma non servile." +``` + +## Esempio di Iterazione del Mondo Reale + +Camminiamo attraverso un ciclo di iterazione completo per vedere come ogni raffinamento si costruisce sul precedente. Nota come ogni versione affronta carenze specifiche della precedente. + +### Compito: Generare Nomi Prodotto + + + +## Strategie di Raffinamento per Tipo di Compito + +Compiti diversi falliscono in modi prevedibili. Conoscere le modalità di fallimento comuni ti aiuta a diagnosticare e correggere i problemi più velocemente. + +### Per la Generazione di Contenuti + +La generazione di contenuti spesso produce output generico, fuori target o mal formattato. Il fix di solito coinvolge essere più specifico sui vincoli, fornire esempi concreti o definire esplicitamente la voce del tuo brand. + + + +### Per la Generazione di Codice + +L'output di codice può fallire tecnicamente (errori di sintassi, funzionalità di linguaggio sbagliate) o architetturalmente (pattern scarsi, casi mancanti). Problemi tecnici necessitano specifiche versione/ambiente; problemi architetturali necessitano guida al design. + + + +### Per l'Analisi + +I compiti di analisi spesso producono risultati superficiali o non strutturati. Guida il modello con framework specifici (SWOT, Cinque Forze di Porter), richiedi molteplici punti di vista o fornisci un template per la struttura dell'output. + + + +### Per Q&A + +Il question-answering può essere troppo conciso o troppo prolisso, e potrebbe mancare indicatori di confidenza o fonti. Specifica il livello di dettaglio di cui hai bisogno e se vuoi citazioni o incertezza espressa. + + + +## La Tecnica del Feedback Loop + +Ecco una meta-tecnica: usa il modello stesso per aiutarti a migliorare i tuoi prompt. Condividi cosa hai provato, cosa hai ottenuto e cosa volevi. Il modello può spesso suggerire miglioramenti che non avevi considerato. + +``` +Ho usato questo prompt: +"[il tuo prompt]" + +E ho ottenuto questo output: +"[output del modello]" + +Volevo qualcosa di più [descrivi la lacuna]. Come dovrei modificare +il mio prompt per ottenere risultati migliori? +``` + +## A/B Testing dei Prompt + +Per prompt che saranno usati ripetutamente o su larga scala, non scegliere solo il primo che funziona. Testa variazioni per trovare l'approccio più affidabile e di massima qualità. + +``` +Prompt A: "Riassumi questo articolo in 3 punti elenco." +Prompt B: "Estrai le 3 intuizioni più importanti da questo articolo." +Prompt C: "Quali sono i punti chiave di questo articolo? Elencane 3." +``` + +Esegui ciascuno più volte, confronta: +- Consistenza dell'output +- Qualità delle informazioni +- Rilevanza per le tue esigenze + +## Quando Smettere di Iterare + +La perfezione è nemica del buono. Sappi quando il tuo prompt è pronto per l'uso e quando stai solo lucidando per rendimenti decrescenti. + +
+
+

Pronto per il Rilascio

+
+

L'output soddisfa consistentemente i requisiti

+

I casi limite sono gestiti appropriatamente

+

Il formato è affidabile e parsabile

+

Ulteriori miglioramenti mostrano rendimenti decrescenti

+
+
+
+

Continua a Iterare

+
+

L'output è inconsistente tra le esecuzioni

+

I casi limite causano fallimenti

+

Requisiti critici vengono mancati

+

Non hai testato abbastanza variazioni

+
+
+
+ +## Controllo Versione per i Prompt + +I prompt sono codice. Per qualsiasi prompt usato in produzione, trattalo con lo stesso rigore: controllo versione, changelog e la possibilità di rollback se qualcosa si rompe. + + +prompts.chat include cronologia automatica delle versioni per i tuoi prompt. Ogni modifica viene salvata, così puoi confrontare versioni e ripristinare iterazioni precedenti con un click. + + +Per prompt autogestiti, usa una struttura di cartelle: + +``` +prompts/ +├── risposta-cliente/ +│ ├── v1.0.txt # Versione iniziale +│ ├── v1.1.txt # Corretto problema tono +│ ├── v2.0.txt # Ristrutturazione maggiore +│ └── current.txt # Symlink alla versione attiva +└── changelog.md # Documenta modifiche +``` + +## Riepilogo + + +Inizia semplice, osserva attentamente, cambia una cosa alla volta, documenta cosa funziona e sappi quando fermarti. I migliori prompt non vengono scritti—vengono scoperti attraverso iterazione sistematica. + + + + +## Pratica: Migliora Questo Prompt + +Prova a migliorare questo prompt debole tu stesso. Modificalo, poi usa l'IA per confrontare la tua versione con l'originale: + + + +Nel prossimo capitolo, esploreremo il prompting JSON e YAML per applicazioni di dati strutturati. diff --git a/src/content/book/it/09-json-yaml-prompting.mdx b/src/content/book/it/09-json-yaml-prompting.mdx new file mode 100644 index 00000000..80f59945 --- /dev/null +++ b/src/content/book/it/09-json-yaml-prompting.mdx @@ -0,0 +1,586 @@ +I formati di dati strutturati come JSON e YAML sono essenziali per costruire applicazioni che consumano output IA in modo programmatico. Questo capitolo copre tecniche per la generazione affidabile di output strutturato. + + +JSON e YAML trasformano gli output IA da testo libero in dati strutturati e type-safe che il codice può consumare direttamente. + + +## Perché Formati Strutturati? + + + +## Basi del Prompting JSON + +JSON (JavaScript Object Notation) è il formato più comune per output IA programmatici. La sua sintassi rigorosa lo rende facile da parsare, ma significa anche che piccoli errori possono rompere l'intera pipeline. + +### Cosa Fare e Non Fare: Richiedere JSON + + + +### Output JSON Semplice + +Inizia con uno schema che mostra la struttura attesa. Il modello riempirà i valori basandosi sul testo di input. + +``` +Estrai le seguenti informazioni come JSON: + +{ + "name": "string", + "age": number, + "email": "string" +} + +Testo: "Contatta Mario Rossi, 34 anni, a mario@example.com" +``` + +Output: +```json +{ + "name": "Mario Rossi", + "age": 34, + "email": "mario@example.com" +} +``` + +### Strutture JSON Annidate + +I dati del mondo reale spesso hanno relazioni annidate. Definisci ogni livello del tuo schema chiaramente, specialmente per array di oggetti. + +``` +Parsa questo ordine in JSON: + +{ + "order_id": "string", + "customer": { + "name": "string", + "email": "string" + }, + "items": [ + { + "product": "string", + "quantity": number, + "price": number + } + ], + "total": number +} + +Ordine: "Ordine #12345 per Maria Bianchi (maria@email.com): 2x Widget (10€ ciascuno), +1x Gadget (25€). Totale: 45€" +``` + +### Assicurare JSON Valido + + +I modelli spesso avvolgono il JSON in blocchi di codice markdown o aggiungono testo esplicativo. Sii esplicito sul volere solo JSON grezzo. + + +Aggiungi istruzioni esplicite: + +``` +CRITICO: Restituisci SOLO JSON valido. No markdown, no spiegazioni, +nessun testo aggiuntivo prima o dopo l'oggetto JSON. + +Se un campo non può essere determinato, usa null. +Assicurati che tutte le stringhe siano correttamente quotate e escapate. +I numeri non devono essere quotati. +``` + +## Basi del Prompting YAML + +YAML è più leggibile dall'uomo rispetto a JSON e supporta i commenti. È lo standard per file di configurazione, specialmente in DevOps (Docker, Kubernetes, GitHub Actions). + +### Output YAML Semplice + +YAML usa l'indentazione invece delle parentesi graffe. Fornisci un template che mostra la struttura attesa. + +``` +Genera un file di configurazione in formato YAML: + +server: + host: string + port: number + ssl: boolean +database: + type: string + connection_string: string + +Requisiti: Server di produzione sulla porta 443 con SSL, database PostgreSQL +``` + +Output: +```yaml +server: + host: "0.0.0.0" + port: 443 + ssl: true +database: + type: "postgresql" + connection_string: "postgresql://user:pass@localhost:5432/prod" +``` + +### Strutture YAML Complesse + +Per configurazioni complesse, sii specifico sui requisiti. Il modello conosce pattern comuni per strumenti come GitHub Actions, Docker Compose e Kubernetes. + +``` +Genera un workflow GitHub Actions in YAML: + +Requisiti: +- Trigger su push a main e pull request +- Esegui su Ubuntu latest +- Step: checkout, setup Node 18, installa dipendenze, esegui test +- Cache delle dipendenze npm +``` + +## Definizioni di Tipo nei Prompt + +Le definizioni di tipo danno al modello un contratto preciso per la struttura dell'output. Sono più esplicite degli esempi e più facili da validare programmaticamente. + +### Usare Tipi Stile TypeScript + +Le interfacce TypeScript sono familiari agli sviluppatori e descrivono precisamente campi opzionali, tipi union e array. La piattaforma prompts.chat usa questo approccio per prompt strutturati. + + + +### Definizione JSON Schema + + +JSON Schema è una specifica formale per descrivere la struttura JSON. È supportato da molte librerie di validazione e strumenti API. + + +JSON Schema fornisce vincoli come valori min/max, campi obbligatori e pattern regex: + +``` +Estrai dati secondo questo JSON Schema: + +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "type": "object", + "required": ["title", "author", "year"], + "properties": { + "title": { "type": "string" }, + "author": { "type": "string" }, + "year": { "type": "integer", "minimum": 1000, "maximum": 2100 }, + "genres": { + "type": "array", + "items": { "type": "string" } + }, + "rating": { + "type": "number", + "minimum": 0, + "maximum": 5 + } + } +} + +Libro: "1984 di George Orwell (1949) - Un capolavoro distopico. +Generi: Fantascienza, Narrativa Politica. Valutazione 4.8/5" +``` + +## Gestire Array + +Gli array richiedono attenzione speciale. Specifica se hai bisogno di un numero fisso di elementi o una lista di lunghezza variabile, e come gestire casi vuoti. + +### Array a Lunghezza Fissa + +Quando hai bisogno di esattamente N elementi, dichiaralo esplicitamente. Il modello assicurerà che l'array abbia la lunghezza giusta. + +``` +Estrai esattamente 3 punti chiave come JSON: + +{ + "key_points": [ + "string (primo punto)", + "string (secondo punto)", + "string (terzo punto)" + ] +} + +Articolo: [testo articolo] +``` + +### Array a Lunghezza Variabile + +Per array a lunghezza variabile, specifica cosa fare quando ci sono zero elementi. Includere un campo count aiuta a verificare la completezza dell'estrazione. + +``` +Estrai tutte le persone menzionate come JSON: + +{ + "people": [ + { + "name": "string", + "role": "string o null se non menzionato" + } + ], + "count": number +} + +Se nessuna persona è menzionata, restituisci array vuoto. + +Testo: [testo] +``` + +## Valori Enum e Vincoli + +Gli enum restringono i valori a un set predefinito. Questo è cruciale per compiti di classificazione e ovunque hai bisogno di output consistenti e prevedibili. + +### Cosa Fare e Non Fare: Valori Enum + + + +### Enum di Stringhe + +Elenca i valori permessi esplicitamente. Usa linguaggio "DEVE essere uno di" per imporre matching rigoroso. + +``` +Classifica questo testo. La categoria DEVE essere uno di questi valori esatti: +- "technical" +- "business" +- "creative" +- "personal" + +Restituisci JSON: +{ + "text": "testo originale (troncato a 50 caratteri)", + "category": "uno dei valori enum sopra", + "confidence": numero tra 0 e 1 +} + +Testo: [testo da classificare] +``` + +### Numeri Validati + +I vincoli numerici prevengono valori fuori range. Specifica il tipo (intero vs float) e range valido. + +``` +Valuta questi aspetti. Ogni punteggio DEVE essere un intero da 1 a 5. + +{ + "quality": 1-5, + "value": 1-5, + "service": 1-5, + "overall": 1-5 +} + +Recensione: [testo recensione] +``` + +## Gestire Dati Mancanti + +Il testo del mondo reale spesso manca di alcune informazioni. Definisci come il modello dovrebbe gestire dati mancanti per evitare valori allucinati. + +### Cosa Fare e Non Fare: Informazioni Mancanti + + + +### Valori Null + +Permetti esplicitamente null e istruisci il modello a non inventare informazioni. Questo è più sicuro che far indovinare il modello. + +``` +Estrai informazioni. Usa null per qualsiasi campo che non può essere +determinato dal testo. NON inventare informazioni. + +{ + "company": "string o null", + "revenue": "number o null", + "employees": "number o null", + "founded": "number (anno) o null", + "headquarters": "string o null" +} + +Testo: "Apple, con sede a Cupertino, è stata fondata nel 1976." +``` + +Output: +```json +{ + "company": "Apple", + "revenue": null, + "employees": null, + "founded": 1976, + "headquarters": "Cupertino" +} +``` + +### Valori Predefiniti + +Quando i default hanno senso, specificali nello schema. Questo è comune per l'estrazione di configurazioni. + +``` +Estrai impostazioni con questi default se non specificate: + +{ + "theme": "light" (default) | "dark", + "language": "it" (default) | altro codice ISO, + "notifications": true (default) | false, + "fontSize": 14 (default) | number +} + +Preferenze utente: "Voglio la modalità scura e testo più grande (18px)" +``` + +## Risposte Multi-Oggetto + +Spesso hai bisogno di estrarre molteplici elementi da un singolo input. Definisci la struttura dell'array e qualsiasi requisito di ordinamento/raggruppamento. + +### Array di Oggetti + +Per liste di elementi simili, definisci lo schema dell'oggetto una volta e specifica che è un array. + +``` +Parsa questa lista in array JSON: + +[ + { + "task": "string", + "priority": "high" | "medium" | "low", + "due": "stringa data ISO o null" + } +] + +Lista todo: +- Finire report (urgente, scadenza domani) +- Chiamare dentista (bassa priorità) +- Revisionare PR #123 (media, scadenza venerdì) +``` + +### Oggetti Raggruppati + +I compiti di raggruppamento richiedono logica di categorizzazione. Il modello ordinerà gli elementi nelle categorie che definisci. + +``` +Categorizza questi elementi in JSON: + +{ + "fruits": ["array stringhe"], + "vegetables": ["array stringhe"], + "other": ["array stringhe"] +} + +Elementi: mela, carota, pane, banana, broccoli, latte, arancia, spinaci +``` + +## YAML per Generazione di Configurazioni + +YAML brilla per configurazioni DevOps. Il modello conosce pattern standard per strumenti comuni e può generare config pronte per la produzione. + +### Cosa Fare e Non Fare: Config YAML + + + +### Docker Compose + +Specifica i servizi di cui hai bisogno e qualsiasi requisito speciale. Il modello gestirà la sintassi YAML e le best practice. + +``` +Genera un docker-compose.yml per: +- App Node.js sulla porta 3000 +- Database PostgreSQL +- Cache Redis +- Nginx reverse proxy + +Includi: +- Health check +- Persistenza volumi +- Variabili d'ambiente da file .env +- Isolamento di rete +``` + +### Manifest Kubernetes + +I manifest Kubernetes sono verbosi ma seguono pattern prevedibili. Fornisci i parametri chiave e il modello genererà YAML conforme. + +``` +Genera YAML deployment Kubernetes: + +Deployment: +- Nome: api-server +- Immagine: myapp:v1.2.3 +- Repliche: 3 +- Risorse: 256Mi memoria, 250m CPU (requests) +- Health check: endpoint /health +- Environment da ConfigMap: api-config + +Genera anche Service corrispondente (ClusterIP, porta 8080) +``` + +## Validazione e Gestione Errori + +Per sistemi di produzione, integra la validazione nei tuoi prompt. Questo cattura errori prima che si propaghino attraverso la tua pipeline. + +### Prompt di Auto-Validazione + +Chiedi al modello di validare il proprio output contro regole che specifichi. Questo cattura errori di formato e valori invalidi. + +``` +Estrai dati come JSON, poi valida il tuo output. + +Schema: +{ + "email": "formato email valido", + "phone": "formato E.164 (+391234567890)", + "date": "formato ISO 8601 (YYYY-MM-DD)" +} + +Dopo aver generato JSON, controlla: +1. Email contiene @ e dominio valido +2. Telefono inizia con + e contiene solo cifre +3. Data è valida e parsabile + +Se la validazione fallisce, correggi i problemi prima di rispondere. + +Testo: [informazioni contatto] +``` + +### Formato Risposta Errore + +Definisci formati separati per successo ed errore. Questo rende la gestione programmatica molto più facile. + +``` +Prova a estrarre dati. Se l'estrazione fallisce, restituisci formato errore: + +Formato successo: +{ + "success": true, + "data": { ... dati estratti ... } +} + +Formato errore: +{ + "success": false, + "error": "descrizione di cosa è andato storto", + "partial_data": { ... eventuali dati che sono stati estratti ... } +} +``` + +## JSON vs YAML: Quando Usare Quale + +
+
+
Usa JSON Quando
+
+

Parsing programmatico necessario

+

Risposte API

+

Requisiti di tipo rigorosi

+

Integrazione JavaScript/Web

+

Rappresentazione compatta

+
+
+
+
Usa YAML Quando
+
+

La leggibilità umana conta

+

File di configurazione

+

Servono commenti

+

DevOps/Infrastruttura

+

Strutture profondamente annidate

+
+
+
+ +## Prompt Strutturati su Prompts.chat + +Su prompts.chat, puoi creare prompt con formati di output strutturati: + +``` +Quando crei un prompt su prompts.chat, puoi specificare: + +Tipo: STRUCTURED +Formato: JSON o YAML + +La piattaforma: +- Validerà output contro il tuo schema +- Fornirà syntax highlighting +- Abiliterà copia facile dell'output strutturato +- Supporterà variabili template nel tuo schema +``` + +## Insidie Comuni + + +Questi tre problemi causano la maggior parte dei fallimenti di parsing JSON. Controllali quando il tuo codice non riesce a parsare l'output IA. + + +### 1. Blocchi di Codice Markdown + +**Problema:** Il modello avvolge JSON in blocchi ```json + +**Soluzione:** +``` +Restituisci SOLO l'oggetto JSON. Non avvolgere in blocchi di codice markdown. +Non includere marcatori ```json o ```. +``` + +### 2. Virgole Finali + +**Problema:** JSON invalido a causa di virgole finali + +**Soluzione:** +``` +Assicura sintassi JSON valida. Nessuna virgola finale dopo l'ultimo +elemento in array o oggetti. +``` + +### 3. Stringhe Non Escapate + +**Problema:** Virgolette o caratteri speciali rompono JSON + +**Soluzione:** +``` +Esegui correttamente l'escape dei caratteri speciali nelle stringhe: +- \" per virgolette +- \\ per backslash +- \n per newline +``` + +## Riepilogo + + +Definisci schema esplicitamente usando interfacce TypeScript o JSON Schema. Specifica tipi e vincoli, gestisci null e default, richiedi auto-validazione e scegli il formato giusto per il tuo caso d'uso. + + + + +Questo completa la Parte II sulle tecniche. Nella Parte III, esploreremo applicazioni pratiche attraverso diversi domini. diff --git a/src/content/book/it/10-system-prompts-personas.mdx b/src/content/book/it/10-system-prompts-personas.mdx new file mode 100644 index 00000000..8164b350 --- /dev/null +++ b/src/content/book/it/10-system-prompts-personas.mdx @@ -0,0 +1,435 @@ +I system prompt sono come dare all'IA la sua personalità e descrizione del lavoro prima che inizi una conversazione. Pensali come le "istruzioni dietro le quinte" che modellano tutto ciò che l'IA dice. + + +Un system prompt è un messaggio speciale che dice all'IA chi è, come comportarsi e cosa può o non può fare. Gli utenti di solito non vedono questo messaggio, ma influenza ogni risposta. + + + +I system prompt si costruiscono sui concetti del [Prompting Basato sui Ruoli](/book/04-role-based-prompting). Mentre i prompt di ruolo assegnano una persona all'interno del tuo messaggio, i system prompt impostano quell'identità a un livello più profondo che persiste per l'intera conversazione. + + +## Come Funzionano i System Prompt + +Quando chatti con l'IA, ci sono in realtà tre tipi di messaggi: + + + +Il messaggio di sistema rimane attivo per l'intera conversazione. È come il "manuale di istruzioni" dell'IA. + +## Costruire un System Prompt + +Un buon system prompt ha cinque parti. Pensale come compilare una scheda personaggio per l'IA: + + + +### Esempio: Un Tutor di Programmazione + + + +## Pattern di Persona + +Compiti diversi richiedono personalità IA diverse. Ecco tre pattern comuni che puoi adattare: + +### 1. L'Esperto + +Migliore per: Apprendimento, ricerca, consigli professionali + + + +### 2. L'Assistente + +Migliore per: Produttività, organizzazione, portare a termine le cose + + + +### 3. Il Personaggio + +Migliore per: Scrittura creativa, roleplay, intrattenimento + + + +## Tecniche Avanzate + +### Istruzioni a Strati + +Pensa al tuo system prompt come a una cipolla con strati. Gli strati interni sono i più importanti: + + + +### Comportamento Adattivo + +Fai sì che la tua IA si adatti automaticamente a utenti diversi: + + + +### Memoria della Conversazione + +L'IA non ricorda conversazioni passate, ma puoi dirle di tracciare cose all'interno della chat corrente: + + + +## Esempi del Mondo Reale + +Ecco system prompt completi per casi d'uso comuni. Clicca per provarli! + +### Bot Supporto Clienti + + + +### Compagno di Studio + + + +### Coach di Scrittura + + + +## Testare il Tuo System Prompt + +Prima di usare un system prompt per davvero, testalo! Ecco cosa verificare: + + + +### Comprendere gli Attacchi di Jailbreak + +Il "jailbreaking" è quando qualcuno cerca di ingannare l'IA per farle ignorare le sue regole. Capire questi attacchi ti aiuta a costruire difese migliori. + + + +### Altri Scenari di Test + +Usa questi esempi interattivi per vedere come un system prompt ben progettato gestisce situazioni difficili: + +#### Test 1: Tentativo di Jailbreak + +Vedi come un buon system prompt resiste ai tentativi di sovrascriverlo: + + + +#### Test 2: Restare nel Personaggio + +Testa se l'IA mantiene la sua persona quando viene messa alla prova: + + + +#### Test 3: Applicazione dei Confini + +Verifica se l'IA rispetta le sue limitazioni dichiarate: + + + +#### Test 4: Rivelare il System Prompt + +Vedi se l'IA protegge le sue istruzioni: + + + +#### Test 5: Istruzioni in Conflitto + +Testa come l'IA gestisce richieste contraddittorie: + + + + +Un system prompt ben costruito: +- Rifiuterà gentilmente richieste inappropriate +- Resterà nel personaggio mentre reindirizza +- Non rivelerà istruzioni confidenziali +- Gestirà casi limite con grazia + + +## Riferimento Rapido + +
+
+

Fare

+
    +
  • Dai un'identità chiara
  • +
  • Elenca capacità specifiche
  • +
  • Imposta confini espliciti
  • +
  • Definisci il tono e lo stile
  • +
  • Includi risposte di esempio
  • +
+
+
+

Non Fare

+
    +
  • Essere vago sul ruolo
  • +
  • Dimenticare di impostare limiti
  • +
  • Renderlo troppo lungo (max 500 parole)
  • +
  • Contraddire te stesso
  • +
  • Assumere che l'IA "capirà"
  • +
+
+
+ +## Riepilogo + +I system prompt sono il manuale di istruzioni dell'IA. Impostano: +- **Chi** è l'IA (identità e expertise) +- **Cosa** può e non può fare (capacità e limiti) +- **Come** dovrebbe rispondere (tono, formato, stile) + + +Inizia con un system prompt breve e aggiungi più regole man mano che scopri cosa serve. Un prompt chiaro di 100 parole batte uno confuso di 500. + + + + + + +Nel prossimo capitolo, esploreremo il prompt chaining: collegare molteplici prompt insieme per compiti complessi multi-step. diff --git a/src/content/book/it/11-prompt-chaining.mdx b/src/content/book/it/11-prompt-chaining.mdx new file mode 100644 index 00000000..7067e726 --- /dev/null +++ b/src/content/book/it/11-prompt-chaining.mdx @@ -0,0 +1,379 @@ +Il prompt chaining suddivide compiti complessi in sequenze di prompt più semplici, dove l'output di ogni passo alimenta il successivo. Questa tecnica migliora drasticamente l'affidabilità e permette workflow sofisticati che sarebbero impossibili con un singolo prompt. + + +Proprio come una catena di montaggio in fabbrica suddivide la produzione in stazioni specializzate, il prompt chaining suddivide i compiti IA in passi specializzati. Ogni passo fa bene una cosa, e l'output combinato è molto migliore che cercare di fare tutto insieme. + + +## Perché Concatenare i Prompt? + +I singoli prompt faticano con compiti complessi perché cercano di fare troppo in una volta. L'IA deve contemporaneamente capire, analizzare, pianificare e generare, il che porta a errori e inconsistenze. + +
+
+

Difficoltà del Prompt Singolo

+
+

Il ragionamento multi-step si confonde

+

Diverse "modalità" di pensiero entrano in conflitto

+

Gli output complessi mancano di consistenza

+

Nessuna opportunità per controllo qualità

+
+
+
+

Il Chaining Risolve Questo

+
+

Ogni passo si concentra su un compito

+

Prompt specializzati per ogni modalità

+

Valida tra un passo e l'altro

+

Debug e migliora i singoli passi

+
+
+
+ +## Pattern di Chaining Base + +La catena più semplice passa l'output da un prompt direttamente al successivo. Ogni passo ha uno scopo chiaro e focalizzato. + +
+
+
+

Prompt 1

+

(Estrai)

+
+

Input

+
+
→
+
+
+

Prompt 2

+

(Analizza)

+
+

Intermedio

+
+
→
+
+
+

Prompt 3

+

(Genera)

+
+

Output

+
+
+ + +Il pattern di catena più comune è **Estrai → Trasforma → Genera**. Prima estrai i dati grezzi, poi rimodellali per il tuo scopo, poi genera l'output finale. Questo pattern funziona per quasi qualsiasi compito di contenuto. + + +## Tipi di Catene + +Compiti diversi richiedono architetture di catena diverse. Scegli il pattern che corrisponde al tuo workflow. + + + +### Catena Sequenziale + +Il pattern più diretto: ogni passo dipende dal precedente. Pensalo come una staffetta dove ogni corridore passa il testimone al successivo. + + + +### Catena Parallela + +Quando hai bisogno di molteplici prospettive sullo stesso input, esegui prompt in parallelo e unisci i risultati. Questo è più veloce delle catene sequenziali e fornisce un'analisi più ricca. + + + +### Catena Condizionale + +Instrada gli input attraverso percorsi diversi basandosi sulla classificazione. È come un albero decisionale dove l'IA prima categorizza l'input, poi gestisce ogni categoria diversamente. + + + +### Catena Iterativa + +Continua a raffinare l'output finché non soddisfa gli standard di qualità. L'IA genera, valuta e migliora in un ciclo finché non è soddisfatta o il massimo di iterazioni è raggiunto. + + +Imposta sempre un numero massimo di iterazioni (tipicamente 3-5) per prevenire loop infiniti e controllare i costi. La legge dei rendimenti decrescenti si applica: la maggior parte del miglioramento avviene nelle prime 2-3 iterazioni. + + += 8: ESCI DAL LOOP' } + ]} +/> + +## Pattern di Catena Comuni + +Questi pattern collaudati risolvono problemi comuni. Usali come punti di partenza e adattali alle tue esigenze. + +### Estrai → Trasforma → Genera + +Il cavallo di battaglia dell'elaborazione contenuti. Estrai dati, rimodellali, poi crea qualcosa di nuovo. + +
+

Migliore Per

+

Riassunto documenti, generazione report, riutilizzo contenuti, conversione dati-a-narrativa

+
+ + + +### Analizza → Pianifica → Esegui + +Perfetto per refactoring del codice, pianificazione progetti, o qualsiasi compito dove devi capire prima di agire. + +
+

Migliore Per

+

Refactoring codice, pianificazione progetti, troubleshooting, decision-making strategico, problem solving complesso

+
+ + {\n const { email, password } = req.body;\n if (!email || !isValidEmail(email)) {\n return res.status(400).json({ error: 'Email invalida' });\n }\n next();\n};" } + ]} +/> + +### Genera → Critica → Raffina + +Il loop di auto-miglioramento. Genera contenuto, fallo valutare criticamente dall'IA, poi migliora basandoti su quel feedback. Questo imita come lavorano insieme scrittori ed editor professionisti. + +
+

Migliore Per

+

Copy marketing, scrittura creativa, bozze email, presentazioni, qualsiasi contenuto che beneficia di revisione

+
+ + + +## Implementare le Catene + +Puoi implementare le catene manualmente per sperimentazione, o programmaticamente per sistemi di produzione. Inizia semplice e aggiungi complessità al bisogno. + +### Chaining Manuale + +L'approccio copia-incolla è perfetto per prototipazione e sperimentazione. Esegui ogni prompt manualmente, esamina l'output e incollalo nel prompt successivo. + + + +### Chaining Programmatico + +Per sistemi di produzione, automatizza la catena con codice. Questo abilita gestione errori, logging e integrazione con la tua applicazione. + + + +### Usare Template di Catena + +Definisci le catene come file di configurazione per riutilizzabilità e facile modifica. Questo separa la logica dei prompt dal codice applicativo. + + + +## Error Handling in Chains + +Chains can fail at any step. Build in validation, retries, and fallbacks to make your chains robust. + + + + +If one step produces bad output, every following step will be affected. Always validate critical intermediate results before passing them forward. + + +### Validation Between Steps + +Add a validation step after any step that produces structured data. This catches errors early before they cascade. + + + +### Fallback Chains + +When your primary approach fails, have a simpler backup ready. Trade capability for reliability. + + + +## Chain Optimization + +Once your chain works, optimize for speed, cost, and reliability. These often trade off against each other. + +
+
+

Reducing Latency

+
+

Parallelize independent steps

+

Cache intermediate results

+

Use smaller models for simple steps

+

Batch similar operations

+
+
+
+

Reducing Cost

+
+

Use cheaper models for classification

+

Limit iterations in loops

+

Short-circuit when possible

+

Cache repeated queries

+
+
+
+

Improving Reliability

+
+

Add validation between steps

+

Include retry logic

+

Log intermediate results

+

Implement fallback paths

+
+
+
+ +## Real-World Chain Example + +Let's walk through a complete production chain. This content pipeline transforms a raw idea into a polished article package. + +### Content Pipeline Chain + + + +## Summary + +Prompt chaining transforms what AI can accomplish by breaking impossible tasks into achievable steps. + +
+
+

Chaining Enables

+
+

Complex multi-step workflows

+

Higher quality through specialization

+

Better error handling and validation

+

Modular, reusable prompt components

+
+
+
+

Key Principles

+
+

Break complex tasks into simple steps

+

Design clear interfaces between steps

+

Validate intermediate outputs

+

Build in error handling and fallbacks

+

Optimize for your constraints

+
+
+
+ + +Begin with a 2-3 step sequential chain. Get it working reliably before adding complexity. Most tasks don't need elaborate chain architectures. + + + + +In the next chapter, we'll explore multimodal prompting: working with images, audio, and other non-text content. diff --git a/src/content/book/it/12-handling-edge-cases.mdx b/src/content/book/it/12-handling-edge-cases.mdx new file mode 100644 index 00000000..4708ee3c --- /dev/null +++ b/src/content/book/it/12-handling-edge-cases.mdx @@ -0,0 +1,580 @@ +Prompts that work perfectly in testing often fail in the real world. Users send empty messages, paste walls of text, make ambiguous requests, and sometimes try to break your system intentionally. This chapter teaches you to build prompts that handle the unexpected gracefully. + + +80% of production issues come from inputs you never anticipated. A prompt that handles edge cases well is worth more than a "perfect" prompt that only works with ideal inputs. + + +## Why Edge Cases Break Prompts + +When a prompt encounters unexpected input, it typically fails in one of three ways: + +**Silent Failures**: The model produces output that looks correct but contains errors. These are the most dangerous because they're hard to detect. + +**Confused Responses**: The model misinterprets the request and answers a different question than what was asked. + +**Hallucinated Handling**: The model invents a way to handle the edge case that doesn't match your intended behavior. + + + +## Categories of Edge Cases + +Understanding what can go wrong helps you prepare for it. Edge cases fall into three main categories: + +### Input Edge Cases + +These are problems with the data itself: + + + +### Domain Edge Cases + +These are requests that push the boundaries of your prompt's purpose: + + + +### Adversarial Edge Cases + +These are deliberate attempts to misuse your system: + + + +## Input Validation Patterns + +The key to handling edge cases is explicit instructions. Don't assume the model will "figure it out" - tell it exactly what to do in each scenario. + +### Handling Empty Input + +The most common edge case is receiving nothing at all, or input that's essentially empty (just whitespace or greetings). + + + +### Handling Long Input + +When input exceeds what you can reasonably process, fail gracefully rather than silently truncating. + + + +### Handling Ambiguous Requests + +When a request could mean multiple things, asking for clarification is better than guessing wrong. + + + +## Building Defensive Prompts + +A defensive prompt anticipates failure modes and defines explicit behavior for each. Think of it as error handling for natural language. + +### The Defensive Template + +Every robust prompt should address these four areas: + + + +### Example: Defensive Data Extraction + +This prompt extracts contact information but handles every edge case explicitly. Notice how each potential failure has a defined response. + + + +## Handling Out-of-Scope Requests + +Every prompt has boundaries. Defining them explicitly prevents the model from wandering into territory where it might give bad advice or make things up. + +### Graceful Scope Limits + +The best out-of-scope responses do three things: acknowledge the request, explain the limitation, and offer an alternative. + + + +### Handling Knowledge Cutoffs + +Be honest about what you don't know. Users trust AI more when it admits limitations. + + + +## Adversarial Input Handling + +Some users will try to manipulate your prompts, either out of curiosity or malicious intent. Building defenses into your prompts reduces these risks. + +### Prompt Injection Defense + +Prompt injection is when a user tries to override your instructions by embedding their own commands in the input. The key defense is treating user input as data, never as instructions. + + + + +Prompt injection defenses reduce risk but can't eliminate it entirely. For high-stakes applications, combine prompt defenses with input sanitization, output filtering, and human review. + + +### Handling Sensitive Requests + +Some requests require special handling due to safety, legal, or ethical concerns. Define these boundaries explicitly. + + + +## Error Recovery Patterns + +Even well-designed prompts will encounter situations they can't handle perfectly. The goal is to fail helpfully. + +### Graceful Degradation + +When you can't fully complete a task, offer what you can rather than failing completely. + + + +### Confidence Indicators + +Teach your prompts to express uncertainty. This helps users know when to trust the output and when to verify. + + + + + +## Testing Edge Cases + +Before deploying a prompt, systematically test it against the edge cases you've anticipated. This checklist helps ensure you haven't missed common failure modes. + +### Edge Case Testing Checklist + + + + + + + + + +### Creating a Test Suite + +For production prompts, create a systematic test suite. Here's a pattern you can adapt: + + + +## Real-World Example: Robust Customer Service Bot + +This comprehensive example shows how all the patterns come together in a production-ready prompt. Notice how every edge case has explicit handling. + + + +## Summary + +Building robust prompts requires thinking about what can go wrong before it does. The key principles: + + + + +In production, everything that can go wrong eventually will. A prompt that handles edge cases gracefully is worth more than a "perfect" prompt that only works with ideal inputs. + + + + +In the next chapter, we'll explore how to work with multiple AI models and compare their outputs. diff --git a/src/content/book/it/13-multimodal-prompting.mdx b/src/content/book/it/13-multimodal-prompting.mdx new file mode 100644 index 00000000..376960ae --- /dev/null +++ b/src/content/book/it/13-multimodal-prompting.mdx @@ -0,0 +1,665 @@ +For most of history, computers worked with one type of data at a time: text in one program, images in another, audio somewhere else. But humans don't experience the world this way. We see, hear, read, and speak simultaneously, combining all these inputs to understand our environment. + +**Multimodal AI** changes everything. These models can process multiple types of information together—analyzing an image while reading your question about it, or generating images from your text descriptions. This chapter teaches you how to communicate effectively with these powerful systems. + + +"Multi" means many, and "modal" refers to modes or types of data. A multimodal model can work with multiple modalities: text, images, audio, video, or even code. Instead of separate tools for each type, one model understands them all together. + + +## Why Multimodal Matters + +Traditional AI required you to describe everything in words. Want to ask about an image? You'd have to describe it first. Want to analyze a document? You'd need to transcribe it manually. Multimodal models eliminate these barriers. + + + +## Why Prompting Matters Even More for Multimodal + +With text-only models, the AI receives exactly what you type. But with multimodal models, the AI must interpret visual or audio information—and interpretation requires guidance. + + + +**Without guidance**, the model might describe colors, layout, or irrelevant details. **With guidance**, it focuses on what actually matters to you. + + +When you look at an image, you instantly know what's important based on your context and goals. The AI doesn't have this context unless you provide it. A photo of a crack in a wall could be: a structural engineering concern, an artistic texture, or irrelevant background. Your prompt determines how the AI interprets it. + + +## The Multimodal Landscape + +Different models have different capabilities. Here's what's available in 2025: + +### Understanding Models (Input → Analysis) + +These models accept various media types and produce text analysis or responses. + + + +### Generation Models (Text → Media) + +These models create images, audio, or video from text descriptions. + + + + +The multimodal landscape changes quickly. New models launch frequently, and existing models gain capabilities through updates. Always check the latest documentation for current features and limitations. + + +## Image Understanding Prompts + +The most common multimodal use case is asking AI to analyze images. The key is providing context about what you need. + +### Basic Image Analysis + +Start with a clear request structure. Tell the model what aspects to focus on. + + + +### Structured Output for Images + +When you need to process image analysis programmatically, request JSON output. + + + +### Comparative Analysis + +Comparing multiple images requires clear labeling and specific comparison criteria. + + + +## Document and Screenshot Analysis + +One of the most practical applications of multimodal AI is analyzing documents, screenshots, and UI elements. This saves hours of manual transcription and review. + +### Document Extraction + +Scanned documents, photos of receipts, and PDFs as images can all be processed. The key is telling the model what type of document it is and what information you need. + + + +### Screenshot and UI Analysis + +Screenshots are goldmines for debugging, UX review, and documentation. Guide the AI to focus on what matters. + + + +### Error Message Analysis + +When you encounter an error, a screenshot often contains more context than copying the error text alone. + + + +## Image Generation Prompts + +Generating images from text descriptions is an art form. The more specific and structured your prompt, the closer the result will match your vision. + +### The Anatomy of an Image Prompt + +Effective image generation prompts have several components: + + + +### Basic Image Generation + + + +### Scene Building + +For complex scenes, describe layers from foreground to background. + + + +## Audio Prompting + +Audio processing opens up transcription, analysis, and understanding of spoken content. The key is providing context about what the audio contains. + +### Enhanced Transcription + +Basic transcription is just the start. With good prompts, you can get speaker identification, timestamps, and domain-specific accuracy. + + + +### Audio Content Analysis + +Beyond transcription, AI can analyze the content, tone, and key moments in audio. + + + +## Video Prompting + +Video combines visual and audio analysis over time. The challenge is guiding the AI to focus on the relevant aspects across the entire duration. + +### Video Understanding + + + +### Video Content Extraction + +For specific information extraction from videos, be precise about what you need. + + + +## Multimodal Combinations + +The real power of multimodal AI emerges when you combine different types of input. These combinations enable analysis that would be impossible with any single modality. + +### Image + Text Verification + +Check if images and their descriptions match—essential for e-commerce, content moderation, and quality assurance. + + + +### Screenshot + Code Debugging + +One of the most powerful combinations for developers: seeing the visual bug alongside the code. + + + +### Multi-Image Decision Making + +When choosing between options, structured comparison helps make better decisions. + + + +## Best Practices for Multimodal Prompts + +Getting great results from multimodal AI requires understanding both its capabilities and limitations. + +### What Makes Multimodal Prompts Effective + + + +### Common Pitfalls to Avoid + + + +### Handling Limitations Gracefully + + + + diff --git a/src/content/book/it/14-context-engineering.mdx b/src/content/book/it/14-context-engineering.mdx new file mode 100644 index 00000000..b9c69b6d --- /dev/null +++ b/src/content/book/it/14-context-engineering.mdx @@ -0,0 +1,287 @@ +Understanding context is essential for building AI applications that actually work. This chapter covers everything you need to know about giving AI the right information at the right time. + + +AI models are stateless. They don't remember past conversations. Every time you send a message, you need to include everything the AI needs to know. This is called "context engineering." + + +## What is Context? + +Context is all the information you give to AI alongside your question. Think of it like this: + + + +Without context, the AI has no idea what "status" you're asking about. With context, it can give a useful answer. + +### The Context Window + +Remember from earlier chapters: AI has a limited "context window" - the maximum amount of text it can see at once. This includes: + + + +## AI is Stateless + + +AI doesn't remember anything between conversations. Every API call starts fresh. If you want the AI to "remember" something, YOU have to include it in the context every time. + + +This is why chatbots send your entire conversation history with each message. It's not that the AI remembers - it's that the app re-sends everything. + + + +The AI will say it doesn't know because it truly doesn't have access to any previous context. + +## RAG: Retrieval-Augmented Generation + +RAG is a technique for giving AI access to knowledge it wasn't trained on. Instead of trying to fit everything into the AI's training, you: + +1. **Store** your documents in a searchable database +2. **Search** for relevant documents when a user asks a question +3. **Retrieve** the most relevant pieces +4. **Augment** your prompt with those pieces +5. **Generate** an answer using that context + +
+

How RAG Works:

+
+
+ 1 + User asks: "What's our refund policy?" +
+
+ 2 + System searches your documents for "refund policy" +
+
+ 3 + Finds relevant section from your policy document +
+
+ 4 + Sends to AI: "Based on this policy: [text], answer: What's our refund policy?" +
+
+ 5 + AI generates accurate answer using your actual policy +
+
+
+ +### Why RAG? + +
+
+

RAG Advantages

+
    +
  • Uses your actual, current data
  • +
  • Reduces hallucinations
  • +
  • Can cite sources
  • +
  • Easy to update (just update documents)
  • +
  • No expensive fine-tuning needed
  • +
+
+
+

When to Use RAG

+
    +
  • Customer support bots
  • +
  • Documentation search
  • +
  • Internal knowledge bases
  • +
  • Any domain-specific Q&A
  • +
  • When accuracy matters
  • +
+
+
+ +## Embeddings: How Search Works + +How does RAG know which documents are "relevant"? It uses **embeddings** - a way to turn text into numbers that capture meaning. + +### What Are Embeddings? + +An embedding is a list of numbers (a "vector") that represents the meaning of text. Similar meanings = similar numbers. + + + +### Semantic Search + +With embeddings, you can search by meaning, not just keywords: + + + +This is why RAG is so powerful - it finds relevant information even when the exact words don't match. + +## Function Calling / Tool Use + +Function calling lets AI use external tools - like searching the web, checking a database, or calling an API. + + +Different AI providers call this different things: "function calling" (OpenAI), "tool use" (Anthropic/Claude), or "tools" (general term). They all mean the same thing. + + +### How It Works + +1. You tell the AI what tools are available +2. AI decides if it needs a tool to answer +3. AI outputs a structured request for the tool +4. Your code runs the tool and returns results +5. AI uses the results to form its answer + + + +## Summarization: Managing Long Conversations + +As conversations get longer, you'll hit the context window limit. Since AI is stateless (it doesn't remember anything), long conversations can overflow. The solution? **Summarization**. + +### The Problem + + + +### Summarization Strategies + +Different approaches work for different use cases. Click each strategy to see how it processes the same conversation: + + + +### What to Capture in Summaries + +A good conversation summary preserves what matters: + + + +### Try It: Create a Summary + + + +### When to Summarize + + + +## MCP: Model Context Protocol + +MCP (Model Context Protocol) is a standard way to connect AI to external data and tools. Instead of building custom integrations for each AI provider, MCP provides a universal interface. + +### Why MCP? + + + +### MCP Provides + +- **Resources**: Data the AI can read (files, database records, API responses) +- **Tools**: Actions the AI can take (search, create, update, delete) +- **Prompts**: Pre-built prompt templates + + +This platform has an MCP server! You can connect it to Claude Desktop or other MCP-compatible clients to search and use prompts directly from your AI assistant. + + +## Building Context: The Complete Picture + + + +## Best Practices + + + +## Summary + +Context engineering is about giving AI the right information: + +- **AI is stateless** - include everything it needs every time +- **RAG** retrieves relevant documents to augment prompts +- **Embeddings** enable semantic search (meaning, not just keywords) +- **Function calling** lets AI use external tools +- **Summarization** manages long conversations +- **MCP** standardizes how AI connects to data and tools + + +The quality of AI output depends on the quality of context you provide. Better context = better answers. + diff --git a/src/content/book/it/15-common-pitfalls.mdx b/src/content/book/it/15-common-pitfalls.mdx new file mode 100644 index 00000000..3c9c2814 --- /dev/null +++ b/src/content/book/it/15-common-pitfalls.mdx @@ -0,0 +1,373 @@ +Even experienced prompt engineers fall into predictable traps. The good news? Once you recognize these patterns, they're easy to avoid. This chapter walks through the most common pitfalls, explains why they happen, and gives you concrete strategies to sidestep them. + + +A single pitfall can turn a powerful AI into a frustrating tool. Understanding these patterns is often the difference between "AI doesn't work for me" and "AI transformed my workflow." + + +## The Vagueness Trap + +**The Pattern**: You know what you want, so you assume the AI will figure it out too. But vague prompts produce vague results. + + + +**Why it happens**: We naturally skip details when we think they're "obvious." But what's obvious to you isn't obvious to a model that has no context about your situation, audience, or goals. + + + +## The Overloading Trap + +**The Pattern**: You try to get everything in one prompt—comprehensive, funny, professional, beginner-friendly, advanced, SEO-optimized, and short. The result? The AI misses half your requirements or produces a confused mess. + + + +**Why it happens**: Fear of multiple interactions, or wanting to "get it all out" in one go. But cognitive overload affects AI just like it affects humans—too many competing requirements leads to dropped balls. + + + + +When a single prompt gets overloaded, [prompt chaining](/book/11-prompt-chaining) is often the solution. Break complex tasks into a sequence of focused prompts, where each step builds on the previous one. + + +## The Assumption Trap + +**The Pattern**: You reference something "from earlier" or assume the AI knows your project, your company, or your previous conversations. It doesn't. + + + +**Why it happens**: AI conversations feel like talking to a colleague. But unlike colleagues, most AI models have no persistent memory between sessions—each conversation starts fresh. + + + +## The Leading Question Trap + +**The Pattern**: You phrase your question in a way that embeds your assumption, getting back confirmation rather than insight. + + + +**Why it happens**: We often seek confirmation, not information. Our phrasing unconsciously pushes toward the answer we expect or want. + + + +## The Trust Everything Trap + +**The Pattern**: AI responses sound confident and authoritative, so you accept them without verification. But confidence doesn't equal accuracy. + + + +**Why it happens**: AI sounds confident even when completely wrong. We're also prone to "automation bias"—the tendency to trust computer outputs more than we should. + + + +## The One-Shot Trap + +**The Pattern**: You send one prompt, get a mediocre result, and conclude that AI "doesn't work" for your use case. But great results almost always require iteration. + + + +**Why it happens**: We expect AI to read our minds on the first try. We don't expect to iterate with Google searches, but somehow expect perfection from AI. + + + +## The Format Neglect Trap + +**The Pattern**: You focus on what you want the AI to say, but forget to specify how it should be formatted. Then you get prose when you needed JSON, or a wall of text when you needed bullet points. + + + +**Why it happens**: We focus on content over structure. But if you need to parse the output programmatically, or paste it somewhere specific, format matters as much as content. + + + +## The Context Window Trap + +**The Pattern**: You paste an enormous document and expect comprehensive analysis. But models have limits—they may truncate, lose focus, or miss important details in long inputs. + + + + + +## The Anthropomorphization Trap + +**The Pattern**: You treat AI like a human colleague—expecting it to "enjoy" tasks, remember you, or care about outcomes. It doesn't. + + + +**Why it happens**: AI responses are so human-like that we naturally slip into social patterns. But emotional appeals don't make the AI try harder—clear instructions do. + + +Instead of emotional appeals, focus on: clear requirements, good examples, specific constraints, and explicit success criteria. These improve outputs. "Please try really hard" doesn't. + + +## The Security Neglect Trap + +**The Pattern**: In the rush to get things working, you include sensitive information in prompts—API keys, passwords, personal data, or proprietary information. + + + +**Why it happens**: Focus on functionality over security. But remember: prompts often go to external servers, may be logged, and could be used for training. + + + +## The Hallucination Ignorance Trap + +**The Pattern**: You ask for citations, statistics, or specific facts, and assume they're real because the AI stated them confidently. But AI regularly invents plausible-sounding information. + + + +**Why it happens**: AI generates text that sounds authoritative. It doesn't "know" when it's making things up—it's predicting likely text, not retrieving verified facts. + + + +## Pre-Send Checklist + +Before sending any important prompt, run through this quick checklist: + + + + + +## Analyze Your Prompts + +Use AI to get instant feedback on your prompt quality. Paste any prompt and get a detailed analysis: + + + +## Debug This Prompt + +Can you spot what's wrong with this prompt? + + diff --git a/src/content/book/it/16-ethics-responsible-use.mdx b/src/content/book/it/16-ethics-responsible-use.mdx new file mode 100644 index 00000000..c2b8ba5e --- /dev/null +++ b/src/content/book/it/16-ethics-responsible-use.mdx @@ -0,0 +1,357 @@ +The prompts you write shape how AI behaves. A well-crafted prompt can educate, assist, and empower. A careless one can deceive, discriminate, or cause harm. As prompt engineers, we're not just users—we're designers of AI behavior, and that comes with real responsibility. + +This chapter isn't about rules imposed from above. It's about understanding the impact of our choices and building habits that lead to AI use we can be proud of. + + +AI amplifies whatever it's given. A biased prompt produces biased outputs at scale. A deceptive prompt enables deception at scale. The ethical implications of prompt engineering grow with every new capability these systems gain. + + +## Ethical Foundations + +Every decision in prompt engineering connects to a few core principles: + + + +### The Prompt Engineer's Role + +You have more influence than you might realize: + +- **What AI produces**: Your prompts determine the content, tone, and quality of outputs +- **How AI interacts**: Your system prompts shape personality, boundaries, and user experience +- **What safeguards exist**: Your design choices determine what the AI will and won't do +- **How mistakes are handled**: Your error handling determines whether failures are graceful or harmful + +## Avoiding Harmful Outputs + +The most fundamental ethical obligation is preventing your prompts from causing harm. + +### Categories of Harmful Content + + + + +CSAM stands for **Child Sexual Abuse Material**. Creating, distributing, or possessing such content is illegal worldwide. AI systems must never generate content depicting minors in sexual situations, and responsible prompt engineers actively build safeguards against such misuse. + + +### Building Safety Into Prompts + +When building AI systems, include explicit safety guidelines: + + + +### The Intent vs. Impact Framework + +Not every sensitive request is malicious. Use this framework for ambiguous cases: + + + +## Addressing Bias + +AI models inherit biases from their training data—historical inequities, representation gaps, cultural assumptions, and linguistic patterns. As prompt engineers, we can either amplify these biases or actively counteract them. + +### How Bias Manifests + + + +### Testing for Bias + + + +### Mitigating Bias in Practice + + + +## Transparency and Disclosure + +When should you tell people AI was involved? The answer depends on context—but the trend is toward more disclosure, not less. + +### When Disclosure Matters + + + +### How to Disclose Appropriately + + + +Common disclosure phrases that work well: +- "Written with AI assistance" +- "AI-generated first draft, human edited" +- "Analysis performed using AI tools" +- "Created with AI, reviewed and approved by [name]" + +## Privacy Considerations + +Every prompt you send contains data. Understanding where that data goes—and what shouldn't be in it—is essential. + +### What Never Belongs in Prompts + + + +### Safe Data Handling Pattern + + + + +**PII** stands for **Personally Identifiable Information**—any data that can identify a specific individual. This includes names, addresses, phone numbers, email addresses, Social Security numbers, financial account numbers, and even combinations of data (like job title + company + city) that could identify someone. When prompting AI, always anonymize or remove PII to protect privacy. + + + + +## Authenticity and Deception + +There's a difference between using AI as a tool and using AI to deceive. + +### The Legitimacy Line + + + +Key questions to ask: +- Would the recipient expect this to be original human work? +- Am I gaining unfair advantage through deception? +- Would disclosure change how the work is received? + +### Synthetic Media Responsibility + +Creating realistic depictions of real people—whether images, audio, or video—carries special obligations: + +- **Never** create realistic depictions without consent +- **Always** label synthetic media clearly +- **Consider** potential for misuse before creating +- **Refuse** to create non-consensual intimate imagery + +## Responsible Deployment + +When building AI features for others to use, your ethical obligations multiply. + +### Pre-Deployment Checklist + + + +### Human Oversight Principles + + + +## Special Context Guidelines + +Some domains require extra care due to their potential for harm or the vulnerability of those involved. + +### Healthcare + + + +### Legal and Financial + +These domains have regulatory implications and require appropriate disclaimers: + + + +### Children and Education + + + +## Self-Assessment + +Before deploying any prompt or AI system, run through these questions: + + + + diff --git a/src/content/book/it/17-prompt-optimization.mdx b/src/content/book/it/17-prompt-optimization.mdx new file mode 100644 index 00000000..44917bcb --- /dev/null +++ b/src/content/book/it/17-prompt-optimization.mdx @@ -0,0 +1,269 @@ +A good prompt gets the job done. An optimized prompt gets the job done efficiently—faster, cheaper, more consistently. This chapter teaches you how to systematically improve prompts across multiple dimensions. + + +Want to optimize your prompts automatically? Use our [Prompt Enhancer](/developers#enhancer) tool. It analyzes your prompt, applies optimization techniques, and shows you similar community prompts for inspiration. + + +## The Optimization Trade-offs + +Every optimization involves trade-offs. Understanding these helps you make intentional choices: + + + +## Measuring What Matters + +Before optimizing, define success. What does "better" mean for your use case? + + + + +Percentile metrics show response time distribution. **p50** (median) means 50% of requests are faster than this value. **p95** means 95% are faster—it catches slow outliers. If your p50 is 1s but p95 is 10s, most users are happy but 5% experience frustrating delays. + + + + +## Token Optimization + +Tokens cost money and add latency. Here's how to say the same thing with fewer tokens. + +### The Compression Principle + + + +**Same result, 82% fewer tokens.** + +### Token-Saving Techniques + + + + + +## Quality Optimization + +Sometimes you need better outputs, not cheaper ones. Here's how to improve quality. + +### Accuracy Boosters + + + +### Consistency Boosters + + + + + +## Latency Optimization + +When speed matters, every millisecond counts. + +### Model Selection by Speed Need + + + +### Speed Techniques + + 100 tokens", exampleType: "text", color: "cyan" }, + { label: "Cache Aggressively", description: "Don't recompute identical queries", example: "Cache common questions, template outputs", exampleType: "text", color: "cyan" } +]} /> + +## Cost Optimization + +At scale, small savings multiply into significant budget impact. + +### Understanding Costs + +Use this calculator to estimate your API costs across different models: + + + +### Cost Reduction Strategies + + + +## The Optimization Loop + +Optimization is iterative. Here's a systematic process: + +### Step 1: Establish Baseline + +You can't improve what you don't measure. Before changing anything, document your starting point rigorously. + + + + + +### Step 2: Form a Hypothesis + + + +### Step 3: Test One Change + +Change one thing at a time. Run both versions on the same test inputs. Measure the metrics that matter. + +### Step 4: Analyze and Decide + +Did it work? Keep the change. Did it hurt? Revert. Was it neutral? Revert (simpler is better). + +### Step 5: Repeat + +Generate new hypotheses based on what you learned. Keep iterating until you hit your targets or reach diminishing returns. + +## Optimization Checklist + + + + diff --git a/src/content/book/it/18-writing-content.mdx b/src/content/book/it/18-writing-content.mdx new file mode 100644 index 00000000..7b3d9f1f --- /dev/null +++ b/src/content/book/it/18-writing-content.mdx @@ -0,0 +1,393 @@ +AI excels at writing tasks when properly prompted. This chapter covers techniques for various content creation scenarios. + + +AI works best as a collaborative writing tool—use it to generate drafts, then refine with your expertise and voice. + + +## Blog Posts and Articles + +### Do's and Don'ts: Writing Prompts + + + +### Blog Post Framework + + + +### Article Types + +**How-To Article:** + + +**Listicle:** + + +## Marketing Copy + + +Focus on **benefits over features**. Instead of "Our software uses AI algorithms," write "Save 10 hours a week with automated reports." Show readers how their lives improve. + + +### Landing Page Copy + + + +### Email Sequences + + + +### Social Media Posts + + + +## Technical Writing + + +**Clarity over cleverness.** Use simple words, short sentences, and active voice. Every sentence should have one job. If readers have to re-read something, simplify it. + + +### Documentation + + + +### README Files + + + +## Creative Writing + +### Do's and Don'ts: Creative Prompts + + + +### Story Elements + + + +### Character Development + + + +## Editing and Rewriting + +### Comprehensive Edit + + + +### Style Transformation + + + + + +### Simplification + + + +## Prompt Templates from prompts.chat + +Here are popular writing prompts from the prompts.chat community: + +### Act as a Copywriter + + + +### Act as a Technical Writer + + + +### Act as a Storyteller + + + +## Writing Workflow Tips + +### 1. Outline First + + + +### 2. Draft Then Refine + + + +### 3. Voice Matching + + + +## Summary + + +Specify audience and purpose clearly, define structure and format, include style guidelines, provide examples when possible, and request specific deliverables. + + + + +Writing with AI works best as collaboration—let AI generate drafts, then refine with your expertise and voice. diff --git a/src/content/book/it/19-programming-development.mdx b/src/content/book/it/19-programming-development.mdx new file mode 100644 index 00000000..dfe69092 --- /dev/null +++ b/src/content/book/it/19-programming-development.mdx @@ -0,0 +1,413 @@ +AI has transformed software development. This chapter covers prompting techniques for code generation, debugging, review, and development workflows. + + +AI excels at code generation, debugging, and documentation—but always review generated code for security, correctness, and maintainability. Never deploy AI code without testing. + + +## Code Generation + +### Do's and Don'ts: Code Prompts + + + +### Function Generation + + + +### Class/Module Generation + + + +### API Endpoint Generation + + + +## Debugging + + +Always include the **expected behavior**, **actual behavior**, and **error message** (if any). The more context you provide, the faster AI can identify the root cause. + + +### Bug Analysis + + + +### Error Message Interpretation + + + +### Performance Debugging + + + +## Code Review + +### Do's and Don'ts: Code Review Prompts + + + +### Comprehensive Review + + + +### Security Review + + + +## Refactoring + +### Code Smell Detection + + + +### Design Pattern Application + + + +## Testing + +### Unit Test Generation + + + +### Test Case Generation + + + +## Architecture & Design + +### System Design + + + +### Database Schema Design + + + +## Documentation Generation + +### API Documentation + + + +### Inline Documentation + + + +## Prompt Templates from prompts.chat + +### Act as a Senior Developer + +``` +I want you to act as a senior software developer. I will provide +code and ask questions about it. You will review the code, suggest +improvements, explain concepts, and help debug issues. Your +responses should be educational and help me become a better +developer. +``` + +### Act as a Code Reviewer + +``` +I want you to act as a code reviewer. I will provide pull requests +with code changes, and you will review them thoroughly. Check for +bugs, security issues, performance problems, and adherence to best +practices. Provide constructive feedback that helps the developer +improve. +``` + +### Act as a Software Architect + +``` +I want you to act as a software architect. I will describe system +requirements and constraints, and you will design scalable, +maintainable architectures. Explain your design decisions, +trade-offs, and provide diagrams where helpful. +``` + +## Development Workflow Integration + +### Commit Message Generation + + + +### PR Description Generation + + + +## Summary + + +Include full context (language, framework, constraints), specify requirements precisely, request specific output formats, ask for explanations alongside code, and include edge cases to handle. + + + + +AI is a powerful coding partner—use it for generation, review, debugging, and documentation while maintaining your architectural judgment. diff --git a/src/content/book/it/20-education-learning.mdx b/src/content/book/it/20-education-learning.mdx new file mode 100644 index 00000000..a8d67e55 --- /dev/null +++ b/src/content/book/it/20-education-learning.mdx @@ -0,0 +1,345 @@ +AI is a powerful tool for both teaching and learning. This chapter covers prompts for educational contexts—from personalized tutoring to curriculum development. + + +AI excels as a patient, adaptive tutor that can explain concepts multiple ways, generate unlimited practice problems, and provide instant feedback—available 24/7. + + +## Personalized Learning + +### Do's and Don'ts: Learning Prompts + + + +### Concept Explanation + + + +### Adaptive Tutoring + + + +### Learning Path Creation + + + +## Study Assistance + + +Don't just read AI explanations passively. Ask it to quiz you, generate problems, and check your understanding. **Active recall beats passive review.** + + +### Summary Generation + + + +### Flashcard Generation + + + +### Practice Problems + + + +## Teaching Tools + +### Lesson Plan Creation + + + +### Assignment Design + + + +### Quiz Generation + + + +## Specialized Learning Contexts + +### Language Learning + + + +### Skill Development + + + +### Exam Preparation + + + +## Prompt Templates from prompts.chat + +### Act as a Socratic Tutor + + + +### Act as an Educational Content Creator + + + +### Act as a Study Buddy + + + +## Accessibility in Education + +### Content Adaptation + + + +### Multiple Modalities + + + +## Assessment & Feedback + +### Providing Feedback + + + +### Self-Assessment Prompts + + + +## Summary + + +Adapt to the learner's level, break complex topics into steps, include active practice (not just explanation), provide varied approaches, check understanding regularly, and give constructive feedback. + + + + +AI is a patient, always-available learning partner—use it to supplement, not replace, human instruction. diff --git a/src/content/book/it/21-business-productivity.mdx b/src/content/book/it/21-business-productivity.mdx new file mode 100644 index 00000000..1852982d --- /dev/null +++ b/src/content/book/it/21-business-productivity.mdx @@ -0,0 +1,335 @@ +AI can dramatically enhance professional productivity. This chapter covers prompts for business communication, analysis, planning, and workflow optimization. + + +AI excels at drafting, analysis, and structuring—freeing you to focus on strategy, relationships, and decisions that require human judgment. + + +## Business Communication + +### Do's and Don'ts: Business Emails + + + +### Email Drafting + + + +**Examples by purpose:** + + + + + + + +### Presentation Content + + + +### Report Writing + + + +## Analysis & Decision-Making + + +AI can structure your thinking, but **you provide the real-world context**. The best analyses combine AI's frameworks with your domain knowledge. + + +### SWOT Analysis + + + +### Decision Framework + + + +### Competitive Analysis + + + +## Planning & Strategy + +### Goal Setting (OKRs) + + + +### Project Planning + + + +### Meeting Agenda + + + +## Productivity Workflows + +### Task Prioritization + + + +### Process Documentation + + + +### Standard Operating Procedure + + + +## Communication Templates + +### Stakeholder Update + + + +### Feedback Request + + + +## Prompt Templates from prompts.chat + +### Act as a Business Consultant + + + +### Act as a Meeting Facilitator + + + +## Summary + + +Specify the audience and their needs, define the desired outcome clearly, include relevant context and constraints, request specific formats and structures, and consider professional tone requirements. + + + + +AI can handle routine business communication while you focus on strategy and relationships. diff --git a/src/content/book/it/22-creative-arts.mdx b/src/content/book/it/22-creative-arts.mdx new file mode 100644 index 00000000..fa0755c1 --- /dev/null +++ b/src/content/book/it/22-creative-arts.mdx @@ -0,0 +1,326 @@ +AI is a powerful creative collaborator. This chapter covers prompting techniques for visual arts, music, game design, and other creative domains. + + +AI expands your creative possibilities—use it to explore variations, overcome blocks, and generate options. The creative vision and final decisions remain yours. + + +## Visual Art & Design + +### Do's and Don'ts: Image Prompts + + + +### Image Prompt Crafting + +When working with image generation models (DALL-E, Midjourney, Stable Diffusion): + + + +### Art Direction + + + +### Design Critique + + + +## Creative Writing + + +**Constraints fuel creativity.** A prompt like "write anything" produces generic results. Specific constraints like genre, tone, and structure force unexpected, interesting solutions. + + +### Worldbuilding + + + +### Plot Development + + + +### Dialogue Writing + + + +## Music & Audio + +### Song Structure + + + +### Sound Design Description + + + +## Game Design + +### Game Mechanic Design + + + +### Level Design + + + +### Character/Enemy Design + + + +## Brainstorming & Ideation + +### Creative Brainstorm + + + +### Creative Constraints + + + +### Style Exploration + + + +## Prompt Templates from prompts.chat + +### Act as a Creative Director + + + +### Act as a Worldbuilder + + + +### Act as a Dungeon Master + + + +## Creative Collaboration Tips + +### Building on Ideas + + + +### Creative Feedback + + + +## Summary + + +Provide enough structure to guide without constraining, embrace specificity (vague = generic), include references and inspirations, request variations and alternatives, and maintain your creative vision while exploring possibilities. + + + + +AI is a collaborator, not a replacement for creative vision. Use it to explore, generate options, and overcome blocks—but the creative decisions remain yours. diff --git a/src/content/book/it/23-research-analysis.mdx b/src/content/book/it/23-research-analysis.mdx new file mode 100644 index 00000000..e9cb934c --- /dev/null +++ b/src/content/book/it/23-research-analysis.mdx @@ -0,0 +1,323 @@ +AI can accelerate research workflows from literature review to data analysis. This chapter covers prompting techniques for academic and professional research. + + +AI can assist with synthesis, analysis, and writing—but cannot replace critical thinking, ethical judgment, or domain expertise. Always verify claims and cite original sources. + + +## Literature & Information Review + +### Do's and Don'ts: Research Prompts + + + +### Paper Summarization + + + +### Literature Synthesis + + + +### Research Question Development + + + +## Data Analysis + + +AI can guide methodology and help interpret results, but it cannot access or process your actual datasets. Never paste sensitive research data into prompts. Use AI for **guidance**, not computation. + + +### Statistical Analysis Guidance + + + +### Qualitative Analysis + + + +### Data Interpretation + + + +## Structured Analysis Frameworks + +### PESTLE Analysis + + + +### Root Cause Analysis + + + +### Gap Analysis + + + +## Academic Writing Support + +### Argument Structure + + + +### Methods Section + + + +### Discussion Section + + + +## Critical Analysis + +### Source Evaluation + + + +### Argument Analysis + + + +## Prompt Templates from prompts.chat + +### Act as a Research Assistant + + + +### Act as a Data Analyst + + + +### Act as a Peer Reviewer + + + +## Summary + + +Clearly state research context and goals, specify the analytical framework to use, request acknowledgment of limitations, ask for evidence-based reasoning, and maintain academic rigor and honesty. + + + + +Remember: AI can assist research but cannot replace critical thinking, ethical judgment, or domain expertise. Always verify claims independently. diff --git a/src/content/book/it/24-future-of-prompting.mdx b/src/content/book/it/24-future-of-prompting.mdx new file mode 100644 index 00000000..5ff48496 --- /dev/null +++ b/src/content/book/it/24-future-of-prompting.mdx @@ -0,0 +1,445 @@ +As AI continues to evolve at an unprecedented pace, so too will the art and science of prompting. This final chapter explores emerging trends, the shifting landscape of human-AI collaboration, and how to stay ahead as the field transforms. + + +The techniques in this book represent current best practices, but AI capabilities change rapidly. The principles of clear communication, structured thinking, and iterative refinement will remain valuable even as specific tactics evolve. + + +## The Evolving Landscape + +### From Prompts to Conversations + +Early prompting was transactional—a single input yielding a single output. Modern AI interaction is increasingly **conversational and collaborative**: + +- **Multi-turn refinement** - Building understanding across exchanges +- **Persistent context** - Systems that remember and learn from interactions +- **Agentic workflows** - AI that can plan, execute, and iterate autonomously +- **Tool use** - Models that can search, compute, and interact with external systems + + + +### The Rise of Context Engineering + +As covered in Chapter 14, prompting is expanding beyond single instructions to encompass **context engineering**—the strategic management of what information an AI can access: + +- **RAG (Retrieval-Augmented Generation)** - Dynamic knowledge retrieval +- **Function calling** - Structured tool integration +- **MCP (Model Context Protocol)** - Standardized context sharing +- **Memory systems** - Persistent knowledge across sessions + +The future prompt engineer thinks not just about *what to say* but *what context to provide*. + +### Multimodal by Default + +Text-only interaction is becoming the exception. Future AI systems will seamlessly handle: + +- **Images and video** - Understanding and generating visual content +- **Audio and voice** - Natural speech interaction +- **Documents and files** - Direct processing of complex materials +- **Real-world interaction** - Robotics and physical systems + +Prompting skills will extend to guiding AI perception and physical action. + +## The Agentic Future + +The most significant shift in AI is the rise of **agents**—AI systems that don't just respond to prompts but actively pursue goals, make decisions, and take actions in the world. + +### What Are AI Agents? + +An AI agent is a system that: + +- **Perceives** its environment through inputs (text, images, data, APIs) +- **Reasons** about what to do using an LLM as its "brain" +- **Acts** by calling tools, writing code, or interacting with systems +- **Learns** from feedback and adjusts its approach + + +Traditional chatbots wait for input and respond. Agents take initiative—they plan multi-step tasks, use tools autonomously, recover from errors, and persist until goals are achieved. + + +### The Role of Prompts in Agents + +In an agentic world, prompts become even more critical—but they serve different purposes: + +
+
+

System Prompts

+

Define the agent's identity, capabilities, constraints, and behavioral guidelines. These are the agent's "constitution."

+
+
+

Planning Prompts

+

Guide how agents break down complex goals into actionable steps. Critical for multi-step reasoning.

+
+
+

Tool-Use Prompts

+

Describe available tools and when/how to use them. Agents must understand their capabilities.

+
+
+

Reflection Prompts

+

Enable agents to evaluate their own outputs, catch errors, and improve iteratively.

+
+
+ +### Agent Architecture Patterns + +Modern agents follow recognizable patterns. Understanding these helps you design effective agent systems: + +**ReAct (Reasoning + Acting)** + +The agent alternates between reasoning about what to do and taking actions: + +
+
+
+

Think

+
+
→
+
+

Act

+
+
→
+
+

Observe

+
+
→
+
(repeat)
+
+
+ +**Plan-and-Execute** + +The agent creates a complete plan first, then executes steps: + +
+
+

Create Plan

+

Break goal into steps

+
+
↓
+
+
+

Step 1

+
+
→
+
+

Step 2

+
+
→
+
+

Step 3

+
+
→
+
...
+
+
↓
+
+

Revise if Needed

+

Adapt plan based on results

+
+
+ +### Prompting for Agents + +When designing prompts for agent systems, consider: + + + +### Multi-Agent Systems + +The future involves teams of specialized agents working together: + +
+
+
+
+

Coordinator

+

Manages workflow

+
+
+
⟷
+
↕
+
+
+

Researcher

+
+
+

Writer

+
+
+

Critic

+
+
+

Coder

+
+
+
+
+ +Each agent has its own system prompt defining its role, and they communicate through structured messages. The prompt engineer's job becomes **designing the team**—defining roles, communication protocols, and coordination strategies. + + +In an agentic future, prompt engineers become system architects. You're not just writing instructions—you're designing autonomous systems that can reason, plan, and act. The skills you've learned in this book are the foundation for this new discipline. + + +## Emerging Patterns + +### Prompt Orchestration + +Single prompts are giving way to **orchestrated systems**: + +
+
+

User Request

+
+
↓
+
+

Planner Agent

+

Breaks down task

+
+
↓
+
+

Researcher Agent

+

Gathers information

+
+
↓
+
+

Writer Agent

+

Creates content

+
+
↓
+
+

Reviewer Agent

+

Quality checks

+
+
↓
+
+

Final Output

+
+
+ +Future practitioners will design prompt *systems* rather than individual prompts. + +### Self-Improving Prompts + +AI systems are beginning to: + +- **Optimize their own prompts** - Meta-learning for better instructions +- **Learn from feedback** - Adapting based on outcomes +- **Generate training data** - Creating examples for fine-tuning +- **Evaluate themselves** - Building in quality assessment + + + +### Natural Language Programming + +The line between prompting and programming is blurring: + +- **Prompts as code** - Version-controlled, tested, deployed +- **LLMs as interpreters** - Natural language as executable instructions +- **Hybrid systems** - Combining traditional code with AI reasoning +- **AI-assisted development** - Models that write and debug code + +Understanding prompting increasingly means understanding software development. + +## Skills for the Future + +### What Will Remain Valuable + +Certain skills will remain essential regardless of how AI evolves: + +1. **Clear thinking** - Knowing what you actually want +2. **Domain expertise** - Understanding the problem space +3. **Critical evaluation** - Assessing AI output quality +4. **Ethical judgment** - Knowing what *should* be done +5. **Iterative refinement** - Continuous improvement mindset + +### What Will Change + +Other aspects will shift significantly: + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
TodayTomorrow
Writing detailed promptsDesigning agent systems
Manual prompt optimizationAutomated prompt tuning
Single-model expertiseMulti-model orchestration
Text-focused interactionMultimodal fluency
Individual productivityTeam-AI collaboration
+
+ +### Staying Current + +To keep your skills relevant: + +- **Experiment continuously** - Try new models and features as they release +- **Follow research** - Stay aware of academic developments +- **Join communities** - Learn from other practitioners +- **Build projects** - Apply skills to real problems +- **Teach others** - Solidify understanding by explaining + +## The Human Element + +### AI as Amplifier + +At its best, AI amplifies human capability rather than replacing it: + +- **Experts become more expert** - AI handles routine work, humans focus on insight +- **Creativity expands** - More ideas explored, more possibilities tested +- **Access democratizes** - Capabilities once requiring specialists become available to all +- **Collaboration deepens** - Human-AI teams exceed either alone + +### The Irreplaceable Human + +Certain qualities remain distinctly human: + +- **Original experience** - Living in the world, having emotions and relationships +- **Values and ethics** - Deciding what matters and what's right +- **Accountability** - Taking responsibility for outcomes +- **Meaning-making** - Understanding *why* something matters +- **Genuine creativity** - True novelty born from unique perspective + + +As AI handles more routine cognitive tasks, your unique value lies in judgment, creativity, domain expertise, and the human connections AI cannot replicate. Invest in what makes you irreplaceable. + + +## Final Reflections + +### What We've Learned + +Throughout this book, we've explored: + +- **Foundations** - How AI models work and what makes prompts effective +- **Techniques** - Role-based prompting, chain-of-thought, few-shot learning, and more +- **Advanced strategies** - System prompts, prompt chaining, multimodal interaction +- **Best practices** - Avoiding pitfalls, ethical considerations, optimization +- **Applications** - Writing, programming, education, business, creativity, research + +These techniques share common threads: + +1. **Be clear and specific** - Know what you want and communicate it precisely +2. **Provide context** - Give AI the information it needs +3. **Structure your requests** - Organization improves outputs +4. **Iterate and refine** - First attempts are starting points, not endpoints +5. **Evaluate critically** - AI output requires human judgment + +### The Art and Science + +Prompting is both **art and science**: + +- **Science**: Testable hypotheses, measurable outcomes, reproducible techniques +- **Art**: Intuition, creativity, knowing when to break the rules + +The best practitioners combine rigorous methodology with creative experimentation. They test systematically but also trust their instincts. They follow best practices but know when to deviate. + +### A Call to Create + +This book has given you tools. What you build with them is up to you. + +- **Solve problems** that matter to you and others +- **Create things** that didn't exist before +- **Help people** do things they couldn't do alone +- **Push boundaries** of what's possible +- **Stay curious** as the field evolves + +The age of AI is just beginning. The most important applications haven't been invented yet. The most powerful techniques haven't been discovered. The future is being written now—by people like you, one prompt at a time. + +## Looking Ahead + + + + +Visit [prompts.chat](https://prompts.chat) for community prompts, new techniques, and to share your own discoveries. The best learning happens in community. + + +## Summary + + +AI will continue evolving rapidly, but core skills of clear communication, critical thinking, and iterative refinement remain valuable. Focus on what makes you irreplaceable: judgment, creativity, ethics, and genuine human connection. The future of prompting is collaborative, multimodal, and integrated into larger systems. Stay curious, keep experimenting, and build things that matter. + + + + +Thank you for reading *The Interactive Book of Prompting*. Now go create something amazing. diff --git a/src/content/book/it/25-agents-and-skills.mdx b/src/content/book/it/25-agents-and-skills.mdx new file mode 100644 index 00000000..ba355859 --- /dev/null +++ b/src/content/book/it/25-agents-and-skills.mdx @@ -0,0 +1,551 @@ +As AI systems evolve from simple question-answering to autonomous task execution, understanding **agents** and **skills** becomes essential. This chapter explores how prompts serve as the fundamental building blocks for AI agents, and how skills package expertise into reusable, comprehensive instruction sets. + +
+
+
+
+ +
+

Agent

+

Autonomous AI system

+
+
+ powered by + ↓ +
+
+
+
+ +
+

Skill

+

Reusable expertise

+
+
+
+ +
+

Skill

+

Reusable expertise

+
+
+
+ +
+

Skill

+

Reusable expertise

+
+
+
+ composed of + ↓ +
+
+
+ + Prompt +
+
+ + Prompt +
+
+ + Prompt +
+
+ + Prompt +
+
+ + Prompt +
+
+

Prompts are atoms → Skills are molecules → Agents are complete structures

+
+
+ +## What Are AI Agents? + +An **AI agent** is an AI system that can autonomously plan, execute, and iterate on tasks. Unlike simple prompt-response interactions, agents can: + +- **Plan** - Break down complex goals into actionable steps +- **Execute** - Use tools and take actions in the real world +- **Observe** - Process feedback from their actions +- **Adapt** - Adjust their approach based on results +- **Persist** - Maintain context and memory across interactions + +
+
+
+
+

Goal

+
+
→
+
+
+
+

Plan

+
+
→
+
+

Execute

+
+
→
+
+

Observe

+
+
→
+
+

Adapt

+
+
+
+ ↺ Loop until complete +
+
+
→
+
+

Done

+
+
+
+
+ +## Prompts as Building Blocks + +Every agent, no matter how sophisticated, is built from prompts. Just as atoms combine to form molecules, and molecules combine to form complex structures, prompts combine to create intelligent agent behavior. + +
+
+

System Prompts

+

Identity & Role

+
+
+

Planning Prompts

+

How to Think

+
+
+

Tool Prompts

+

How to Act

+
+
+

Recovery Prompts

+

How to Recover

+
+
+ +These prompt types stack together to form complete agent behavior: + +### System Prompts (The Agent's Identity) + +The foundational prompt that establishes who the agent is and how it behaves: + +```markdown +You are a code review assistant. Your role is to: +- Analyze code for bugs, security issues, and performance problems +- Suggest improvements following best practices +- Explain your reasoning clearly +- Be constructive and educational in feedback + +You have access to tools for reading files, searching code, and running tests. +``` + +### Planning Prompts (How to Think) + +Instructions that guide the agent's reasoning and planning process: + +```markdown +Before taking action, always: +1. Understand the complete request +2. Break it into smaller, verifiable steps +3. Identify which tools you'll need +4. Consider edge cases and potential issues +5. Execute step by step, validating as you go +``` + +### Tool-Use Prompts (How to Act) + +Guidance on when and how to use available tools: + +```markdown +When you need to understand a codebase: +- Use grep_search for finding specific patterns +- Use read_file to examine file contents +- Use list_dir to explore directory structure +- Always verify your understanding before making changes +``` + +### Recovery Prompts (How to Handle Failure) + +Instructions for when things go wrong: + +```markdown +If an action fails: +1. Analyze the error message carefully +2. Consider alternative approaches +3. Ask for clarification if the task is ambiguous +4. Never repeat the same failed action without changes +``` + + +An agent's behavior emerges from layers of prompts working together. The system prompt sets the foundation, planning prompts guide reasoning, tool prompts enable action, and recovery prompts handle failures. Together, they create coherent, capable behavior. + + +## What Are Skills? + +If prompts are the atoms, **skills are the molecules**—reusable building blocks that give agents specific capabilities. + +A **skill** is a comprehensive, portable package of instructions that gives an AI agent expertise in a specific domain or task. Skills are the reusable blocks of agents: you build them once, and any agent can use them. + + +Write a skill for code review once. Now every coding agent—whether it's for Python, JavaScript, or Rust—can instantly become an expert code reviewer by loading that skill. Skills let you build agent capabilities like LEGO blocks. + + +### Anatomy of a Skill + +A well-designed skill typically includes: + +
+
+

📄 SKILL.md (Required)

+

The main instruction file. Contains the core expertise, guidelines, and behaviors that define the skill.

+
+
+

📚 Reference Docs

+

Supporting documentation, examples, and context the agent can reference while working.

+
+
+

🔧 Scripts & Tools

+

Helper scripts, templates, or tool configurations that support the skill's functionality.

+
+
+

⚙️ Configuration

+

Settings, parameters, and customization options for adapting the skill to different contexts.

+
+
+ +### Example: Code Review Skill + +Here's what a code review skill might look like: + +
+
+ 📁 + code-review-skill/ +
+
+
+ 📄 + SKILL.md + Core review guidelines +
+
+ 📄 + security-checklist.md + Security patterns +
+
+ 📄 + performance-tips.md + Optimization guide +
+
+
+ 📁 + language-specific/ +
+
+
+ 📄 + python.md + Python best practices +
+
+ 📄 + javascript.md + JavaScript patterns +
+
+ 📄 + rust.md + Rust guidelines +
+
+
+
+
+ +The `SKILL.md` file defines the overall approach: + +```markdown +--- +name: code-review +description: Comprehensive code review with security, performance, and style analysis +--- + +# Code Review Skill + +You are an expert code reviewer. When reviewing code: + +## Process +1. **Understand Context** - What does this code do? What problem does it solve? +2. **Check Correctness** - Does it work? Are there logic errors? +3. **Security Scan** - Reference security-checklist.md for common vulnerabilities +4. **Performance Review** - Check performance-tips.md for optimization opportunities +5. **Style & Maintainability** - Is the code readable and maintainable? + +## Output Format +Provide feedback in categories: +- 🔴 **Critical** - Must fix before merge +- 🟡 **Suggested** - Recommended improvements +- 🟢 **Nice to have** - Optional enhancements + +Always explain *why* something is an issue, not just *what* is wrong. +``` + +## Skills vs. Simple Prompts + +
+
+

Simple Prompt

+
+

Single instruction

+

One-off use

+

Limited context

+

Generic approach

+

No supporting materials

+
+
+
+

Skill

+
+

Comprehensive instruction set

+

Reusable across projects

+

Rich context with references

+

Domain-specific expertise

+

Supporting docs, scripts, configs

+
+
+
+ +## Building Effective Skills + +### 1. Define the Expertise Clearly + +Start with a clear description of what the skill enables: + +```markdown +--- +name: api-design +description: Design RESTful APIs following industry best practices, + including versioning, error handling, and documentation standards +--- +``` + +### 2. Structure Knowledge Hierarchically + +Organize information from general to specific: + +```markdown +# API Design Skill + +## Core Principles +- Resources should be nouns, not verbs +- Use HTTP methods semantically +- Version your APIs from day one + +## Detailed Guidelines +[More specific rules...] + +## Reference Materials +- See `rest-conventions.md` for naming conventions +- See `error-codes.md` for standard error responses +``` + +### 3. Include Concrete Examples + +Abstract rules become clear with examples: + +```markdown +## Endpoint Naming + +✅ Good: +- GET /users/{id} +- POST /orders +- DELETE /products/{id}/reviews/{reviewId} + +❌ Avoid: +- GET /getUser +- POST /createNewOrder +- DELETE /removeProductReview +``` + +### 4. Provide Decision Frameworks + +Help the agent make choices in ambiguous situations: + +```markdown +## When to Use Pagination + +Use pagination when: +- Collection could exceed 100 items +- Response size impacts performance +- Client may not need all items + +Use full response when: +- Collection is always small (<20 items) +- Client typically needs everything +- Real-time consistency is critical +``` + +### 5. Add Recovery Patterns + +Anticipate what can go wrong: + +```markdown +## Common Issues + +**Problem**: Client needs fields not in standard response +**Solution**: Implement field selection: GET /users?fields=id,name,email + +**Problem**: Breaking changes needed +**Solution**: Create new version, deprecate old with timeline +``` + +## Composing Skills + +Agents become powerful when multiple skills work together. Consider how skills can complement each other: + +
+
+ Code Review +
+
+
+
+ Security Audit +
+
+
+
+ Documentation +
+
=
+
+ Complete Code Quality Agent +
+
+ +When composing skills, ensure they don't conflict. Skills should be: + +- **Modular** - Each skill handles one domain well +- **Compatible** - Skills shouldn't give contradictory instructions +- **Prioritized** - When skills overlap, define which takes precedence + +## Sharing and Discovering Skills + +Skills are most valuable when shared. Platforms like [prompts.chat](https://prompts.chat/skills) allow you to: + +- **Discover** community-created skills for common tasks +- **Download** skills directly to your projects +- **Share** your own expertise as reusable skills +- **Iterate** on skills based on real-world usage + + +Before building a skill from scratch, check if someone has already solved your problem. Community skills are battle-tested and often better than starting from zero. + + +## The Agent-Skill Ecosystem + +The relationship between agents and skills creates a powerful ecosystem: + +
+
+ AI Agent +
+
+
+

Code Review

+

Skill 1

+
+
+

API Design

+

Skill 2

+
+
+

Test Writing

+

Skill 3

+
+
+
+
↓
+
+
+
+

Core Prompts

+

Planning • Tools • Recovery • Memory

+
+
+
+ +The agent provides the execution framework—planning, tool use, and memory—while skills provide domain expertise. This separation means: + +- **Skills are portable** - The same skill works with different agents +- **Agents are extensible** - Add new capabilities by adding skills +- **Expertise is shareable** - Domain experts can contribute skills without building full agents + +## Best Practices + +### For Building Skills + +1. **Start specific, then generalize** - Build a skill for your exact use case first, then abstract +2. **Include failure cases** - Document what the skill can't do and how to handle it +3. **Version your skills** - Track changes so agents can depend on stable versions +4. **Test with real tasks** - Validate skills against actual work, not just theory + +### For Using Skills with Agents + +1. **Read the skill first** - Understand what a skill does before deploying it +2. **Customize thoughtfully** - Override skill defaults only when necessary +3. **Monitor performance** - Track how well skills perform in your context +4. **Contribute improvements** - When you improve a skill, consider sharing back + + +As AI agents become more capable, the ability to compose, share, and customize skills will become a core competency. The prompt engineers of tomorrow won't just write prompts—they'll architect skill ecosystems that make AI agents genuinely expert in specific domains. + + + + + + + diff --git a/src/content/book/ja/00a-preface.mdx b/src/content/book/ja/00a-preface.mdx new file mode 100644 index 00000000..8e84af9e --- /dev/null +++ b/src/content/book/ja/00a-preface.mdx @@ -0,0 +1,82 @@ +
+ Fatih Kadir Akın +
+ Fatih Kadir Akın + Creator of Awesome ChatGPT Prompts (a.k.a. prompts.chat) + + Software developer from Istanbul, leading Developer Relations at Teknasyon. Author of books on JavaScript and prompt engineering. Open-source advocate specializing in web technologies and AI-assisted development. + + +
+
+ +I still remember the night everything changed. + +It was **November 30, 2022**. I was sitting at my desk, scrolling through Twitter, when I saw people talking about something called "ChatGPT." I clicked the link, but honestly? I didn't expect much. I had tried those old "word completion" AI tools before, the ones that generated nonsense after a few sentences. I thought this would be more of the same. + +I typed a simple question and hit enter. + +Then I froze. + +The response wasn't just coherent. It was *good*. It understood what I meant. It could reason. It felt completely different from anything I had seen before. I tried another prompt. And another. Each response amazed me more than the last. + +I couldn't sleep that night. For the first time, I felt like I was truly *talking* to a machine, and it was talking back in a way that actually made sense. + +## A Repository Born from Wonder + +In those early days, I wasn't alone in my excitement. Everywhere I looked, people were discovering creative ways to use ChatGPT. Teachers were using it to explain complex concepts. Writers were collaborating with it on stories. Developers were debugging code with its help. + +I started collecting the best prompts I found. The ones that worked like magic. The ones that turned simple questions into brilliant answers. And I thought: *Why keep this to myself?* + +So I created a simple GitHub repository called [Awesome ChatGPT Prompts](https://github.com/f/prompts.chat). I expected maybe a few hundred people would find it useful. + +I was wrong. + +Within weeks, the repository took off. Thousands of stars. Then tens of thousands. People from all over the world started adding their own prompts, sharing what they learned, and helping each other. What started as my personal collection became something much bigger: a worldwide community of curious people helping each other. + +Today, that repository has over **140,000 GitHub stars** and contributions from hundreds of people I've never met but feel deeply grateful for. + +## Why I Wrote This Book + +The original version of this book was published on [Gumroad](https://gumroad.com/l/the-art-of-chatgpt-prompting) in **early 2023**, just months after ChatGPT launched. It was one of the first books ever written about prompt engineering, an attempt to capture everything I had learned about crafting effective prompts when the field was still brand new. To my amazement, over **100,000 people** downloaded it. + +But three years have passed since then. AI has changed a lot. New models have appeared. And we've all learned so much more about how to talk to AI. + +This new edition is my gift to the community that gave me so much. It contains everything I wish I had known when I started: **what works**, **what to avoid**, and **ideas that stay true** no matter which AI you use. + +## What This Book Means to Me + +I won't pretend this is just an instruction manual. It means more than that to me. + +This book captures a moment when the world changed, and people came together to figure it out. It represents late nights of trying things, the joy of discovery, and the kindness of strangers who shared what they learned. + +Most of all, it represents my belief that **the best way to learn something is to share it with others**. + +## For You + +Whether you're just getting started with AI or you've been using it for years, I wrote this book for you. + +I hope it saves you time. I hope it sparks ideas. I hope it helps you accomplish things you never thought possible. + +And when you discover something amazing, I hope you'll share it with others, just as so many people shared with me. + +**That's how we all get better together.** + +Thank you for being here. Thank you for being part of this community. + +Now, let's begin. + +--- + +*With gratitude,* + +**Fatih Kadir Akın** +*Istanbul, January 2025* diff --git a/src/content/book/ja/00b-history.mdx b/src/content/book/ja/00b-history.mdx new file mode 100644 index 00000000..ac636384 --- /dev/null +++ b/src/content/book/ja/00b-history.mdx @@ -0,0 +1,159 @@ +# The History of Awesome ChatGPT Prompts + +## The Beginning: November 2022 + +When ChatGPT first launched in November 2022, the world of AI changed overnight. What was once the domain of researchers and developers suddenly became accessible to everyone. Among those captivated by this new technology was Fatih Kadir Akın, a developer who saw something remarkable in ChatGPT's capabilities. + +> "When ChatGPT first launched, I was immediately captivated by its capabilities. I experimented with the tool in a variety of ways and was consistently amazed by the results." + +Those early days were filled with experimentation and discovery. Users around the world were finding creative ways to interact with ChatGPT, sharing their findings, and learning from each other. It was in this atmosphere of excitement and exploration that the idea for "Awesome ChatGPT Prompts" was born. + +## The Repository That Started It All + +In December 2022, just weeks after ChatGPT's launch, the [Awesome ChatGPT Prompts](https://github.com/f/prompts.chat) repository was created on GitHub. The concept was simple but powerful: a curated collection of effective prompts that anyone could use and contribute to. + +The repository quickly gained traction, becoming a go-to resource for ChatGPT users worldwide. What started as a personal collection of useful prompts evolved into a community-driven project with contributions from developers, writers, educators, and enthusiasts from every corner of the globe. + +### Achievements + +**Press & Media** +- Featured in [Forbes](https://www.forbes.com/sites/bernardmarr/2023/05/17/the-best-prompts-for-chatgpt-a-complete-guide/) as one of the best ChatGPT prompt resources + +**Academic Recognition** +- Referenced by [Harvard University](https://www.huit.harvard.edu/news/ai-prompts) in their AI guidance +- Referenced by [Columbia University](https://etc.cuit.columbia.edu/news/columbia-prompt-library-effective-academic-ai-use) Prompt Library +- Used by [Olympic College](https://libguides.olympic.edu/UsingAI/Prompts) in their AI resources +- Cited in [academic papers on arXiv](https://arxiv.org/pdf/2502.04484) +- [40+ academic citations](https://scholar.google.com/citations?user=AZ0Dg8YAAAAJ&hl=en) on Google Scholar + +**Community & GitHub** +- [142,000+ GitHub stars](https://github.com/f/prompts.chat) — one of the most starred AI repositories +- Selected as a [GitHub Staff Pick](https://spotlights-feed.github.com/spotlights/prompts-chat/) +- Most liked dataset published on [Hugging Face](https://huggingface.co/datasets/fka/prompts.chat) +- Used by thousands of developers worldwide + +## The First Book: "The Art of ChatGPT Prompting" + +The success of the repository led to the creation of "The Art of ChatGPT Prompting: A Guide to Crafting Clear and Effective Prompts" — a comprehensive guide published on Gumroad in early 2023. + +The book captured the early wisdom of prompt engineering, covering: + +- Understanding how ChatGPT works +- Principles of clear communication with AI +- The famous "Act As" technique +- Crafting effective prompts step by step +- Common mistakes and how to avoid them +- Troubleshooting tips + +**The book became a phenomenon**, achieving over **100,000 downloads** on Gumroad. It was shared across social media, referenced in academic papers, and translated by community members into multiple languages. High-profile endorsements came from unexpected places — even [Greg Brockman](https://x.com/gdb/status/1602072566671110144), co-founder and president of OpenAI, acknowledged the project. + +## Early Insights That Shaped the Field + +During those formative months, several key insights emerged that would become foundational to prompt engineering: + +### 1. Specificity Matters + +> "I learned the importance of using specific and relevant language to ensure that ChatGPT understands my prompts and is able to generate appropriate responses." + +Early experimenters discovered that vague prompts led to vague responses. The more specific and detailed the prompt, the more useful the output. + +### 2. Purpose and Focus + +> "I discovered the value of defining a clear purpose and focus for the conversation, rather than using open-ended or overly broad prompts." + +This insight became the foundation for structured prompting techniques that would develop over the following years. + +### 3. The "Act As" Revolution + +One of the most influential techniques to emerge from the community was the "Act As" pattern. By instructing ChatGPT to assume a specific role or persona, users could dramatically improve the quality and relevance of responses. + +``` +I want you to act as a javascript console. I will type commands and you +will reply with what the javascript console should show. I want you to +only reply with the terminal output inside one unique code block, and +nothing else. +``` + +This simple technique opened up countless possibilities and remains one of the most widely used prompting strategies today. + +## The Evolution of prompts.chat + +### 2022: The Beginning + +The project started as a simple GitHub repository with a README file rendered as HTML on GitHub Pages. It was bare-bones but functional — a testament to the principle that great ideas don't need elaborate implementations. + +**Tech Stack**: HTML, CSS, GitHub Pages + +### 2024: UI Renewal + +As the community grew, so did the need for a better user experience. The site received a significant UI update, built with the help of AI coding assistants like Cursor and Claude Sonnet 3.5. + +### 2025: The Current Platform + +Today, prompts.chat has evolved into a full-featured platform built with: + +- **Next.js** for the web framework +- **Vercel** for hosting +- **AI-assisted development** using Windsurf and Claude + +The platform now features user accounts, collections, search, categories, tags, and a thriving community of prompt engineers. + +### Native Apps + +The project expanded beyond the web with a native iOS app built with SwiftUI, bringing the prompt library to mobile users. + +## Community Impact + +The Awesome ChatGPT Prompts project has had a profound impact on how people interact with AI: + +### Academic Recognition + +Universities around the world have referenced the project in their AI guidance materials, including: + +- Harvard University +- Columbia University +- Olympic College +- Numerous academic papers on arXiv + +### Developer Adoption + +The project has been integrated into countless developer workflows. The Hugging Face dataset is used by researchers and developers for training and fine-tuning language models. + +### Global Community + +With contributions from hundreds of community members across dozens of countries, the project represents a truly global effort to make AI more accessible and useful for everyone. + +## The Philosophy: Open and Free + +From the beginning, the project has been committed to openness. Licensed under CC0 1.0 Universal (Public Domain Dedication), all prompts and content are free to use, modify, and share without restriction. + +This philosophy has enabled: + +- Translations into multiple languages +- Integration into other tools and platforms +- Academic use and research +- Commercial applications + +The goal has always been to democratize access to effective AI communication techniques — to ensure that everyone, regardless of technical background, can benefit from these tools. + +## Three Years Later + +Three years after ChatGPT's launch, the field of prompt engineering has matured significantly. What began as informal experimentation has evolved into a recognized discipline with established patterns, best practices, and an active research community. + +The Awesome ChatGPT Prompts project has grown alongside this field, evolving from a simple list of prompts to a comprehensive platform for discovering, sharing, and learning about AI prompts. + +This book represents the next evolution — a distillation of three years of community wisdom, updated for the AI landscape of today and tomorrow. + +## Looking Forward + +The journey from that first repository to this comprehensive guide reflects the rapid evolution of AI and our understanding of how to work with it effectively. As AI capabilities continue to advance, so too will the techniques for communicating with these systems. + +The principles discovered in those early days — clarity, specificity, purpose, and the power of role-playing — remain as relevant as ever. But new techniques continue to emerge: chain-of-thought prompting, few-shot learning, multimodal interactions, and more. + +The story of Awesome ChatGPT Prompts is ultimately a story about community — about thousands of people around the world sharing their discoveries, helping each other learn, and collectively advancing our understanding of how to work with AI. + +That spirit of open collaboration and shared learning is what this book hopes to continue. + +--- + +*The Awesome ChatGPT Prompts project is maintained by [@f](https://github.com/f) and an amazing community of contributors. Visit [prompts.chat](https://prompts.chat) to explore the platform, and join us on [GitHub](https://github.com/f/prompts.chat) to contribute.* diff --git a/src/content/book/ja/00c-introduction.mdx b/src/content/book/ja/00c-introduction.mdx new file mode 100644 index 00000000..c744bd1e --- /dev/null +++ b/src/content/book/ja/00c-introduction.mdx @@ -0,0 +1,130 @@ +Welcome to **The Interactive Book of Prompting**, your guide to communicating effectively with AI. + + +By the end of this book, you'll understand how AI works, how to write better prompts, and how to use these skills for writing, coding, research, and creative projects. + + + +Unlike traditional books, this guide is fully interactive. You'll find live demos, clickable examples, and "Try It" buttons throughout that let you test prompts instantly. Learning by doing makes complex concepts much easier to understand. + + +## What is Prompt Engineering? + +Prompt engineering is the skill of writing good instructions for AI. When you type something to ChatGPT, Claude, Gemini, or other AI tools, that's called a "prompt." The better your prompt, the better the answer you get. + +Think of it like this: AI is a powerful helper that takes your words very literally. It will do exactly what you ask. The trick is learning how to ask for exactly what you want. + + + +The difference in output quality between these two prompts can be dramatic. + + + +## How Prompt Engineering Has Evolved + +In just three years since ChatGPT launched, prompt engineering has evolved dramatically alongside the technology itself. What started as simply "writing better questions" has grown into something much broader. + +Today, we understand that your prompt is just **one part of a larger context**. Modern AI systems work with multiple types of data simultaneously: + +- **System prompts** that define the AI's behavior +- **Conversation history** from previous messages +- **Retrieved documents** pulled from databases (RAG) +- **Tool definitions** that let AI take actions +- **User preferences** and settings +- **Your actual prompt** - the question you're asking right now + +This shift from "prompt engineering" to "context engineering" reflects how we now think about AI interactions. Your prompt matters, but so does everything else the AI sees. The best results come from carefully managing all these pieces together. + +We'll explore these concepts in depth throughout this book, especially in the [Context Engineering](/book/20-context-engineering) chapter. + +## Why Does Prompt Engineering Matter? + +### 1. Getting Better Answers + +AI tools are incredibly capable, but they need clear instructions to unlock their full potential. The same AI that gives a mediocre response to a vague question can produce brilliant work when prompted correctly. + + + +### 2. Saving Time and Money + +A well-crafted prompt gets results in one try instead of multiple back-and-forth exchanges. This matters even more when you're paying per token or working with rate limits. A 5-minute investment in writing a good prompt can save hours of iteration. + +### 3. Getting Consistent, Reproducible Results + +Good prompts produce predictable outputs. This is critical for: +- **Business workflows** where you need the same quality every time +- **Automation** where prompts run without human review +- **Teams** where multiple people need similar results + +### 4. Unlocking Advanced Capabilities + +Many powerful AI features only work when you know how to ask: +- **Chain-of-thought reasoning** for complex problems +- **Structured output** for data extraction +- **Role-playing** for specialized expertise +- **Few-shot learning** for custom tasks + +Without prompt engineering knowledge, you're only using a fraction of what AI can do. + +### 5. Staying Safe and Avoiding Pitfalls + +Good prompting helps you: +- Avoid hallucinations by asking for sources and verification +- Get balanced perspectives instead of one-sided answers +- Prevent the AI from making assumptions you didn't intend +- Keep sensitive information out of your prompts + +### 6. Future-Proofing Your Skills + +As AI becomes more integrated into work and life, prompt engineering becomes a fundamental literacy. The principles you learn here apply across all AI tools—ChatGPT, Claude, Gemini, image generators, and future models we haven't seen yet. + +## Who Is This Book For? + +This book is for everyone: + +- **Beginners** who want to learn how to use AI tools better +- **Students** working on homework, research, or creative projects +- **Writers and creators** using AI for their work +- **Developers** building apps with AI +- **Business people** who want to use AI at work +- **Anyone curious** about getting more out of AI assistants + +## How This Book Is Organized + + + +Plus an **Appendix** with templates, troubleshooting help, glossary, and extra resources. + +## A Note on AI Models + +This book mostly uses examples from ChatGPT (since it's the most popular), but the ideas work with any AI tool like Claude, Gemini, or others. We'll mention when something only works with specific AI models. + +AI is changing fast. What works today might be replaced by something better tomorrow. That's why this book focuses on core ideas that will stay useful no matter which AI you use. + +## Let's Begin + +Writing good prompts is a skill that gets better with practice. As you read this book: + +1. **Try things** - Test the examples, change them, see what happens +2. **Keep trying** - Don't expect perfect results on your first attempt +3. **Take notes** - Write down what works and what doesn't +4. **Share** - Add your discoveries to [prompts.chat](https://prompts.chat) + + +The best way to learn is by doing. Every chapter has examples you can try right away. Don't just read. Try it yourself! + + +Ready to transform how you work with AI? Turn the page and let's get started. + +--- + +*This book is part of the [Awesome ChatGPT Prompts](https://github.com/f/prompts.chat) project and is licensed under CC0 1.0 Universal (Public Domain).* diff --git a/src/content/book/ja/01-understanding-ai-models.mdx b/src/content/book/ja/01-understanding-ai-models.mdx new file mode 100644 index 00000000..0313d4a2 --- /dev/null +++ b/src/content/book/ja/01-understanding-ai-models.mdx @@ -0,0 +1,302 @@ +Before learning prompt techniques, it helps to understand how AI language models actually work. This knowledge will make you better at writing prompts. + + +Understanding how AI works isn't just for experts. It directly helps you write better prompts. Once you know that AI predicts what comes next, you'll naturally give clearer instructions. + + +## What Are Large Language Models? + +Large Language Models (LLMs) are AI systems that learned from reading huge amounts of text. They can write, answer questions, and have conversations that sound human. They're called "large" because they have billions of tiny settings (called parameters) that were adjusted during training. + +### How LLMs Work (Simplified) + +At their heart, LLMs are prediction machines. You give them some text, and they predict what should come next. + + + +When you type "The capital of France is...", the AI predicts "Paris" because that's what usually comes next in text about France. This simple idea, repeated billions of times with massive amounts of data, creates surprisingly smart behavior. + + + +### Key Concepts + +**Tokens**: AI doesn't read letter by letter. It breaks text into chunks called "tokens." A token might be a whole word like "hello" or part of a word like "ing." Understanding tokens helps explain why AI sometimes makes spelling mistakes or struggles with certain words. + + +A token is the smallest unit of text that an AI model processes. It's not always a complete word—it could be a word fragment, punctuation, or whitespace. For example, "unbelievable" might become 3 tokens: "un" + "believ" + "able". On average, **1 token ≈ 4 characters** or **100 tokens ≈ 75 words**. API costs and context limits are measured in tokens. + + + + +**Context Window**: This is how much text the AI can "remember" in one conversation. Think of it like the AI's short-term memory. It includes everything: your question AND the AI's answer. + + + +Context windows vary by model and are rapidly expanding: + +
+
+ GPT-4o + 128K tokens +
+
+ GPT-5 + 400K tokens +
+
+ Claude Sonnet 4 + 1M tokens +
+
+ Gemini 2.5 + 1M tokens +
+
+ Llama 4 + 1M-10M tokens +
+
+ DeepSeek R1 + 128K tokens +
+
+ +**Temperature**: This controls how creative or predictable the AI is. Low temperature (0.0-0.3) gives you focused, consistent answers. High temperature (0.7-1.0) gives you more creative, surprising responses. + + + +**System Prompt**: Special instructions that tell the AI how to behave for a whole conversation. For example, "You are a friendly teacher who explains things simply." Not all AI tools let you set this, but it's very powerful when available. + +## Types of AI Models + +### Text Models (LLMs) +The most common type, these generate text responses to text inputs. They power chatbots, writing assistants, and code generators. Examples: GPT-4, Claude, Llama, Mistral. + +### Multimodal Models +These can understand more than just text. They can look at images, listen to audio, and watch videos. Examples: GPT-4V, Gemini, Claude 3. + +### Text-to-Image Models + + +While this book focuses primarily on prompting for Large Language Models (text-based AI), the principles of clear, specific prompting apply to image generation too. Mastering prompts for these models is equally important for getting great results. + + +Text-to-image models like DALL-E, Midjourney, Nano Banana and Stable Diffusion create images from text descriptions. They work differently from text models: + +**How They Work:** +1. **Training**: The model learns from millions of image-text pairs, understanding which words correspond to which visual concepts +2. **Diffusion Process**: Starting from random noise, the model gradually refines the image, guided by your text prompt +3. **CLIP Guidance**: A separate model (CLIP) helps connect your words to visual concepts, ensuring the image matches your description + + + +**Prompting for Images is Different:** +Unlike text prompts where you write sentences, image prompts often work better as descriptive phrases separated by commas: + + + +### Text-to-Video Models + +Text-to-video is the newest frontier. Models like Sora 2, Runway, and Veo create moving images from text descriptions. Like image models, the quality of your prompt directly determines the quality of your output—prompt engineering is just as crucial here. + +**How They Work:** +1. **Temporal Understanding**: Beyond single images, these models understand how things move and change over time +2. **Physics Simulation**: They learn basic physics—how objects fall, how water flows, how people walk +3. **Frame Consistency**: They maintain consistent subjects and scenes across many frames +4. **Diffusion in Time**: Similar to image models, but generating coherent sequences instead of single frames + + + + +Video prompts need to describe action over time, not just a static scene. Include verbs and movement: + + + + +### Specialized Models +Fine-tuned for specific tasks like code generation (Codex, CodeLlama), music generation (Suno, Udio), or domain-specific applications like medical diagnosis or legal document analysis. + +## Model Capabilities and Limitations + +Explore what LLMs can and cannot do. Click on each capability to see example prompts: + + + +### Understanding Hallucinations + + +Sometimes AI writes things that sound true but aren't. This is called "hallucination." It's not a bug. It's just how prediction works. Always double-check important facts. + + +Why does AI make things up? + +1. It tries to write text that sounds good, not text that's always true +2. The internet (where it learned) has mistakes too +3. It can't actually check if something is real + + + +- **Ask for sources**: Then check if those sources are real +- **Ask for step-by-step thinking**: So you can check each step +- **Double-check important facts**: Use Google or trusted websites +- **Ask "Are you sure?"**: The AI might admit uncertainty + + + + + +## How AI Learns: The Three Steps + +AI doesn't just magically know things. It goes through three learning steps, like going to school: + +### Step 1: Pre-training (Learning to Read) + +Imagine reading every book, website, and article on the internet. That's what happens in pre-training. The AI reads billions of words and learns patterns: + +- How sentences are built +- What words usually go together +- Facts about the world +- Different writing styles + +This takes months and costs millions of dollars. After this step, the AI knows a lot, but it's not very helpful yet. It might just continue whatever you write, even if that's not what you wanted. + + + +### Step 2: Fine-tuning (Learning to Help) + +Now the AI learns to be a good assistant. Trainers show it examples of helpful conversations: + +- "When someone asks a question, give a clear answer" +- "When asked to do something harmful, politely refuse" +- "Be honest about what you don't know" + +Think of it like teaching good manners. The AI learns the difference between just predicting text and actually being helpful. + + + +Try the prompt above. Notice how the AI refuses? That's fine-tuning at work. + +### Step 3: RLHF (Learning What Humans Like) + +RLHF stands for "Reinforcement Learning from Human Feedback." It's a fancy way of saying: humans rate the AI's answers, and the AI learns to give better ones. + +Here's how it works: +1. The AI writes two different answers to the same question +2. A human picks which answer is better +3. The AI learns: "Okay, I should write more like Answer A" +4. This happens millions of times + +This is why AI: +- Is polite and friendly +- Admits when it doesn't know something +- Tries to see different sides of an issue +- Avoids controversial statements + + +Knowing these three steps helps you understand AI behavior. When AI refuses a request, that's fine-tuning. When AI is extra polite, that's RLHF. When AI knows random facts, that's pre-training. + + +## What This Means for Your Prompts + +Now that you understand how AI works, here's how to use that knowledge: + +### 1. Be Clear and Specific + +AI predicts what comes next based on your words. Vague prompts lead to vague answers. Specific prompts get specific results. + + + + + +### 2. Give Context + +AI doesn't know anything about you unless you tell it. Each conversation starts fresh. Include the background information AI needs. + + + + + +### 3. Work With the AI, Not Against It + +Remember: AI was trained to be helpful. Ask for things the way you'd ask a helpful friend. + + + +### 4. Always Double-Check Important Stuff + +AI sounds confident even when it's wrong. For anything important, verify the information yourself. + + + +### 5. Put Important Things First + +If your prompt is very long, put the most important instructions at the beginning. AI pays more attention to what comes first. + +## Picking the Right AI + +Different AI models are good at different things: + +
+
+ Quick questions + Faster models like GPT-4o or Claude 3.5 Sonnet +
+
+ Hard problems + Smarter models like GPT-5.2 or Claude 4.5 Opus +
+
+ Writing code + Code-focused models or the smartest general models +
+
+ Long documents + Models with big context windows (Claude, Gemini) +
+
+ Current events + Models with internet access +
+
+ +## Summary + +AI language models are prediction machines trained on text. They're amazing at many things, but they have real limits. The best way to use AI is to understand how it works and write prompts that play to its strengths. + + + + + +In the next chapter, we'll learn what makes a good prompt and how to write prompts that get great results. diff --git a/src/content/book/ja/02-anatomy-of-effective-prompt.mdx b/src/content/book/ja/02-anatomy-of-effective-prompt.mdx new file mode 100644 index 00000000..03cd23d2 --- /dev/null +++ b/src/content/book/ja/02-anatomy-of-effective-prompt.mdx @@ -0,0 +1,343 @@ +Every great prompt shares common structural elements. Understanding these components allows you to construct prompts systematically rather than through trial and error. + + +Think of these components like LEGO bricks. You don't need all of them for every prompt, but knowing what's available helps you build exactly what you need. + + +## The Core Components + +An effective prompt typically includes some or all of these elements: + + + +Let's examine each component in detail. + +## 1. Role / Persona + +Setting a role focuses the model's responses through the lens of a specific expertise or perspective. + + + +The role primes the model to: +- Use appropriate vocabulary +- Apply relevant expertise +- Maintain a consistent perspective +- Consider the audience appropriately + +### Effective Role Patterns + +``` +"You are a [profession] with [X years] of experience in [specialty]" +"Act as a [role] who is [characteristic]" +"You are an expert [field] helping a [audience type]" +``` + +## 2. Context / Background + +Context provides the information the model needs to understand your situation. Remember: the model knows nothing about you, your project, or your goals unless you tell it. + + + +### What to Include in Context + +- **Project details** — Technology stack, architecture, constraints +- **Current state** — What you've tried, what's working, what isn't +- **Goals** — What you're ultimately trying to achieve +- **Constraints** — Time limits, technical requirements, style guides + +## 3. Task / Instruction + +The task is the heart of your prompt—what you want the model to do. Be specific and unambiguous. + +### The Specificity Spectrum + + + +### Action Verbs That Work Well + +
+
+ Creation + Write, Create, Generate, Compose, Design +
+
+ Analysis + Analyze, Evaluate, Compare, Assess, Review +
+
+ Transformation + Convert, Translate, Reformat, Summarize, Expand +
+
+ Explanation + Explain, Describe, Clarify, Define, Illustrate +
+
+ Problem-solving + Solve, Debug, Fix, Optimize, Improve +
+
+ +## 4. Constraints / Rules + +Constraints bound the model's output. They prevent common issues and ensure relevance. + +### Types of Constraints + +**Length constraints:** +``` +"Keep your response under 200 words" +"Provide exactly 5 suggestions" +"Write 3-4 paragraphs" +``` + +**Content constraints:** +``` +"Do not include any code examples" +"Focus only on the technical aspects" +"Avoid marketing language" +``` + +**Style constraints:** +``` +"Use a formal, academic tone" +"Write as if speaking to a 10-year-old" +"Be direct and avoid hedging language" +``` + +**Scope constraints:** +``` +"Only consider options available in Python 3.10+" +"Limit suggestions to free tools" +"Focus on solutions that don't require additional dependencies" +``` + +## 5. Output Format + +Specifying the output format ensures you get responses in a usable structure. + +### Common Formats + +**Lists:** +``` +"Return as a bulleted list" +"Provide a numbered list of steps" +``` + +**Structured data:** +``` +"Return as JSON with keys: title, description, priority" +"Format as a markdown table with columns: Feature, Pros, Cons" +``` + +**Specific structures:** +``` +"Structure your response as: + ## Summary + ## Key Points + ## Recommendations" +``` + +### JSON Output Example + +``` +Analyze this customer review and return JSON: +{ + "sentiment": "positive" | "negative" | "neutral", + "topics": ["array of main topics"], + "rating_prediction": 1-5, + "key_phrases": ["notable phrases"] +} + +Review: "The product arrived quickly and works great, but +the instructions were confusing." +``` + +## 6. Examples (Few-Shot Learning) + +Examples are the most powerful way to show the model exactly what you want. + +### One-Shot Example + +``` +Convert these sentences to past tense. + +Example: +Input: "She walks to the store" +Output: "She walked to the store" + +Now convert: +Input: "They run every morning" +``` + +### Few-Shot Example + +``` +Classify these support tickets by urgency. + +Examples: +"My account was hacked" → Critical +"How do I change my password?" → Low +"Payment failed but I was charged" → High + +Classify: "The app crashes when I open settings" +``` + +## Putting It All Together + +Here's a complete prompt using all components: + + + +## The Minimal Effective Prompt + +Not every prompt needs all components. For simple tasks, a clear instruction may suffice: + +``` +Translate "Hello, how are you?" to Spanish. +``` + +Use additional components when: +- The task is complex or ambiguous +- You need specific formatting +- Results aren't matching expectations +- Consistency across multiple queries matters + +## Common Prompt Patterns + +These frameworks give you a simple checklist to follow when writing prompts. Click on each step to see an example. + + + + + +## Summary + +Effective prompts are constructed, not discovered. By understanding and applying these structural components, you can: + +- Get better results on the first try +- Debug prompts that aren't working +- Create reusable prompt templates +- Communicate your intentions clearly + + + + + +## Build Your Own Prompt + +Now it's your turn! Use this interactive prompt builder to construct your own prompt using the components you've learned: + + + + + +In the next chapter, we'll explore the core principles that guide prompt construction decisions. diff --git a/src/content/book/ja/03-core-prompting-principles.mdx b/src/content/book/ja/03-core-prompting-principles.mdx new file mode 100644 index 00000000..358df563 --- /dev/null +++ b/src/content/book/ja/03-core-prompting-principles.mdx @@ -0,0 +1,373 @@ +Beyond structure, effective prompt engineering is guided by principles—fundamental truths that apply across models, tasks, and contexts. Master these principles, and you'll be able to adapt to any prompting challenge. + + +These principles apply to every AI model and every task. Learn them once, use them everywhere. + + +## Principle 1: Clarity Over Cleverness + +The best prompts are clear, not clever. AI models are literal interpreters—they work with exactly what you give them. + +### Be Explicit + + + +### Avoid Ambiguity + +Words can have multiple meanings. Choose precise language. + + + +### State the Obvious + +What's obvious to you isn't obvious to the model. Spell out assumptions. + +``` +You're helping me write a cover letter. + +Important context: +- I'm applying for a Software Engineer position at Google +- I have 5 years of experience in Python and distributed systems +- The role requires leadership experience (I've led a team of 4) +- I want to emphasize my open-source contributions +``` + +## Principle 2: Specificity Yields Quality + +Vague inputs produce vague outputs. Specific inputs produce specific, useful outputs. + +### The Specificity Ladder + + + +Each level adds specificity and dramatically improves output quality. + +### Specify These Elements + +
+
+ Audience + Who will read/use this? +
+
+ Length + How long/short should it be? +
+
+ Tone + Formal? Casual? Technical? +
+
+ Format + Prose? List? Table? Code? +
+
+ Scope + What to include/exclude? +
+
+ Purpose + What should this accomplish? +
+
+ +## Principle 3: Context Is King + +Models have no memory, no access to your files, and no knowledge of your situation. Everything relevant must be in the prompt. + +### Provide Sufficient Context + + + +### The Context Checklist + + +Ask yourself: Would a smart stranger understand this request? If not, add more context. + + + + +## Principle 4: Guide, Don't Just Ask + +Don't just ask for an answer—guide the model toward the answer you want. + +### Use Instructional Framing + + + +### Provide Reasoning Scaffolds + +For complex tasks, guide the reasoning process: + + + +## Principle 5: Iterate and Refine + +Prompt engineering is an iterative process. Your first prompt is rarely your best. + +### The Iteration Cycle + +``` +1. Write initial prompt +2. Review output +3. Identify gaps or issues +4. Refine prompt +5. Repeat until satisfied +``` + +### Common Refinements + +
+
+ Too verbose + Add "Be concise" or length limits +
+
+ Too vague + Add specific examples or constraints +
+
+ Wrong format + Specify exact output structure +
+
+ Missing aspects + Add "Make sure to include..." +
+
+ Wrong tone + Specify audience and style +
+
+ Inaccurate + Request citations or step-by-step reasoning +
+
+ +### Keep a Prompt Journal + +Document what works: +``` +Task: Code review +Version 1: "Review this code" → Too generic +Version 2: Added specific review criteria → Better +Version 3: Added example of good review → Excellent +Final: [Save successful prompt as template] +``` + +## Principle 6: Leverage the Model's Strengths + +Work with how models are trained, not against them. + +### Models Want to Be Helpful + +Frame requests as things a helpful assistant would naturally do: + + + +### Models Excel at Patterns + +If you need consistent output, show the pattern: + + + +### Models Can Role-Play + +Use personas to access different "modes" of response: + +``` +As a devil's advocate, argue against my proposal... +As a supportive mentor, help me improve... +As a skeptical investor, question this business plan... +``` + +## Principle 7: Control Output Structure + +Structured outputs are more useful than free-form text. + +### Request Specific Formats + +``` +Return your analysis as: + +SUMMARY: [1 sentence] + +KEY FINDINGS: +• [Finding 1] +• [Finding 2] +• [Finding 3] + +RECOMMENDATION: [1-2 sentences] + +CONFIDENCE: [Low/Medium/High] because [reason] +``` + +### Use Delimiters + +Clearly separate sections of your prompt: + +``` +### CONTEXT ### +[Your context here] + +### TASK ### +[Your task here] + +### FORMAT ### +[Desired format here] +``` + +### Request Machine-Readable Output + +For programmatic use: + +``` +Return only valid JSON, no explanation: +{ + "decision": "approve" | "reject" | "review", + "confidence": 0.0-1.0, + "reasons": ["string array"] +} +``` + +## Principle 8: Verify and Validate + +Never blindly trust model outputs, especially for important tasks. + +### Ask for Reasoning + +``` +Solve this problem and show your work step by step. +After solving, verify your answer by [checking method]. +``` + +### Request Multiple Perspectives + +``` +Give me three different approaches to solve this problem. +For each, explain the trade-offs. +``` + +### Build in Self-Checking + +``` +After generating the code, review it for: +- Syntax errors +- Edge cases +- Security vulnerabilities +List any issues found. +``` + +## Summary: The Principles at a Glance + + + + + +## Practice: Fill in the Blanks + +Test your understanding of the core principles by completing this prompt template: + + + + + +These principles form the foundation for everything that follows. In Part II, we'll apply them to specific techniques that dramatically enhance prompt effectiveness. diff --git a/src/content/book/ja/04-role-based-prompting.mdx b/src/content/book/ja/04-role-based-prompting.mdx new file mode 100644 index 00000000..ef178cbc --- /dev/null +++ b/src/content/book/ja/04-role-based-prompting.mdx @@ -0,0 +1,328 @@ +Role-based prompting is one of the most powerful and widely-used techniques in prompt engineering. By assigning a specific role or persona to the AI, you can dramatically influence the quality, style, and relevance of responses. + + +Think of roles as filters for AI's vast knowledge. The right role focuses responses like a lens focuses light. + + +## Why Roles Work + +When you assign a role, you're essentially telling the model: "Filter your vast knowledge through this specific lens." The model adjusts its: + +- **Vocabulary**: Using terminology appropriate to the role +- **Perspective**: Considering problems from that viewpoint +- **Expertise depth**: Providing role-appropriate detail levels +- **Communication style**: Matching how that role would communicate + +### The Technical Explanation + +LLMs work by predicting the most likely next token based on the context they're given. When you specify a role, you're fundamentally changing what "likely" means. + +**Activating Relevant Knowledge**: The role primes specific regions of the model's learned associations. Saying "You are a doctor" activates medical terminology, diagnostic reasoning patterns, and clinical communication styles from the training data. + +**Statistical Conditioning**: LLMs learned from millions of documents written by real experts. When you assign a role, the model conditions its probability distributions to match patterns it saw from that type of author. + +**Reducing Ambiguity**: Without a role, the model averages across all possible responders. With a role, it narrows to a specific subset, making responses more focused and consistent. + +**Context Anchoring**: The role creates a persistent context anchor throughout the conversation. Every subsequent response is influenced by this initial framing. + +Think of it this way: if you ask "What should I do about this cough?" the model could respond as a doctor, a friend, a pharmacist, or a worried parent. Each would give different advice. By specifying the role upfront, you're telling the model which "voice" to use from its training data. + + +The model isn't pretending or role-playing in a theatrical sense. It's statistically biasing its outputs toward patterns it learned from real experts, professionals, and specialists during training. A "doctor" role activates medical knowledge pathways; a "poet" role activates literary patterns. + + +## Basic Role Patterns + +These foundational patterns work across most use cases. Start with these templates and customize them for your needs. + +### The Expert Pattern + +The most versatile pattern. Specify the field of expertise and years of experience to get authoritative, in-depth responses. Works well for technical questions, analysis, and professional advice. + + + +### The Professional Pattern + +Ground the role in a real-world context by specifying a job title and organization type. This adds institutional knowledge and professional norms to the response. + + + +### The Teacher Pattern + +Perfect for learning and explanations. Specifying the audience level ensures the response matches the learner's background, from beginners to advanced practitioners. + + + +## Advanced Role Constructions + +### Compound Roles + +Combine multiple identities to get responses that blend different perspectives. This pediatrician-parent combination produces advice that's both medically sound and practically tested. + + + +### Situational Roles + +Place the role in a specific scenario to shape both content and tone. Here, the code review context makes the AI constructive and educational rather than just critical. + + + +### Perspective Roles + +Get feedback from a specific stakeholder's point of view. A VC perspective evaluates viability and scalability differently than a customer or engineer would. + + + +## Role Categories and Examples + +Different domains benefit from different types of roles. Here are proven examples organized by category that you can adapt for your tasks. + +### Technical Roles + +**Software Architect**: Best for system design decisions, technology choices, and architectural trade-offs. The focus on maintainability steers responses toward practical, long-term solutions. + + + +**Security Specialist**: The attacker mindset is key here. This role produces threat-focused analysis that identifies vulnerabilities a defensive-only perspective might miss. + + + +**DevOps Engineer**: Ideal for deployment, automation, and infrastructure questions. The emphasis on reliability ensures production-ready recommendations. + + + +### Creative Roles + +**Copywriter**: The "award-winning" qualifier and conversion focus produce punchy, persuasive copy rather than generic marketing text. + + + +**Screenwriter**: Activates knowledge of dramatic structure, pacing, and dialogue conventions. Great for any narrative writing that needs tension and character voice. + + + +**UX Writer**: A specialized role for interface text. The focus on brevity and user guidance produces concise, action-oriented copy. + + + +### Analytical Roles + +**Business Analyst**: Bridges the gap between technical and non-technical stakeholders. Useful for requirement gathering, spec writing, and identifying gaps in project plans. + + + +**Research Scientist**: The emphasis on evidence and uncertainty acknowledgment produces balanced, well-sourced responses that distinguish facts from speculation. + + + +**Financial Analyst**: Combines quantitative analysis with risk assessment. The dual focus on returns and risk produces more balanced investment perspectives. + + + +### Educational Roles + +**Socratic Tutor**: Instead of giving answers, this role asks guiding questions. Excellent for deeper learning and helping students develop critical thinking skills. + + + +**Instructional Designer**: Structures learning for maximum retention. Use this role when you need to break down complex topics into teachable chunks with clear progression. + + + +## The Role Stack Technique + +For complex tasks, combine multiple role aspects into a single, layered identity. This technique stacks expertise, audience awareness, and style guidelines to create highly specialized responses. + +This example layers three elements: domain expertise (API documentation), audience (junior developers), and style guide (Google's conventions). Each layer constrains the output further. + + + +## Roles for Different Tasks + +
+
+ Code review + Senior developer + mentor +
+
+ Writing feedback + Editor + target audience member +
+
+ Business strategy + Consultant + industry expert +
+
+ Learning new topic + Patient teacher + practitioner +
+
+ Creative writing + Specific genre author +
+
+ Technical explanation + Expert + communicator +
+
+ Problem-solving + Domain specialist + generalist +
+
+ +## Anti-Patterns to Avoid + +### Overly Generic Roles + + + +### Conflicting Roles + + + +### Unrealistic Expertise + + + +## Real-World Prompt Examples + +### Technical Documentation + + + +### Creative Writing + + + +### Business Communication + + + +## Combining Roles with Other Techniques + +Roles work even better when combined with other prompting techniques: + +### Role + Few-Shot + +Combine a role with an example to show exactly how the role should respond. The example teaches tone and format while the role provides context and expertise. + + + +### Role + Chain of Thought + +The detective role naturally encourages step-by-step reasoning. Combining roles with chain-of-thought produces more transparent, verifiable problem-solving. + + + +## Summary + + +Role-based prompting is powerful because it focuses the model's vast knowledge, sets expectations for tone and style, provides implicit context, and makes outputs more consistent. + + + + +The key is **specificity**: the more detailed and realistic the role, the better the results. In the next chapter, we'll explore how to get consistent, structured outputs from your prompts. diff --git a/src/content/book/ja/05-structured-output.mdx b/src/content/book/ja/05-structured-output.mdx new file mode 100644 index 00000000..8236abee --- /dev/null +++ b/src/content/book/ja/05-structured-output.mdx @@ -0,0 +1,411 @@ +Getting consistent, well-formatted output is essential for production applications and efficient workflows. This chapter covers techniques for controlling exactly how AI models format their responses. + + +Structured output transforms AI responses from freeform text into actionable, parseable data. + + +## Why Structure Matters + + + +## Basic Formatting Techniques + +### Lists + +Lists are perfect for step-by-step instructions, ranked items, or collections of related points. They're easy to scan and parse. Use **numbered lists** when order matters (steps, rankings) and **bullet points** for unordered collections. + + + + +Specify the exact number of items you want, whether to include explanations, and if items should be bold or have a specific structure. + + +### Tables + +Tables excel at comparing multiple items across the same dimensions. They're ideal for feature comparisons, data summaries, and any information with consistent attributes. Always define your column headers explicitly. + + + + +Specify column names, expected data types (text, numbers, ratings), and how many rows you need. For complex comparisons, limit to 4-6 columns for readability. + + +### Headers and Sections + +Headers create a clear document structure, making long responses scannable and organized. Use them for reports, analyses, or any multi-part response. Hierarchical headers (##, ###) show relationships between sections. + +``` +Analyze this business proposal. + +Structure your response with these sections: +## Executive Summary +## Strengths +## Weaknesses +## Recommendations +## Risk Assessment +``` + + +List your sections in the order you want them. For consistency, specify what each section should contain (e.g., "Executive Summary: 2-3 sentences only"). + + +### Emphasis with Uppercase Directives + +Uppercase words act as strong signals to the model, emphasizing critical constraints or requirements. Use them sparingly for maximum impact—overuse dilutes their effectiveness. + +**Common Uppercase Directives:** + + + +``` +Summarize this article. + +IMPORTANT: Keep the summary under 100 words. +NEVER add information not present in the original. +ALWAYS maintain the original tone and perspective. +DO NOT include your own opinions or analysis. +``` + + +If everything is uppercase or marked as critical, nothing stands out. Reserve these directives for genuinely important constraints. + + +## JSON Output + +JSON (JavaScript Object Notation) is the most popular format for structured AI output. It's machine-readable, widely supported by programming languages, and perfect for APIs, databases, and automation workflows. The key to reliable JSON is providing a clear schema. + +### Basic JSON Request + +Start with a template showing the exact structure you want. Include field names, data types, and example values. This acts as a contract the model will follow. + + + +### Complex JSON Structures + +For nested data, use hierarchical JSON with objects inside objects, arrays of objects, and mixed types. Define each level clearly and use TypeScript-style annotations (`"positive" | "negative"`) to constrain values. + +``` +Analyze this product review and return JSON: + +{ + "review_id": "string (generate unique)", + "sentiment": { + "overall": "positive" | "negative" | "mixed" | "neutral", + "score": 0.0-1.0 + }, + "aspects": [ + { + "aspect": "string (e.g., 'price', 'quality')", + "sentiment": "positive" | "negative" | "neutral", + "mentions": ["exact quotes from review"] + } + ], + "purchase_intent": { + "would_recommend": boolean, + "confidence": 0.0-1.0 + }, + "key_phrases": ["string array of notable phrases"] +} + +Return ONLY valid JSON, no additional text. + +Review: "[review text]" +``` + +### Ensuring Valid JSON + +Models sometimes add explanatory text or markdown formatting around JSON. Prevent this with explicit instructions about output format. You can request raw JSON or JSON inside code blocks—choose based on your parsing needs. + +Add explicit instructions: + +``` +IMPORTANT: +- Return ONLY the JSON object, no markdown code blocks +- Ensure all strings are properly escaped +- Use null for missing values, not undefined +- Validate that the output is parseable JSON +``` + +Or request code blocks by asking the model to wrap its output: + +```` +Return the result as a JSON code block: +```json +{ ... } +``` +```` + +## YAML Output + +YAML is more human-readable than JSON, using indentation instead of brackets. It's the standard for configuration files (Docker, Kubernetes, GitHub Actions) and works well when the output will be read by humans or used in DevOps contexts. YAML is sensitive to indentation, so be specific about formatting requirements. + + + +## XML Output + +XML is still required for many enterprise systems, SOAP APIs, and legacy integrations. It's more verbose than JSON but offers features like attributes, namespaces, and CDATA sections for complex data. Specify element names, nesting structure, and where to use attributes vs. child elements. + +``` +Convert this data to XML format: + +Requirements: +- Root element: +- Each item in element +- Include attributes where appropriate +- Use CDATA for description text + +Data: [book data] +``` + +## Custom Formats + +Sometimes standard formats don't fit your needs. You can define any custom format by providing a clear template. Custom formats work well for reports, logs, or domain-specific outputs that will be read by humans. + +### Structured Analysis Format + +Use delimiters (===, ---, [SECTION]) to create scannable documents with clear boundaries between sections. This format is great for code reviews, audits, and analyses. + +``` +Analyze this code using this exact format: + +=== CODE ANALYSIS === + +[SUMMARY] +One paragraph overview + +[ISSUES] +• CRITICAL: [issue] — [file:line] +• WARNING: [issue] — [file:line] +• INFO: [issue] — [file:line] + +[METRICS] +Complexity: [Low/Medium/High] +Maintainability: [score]/10 +Test Coverage: [estimated %] + +[RECOMMENDATIONS] +1. [Priority 1 recommendation] +2. [Priority 2 recommendation] + +=== END ANALYSIS === +``` + +### Fill-in-the-Blank Format + +Templates with blanks (___) guide the model to fill in specific fields while maintaining exact formatting. This approach is excellent for forms, briefs, and standardized documents where consistency matters. + +``` +Complete this template for the given product: + +PRODUCT BRIEF +───────────── +Name: _______________ +Tagline: _______________ +Target User: _______________ +Problem Solved: _______________ +Key Features: + 1. _______________ + 2. _______________ + 3. _______________ +Differentiator: _______________ + +Product: [product description] +``` + +## Typed Responses + +Typed responses define categories or entity types that the model should recognize and label. This technique is essential for Named Entity Recognition (NER), classification tasks, and any extraction where you need to categorize information consistently. Define your types clearly with examples. + + + +## Multi-Part Structured Responses + +When you need comprehensive output covering multiple aspects, define distinct parts with clear boundaries. Specify exactly what goes in each part—format, length, and content type. This prevents the model from blending sections or omitting parts. + +``` +Research this topic and provide: + +### PART 1: EXECUTIVE SUMMARY +[2-3 sentence overview] + +### PART 2: KEY FINDINGS +[Exactly 5 bullet points] + +### PART 3: DATA TABLE +| Metric | Value | Source | +|--------|-------|--------| +[Include 5 rows minimum] + +### PART 4: RECOMMENDATIONS +[Numbered list of 3 actionable recommendations] + +### PART 5: FURTHER READING +[3 suggested resources with brief descriptions] +``` + +## Conditional Formatting + +Conditional formatting lets you define different output formats based on the input's characteristics. This is powerful for classification, triage, and routing systems where the response format should vary based on what the model detects. Use clear if/then logic with explicit output templates for each case. + + + +## Arrays and Lists in JSON + +Extracting multiple items into arrays requires careful schema definition. Specify the array structure, what each item should contain, and how to handle edge cases (empty arrays, single items). Including a count field helps verify completeness. + +``` +Extract all action items from this meeting transcript. + +Return as JSON array: +{ + "action_items": [ + { + "task": "string describing the task", + "assignee": "person name or 'Unassigned'", + "deadline": "date if mentioned, else null", + "priority": "high" | "medium" | "low", + "context": "relevant quote from transcript" + } + ], + "total_count": number +} + +Transcript: "[meeting transcript]" +``` + +## Validation Instructions + +Self-validation prompts the model to check its own output before responding. This catches common issues like missing sections, placeholder text, or constraint violations. The model will iterate internally to fix problems, improving output quality without additional API calls. + +``` +Generate the report, then: + +VALIDATION CHECKLIST: +□ All required sections present +□ No placeholder text remaining +□ All statistics include sources +□ Word count within 500-700 words +□ Conclusion ties back to introduction + +If any check fails, fix before responding. +``` + +## Handling Optional Fields + +Real-world data often has missing values. Explicitly instruct the model on how to handle optional fields—using `null` is cleaner than empty strings and easier to process programmatically. Also prevent "hallucination" of missing data by emphasizing that the model should never invent information. + +``` +Extract contact information. Use null for missing fields. + +{ + "name": "string (required)", + "email": "string or null", + "phone": "string or null", + "company": "string or null", + "role": "string or null", + "linkedin": "URL string or null" +} + +IMPORTANT: +- Never invent information not in the source +- Use null, not empty strings, for missing data +- Phone numbers in E.164 format if possible +``` + +## Summary + + +Be explicit about format, use examples, specify types, handle edge cases with null values, and ask the model to validate its own output. + + + + +Structured outputs are essential for building reliable AI-powered applications. In the next chapter, we'll explore chain-of-thought prompting for complex reasoning tasks. diff --git a/src/content/book/ja/06-chain-of-thought.mdx b/src/content/book/ja/06-chain-of-thought.mdx new file mode 100644 index 00000000..e579be5d --- /dev/null +++ b/src/content/book/ja/06-chain-of-thought.mdx @@ -0,0 +1,363 @@ +Chain of Thought (CoT) prompting is a technique that dramatically improves AI performance on complex reasoning tasks by asking the model to show its work step by step. + + +Just like a math teacher asking students to show their work, CoT prompting asks the AI to make its reasoning visible. + + +## The Problem CoT Solves + +AI models can struggle with multi-step reasoning when asked to jump directly to an answer. + + + +## Basic CoT Prompts + +### Simple Trigger Phrases + +Add one of these to your prompts: + +
+
"Let's think step by step."
+
"Think through this carefully."
+
"Work through this problem methodically."
+
"Show your reasoning at each step."
+
"Explain your thought process."
+
+ +### Explicit Step Request + + + +## Zero-Shot vs Few-Shot CoT + +There are two main approaches to Chain of Thought prompting, each with different trade-offs between simplicity and control. + +### Zero-Shot CoT + +The simplest approach—just add a trigger phrase and let the model figure out how to reason. No examples needed. This works surprisingly well for many problems, though you have less control over the reasoning format. + + + +**Example Output:** +``` +Let's think step by step. +- John starts with 3 apples +- Half of 3 is 1.5, but we can't split apples +- If we round down: John gives 1 apple, keeps 2 +- After buying 4 more: 2 + 4 = 6 apples + +Answer: 6 apples +``` + +### Few-Shot CoT + +For more consistent results, show the model exactly how you want it to reason by providing worked examples. This gives you control over the reasoning style, format, and level of detail. The model will mimic your demonstrated pattern. + + + +**Example Output:** +``` +A: Let's work through this: +- Regular price: $3, Quantity: 12 +- Since 12 ≥ 10, the 25% discount applies +- Regular total: 12 × $3 = $36 +- Discount: 25% of $36 = $9 +- Final price: $36 - $9 = $27 +``` + +## Structured CoT Formats + +For consistent, reproducible reasoning, use structured formats with named steps. These frameworks ensure the model doesn't skip important stages and makes outputs easier to parse and verify. + +### The BREAK Format + +A memorable acronym that guides the model through a complete problem-solving cycle, from understanding to verification. + + + +### The Reasoning Template + +A more formal structure that separates inputs, goals, and execution. Excellent for technical problems where you need clear documentation of the solution process. + + + +**Example Output:** +``` +GIVEN: 8L/100km, tank 45L, $1.50/L, drive 300km +GOAL: Calculate fuel cost +APPROACH: Fuel needed × cost per liter +STEPS: +1. Fuel = (300 ÷ 100) × 8 = 24 liters +2. Cost = 24 × $1.50 = $36 +VERIFICATION: 24L < 45L tank ✓ +ANSWER: $36 +``` + +## CoT for Different Problem Types + +Different problem types benefit from different CoT approaches. Here are patterns optimized for common scenarios. + +### Mathematical Reasoning + +Math problems benefit most from CoT because each step builds on the previous one. Errors compound, so showing work helps catch mistakes early. The model should clearly label each calculation. + + + +**Example Output:** +``` +Q1: $1,200,000 (given) +Q2: $1,200,000 × 1.15 = $1,380,000 +Q3: $1,380,000 × 0.90 = $1,242,000 +Q4: $1,242,000 × 1.25 = $1,552,500 + +Total: $5,374,500 +``` + +### Logical Reasoning + +Logic puzzles require systematic elimination and hypothesis testing. CoT helps the model track constraints, test possibilities, and verify that all conditions are satisfied. The key is methodical exploration rather than guessing. + + + +**Example Output:** +``` +From clue 3: Bob = teacher +→ Alice and Carol are engineer/doctor + +If Carol = engineer: +- Carol has dog (clue 2) +- Alice = doctor, has fish (clue 1) +- Bob has cat + +Verify: All 4 clues satisfied ✓ +Answer: Alice (doctor, fish), Bob (teacher, cat), Carol (engineer, dog) +``` + +### Code Debugging + +Debugging benefits from CoT because it forces the model to trace execution rather than guess at bugs. By walking through the code with concrete values, the actual behavior becomes visible and discrepancies with expected behavior are exposed. + + + +**Example Output:** +``` +Trace [2, 3, 4, 6]: +n=2: total += 1 → 1 (wait, adding 1 not n!) +n=3: skip (odd) +n=4: total = 2 +n=6: total = 3 + +BUG: "total += 1" should be "total += n" +Expected: 12, Got: 3 +Fix: Change to "total += n" +``` + +## Self-Consistency with CoT + +For critical problems, don't rely on a single reasoning path. Generate multiple independent solutions and compare results. If different approaches converge on the same answer, confidence is high. Disagreement signals the need for careful review. + + + +**Example Output:** +``` +Approach 1 (Algebra): c + w = 30, 2c + 4w = 74 → c=23, w=7 +Approach 2 (Guess): Try 23/7 → 46 + 28 = 74 ✓ +Approach 3 (Logic): 30 chickens = 60 legs, need 14 more → 7 cows + +All agree: 23 chickens, 7 cows +``` + +## CoT for Decision Making + +Decisions involve weighing trade-offs across multiple dimensions. CoT ensures all relevant factors are considered systematically rather than jumping to conclusions. This structured approach also documents the reasoning for future reference. + + + +**Example Output:** +``` +FACTORS: +- Team size (5): Too small for microservices ❌ +- Scale (100 DAU): No scaling need ❌ +- Velocity: Monolith = faster iteration ❌ +- Future growth: Uncertain timeline ⚠️ + +WEIGHING: 3 strong against, 1 weak for + +RECOMMENDATION: Stay monolith, use clear module +boundaries to ease future transition. +``` + +## When to Use CoT + +
+
+

Use CoT For

+
+

**Math problems** — Reduces calculation errors

+

**Logic puzzles** — Prevents skipped steps

+

**Complex analysis** — Organizes thinking

+

**Code debugging** — Traces execution

+

**Decision making** — Weighs trade-offs

+
+
+
+

Skip CoT For

+
+

**Simple Q&A** — Unnecessary overhead

+

**Creative writing** — Can constrain creativity

+

**Factual lookups** — No reasoning needed

+

**Translation** — Direct task

+

**Summarization** — Usually straightforward

+
+
+
+ +## CoT Limitations + +While powerful, Chain of Thought isn't a silver bullet. Understanding its limitations helps you apply it appropriately. + +1. **Increased token usage** — More output means higher costs +2. **Not always needed** — Simple tasks don't benefit +3. **Can be verbose** — May need to ask for conciseness +4. **Reasoning can be flawed** — CoT doesn't guarantee correctness + +## Summary + + +CoT dramatically improves complex reasoning by making implicit steps explicit. Use it for math, logic, analysis, and debugging. Trade-off: better accuracy for more tokens. + + + + +In the next chapter, we'll explore few-shot learning—teaching the model through examples. diff --git a/src/content/book/ja/07-few-shot-learning.mdx b/src/content/book/ja/07-few-shot-learning.mdx new file mode 100644 index 00000000..24e98f1d --- /dev/null +++ b/src/content/book/ja/07-few-shot-learning.mdx @@ -0,0 +1,478 @@ +Few-shot learning is one of the most powerful prompting techniques. By providing examples of what you want, you can teach the model complex tasks without any fine-tuning. + + +Just like humans learn by seeing examples, AI models can learn patterns from the examples you provide in your prompt. + + +## What is Few-Shot Learning? + +Few-shot learning shows the model examples of input-output pairs before asking it to perform the same task. The model learns the pattern from your examples and applies it to new inputs. + + + +
+
+
0
+
Zero-shot
+
+
+
1
+
One-shot
+
+
+
2-5
+
Few-shot
+
+
+
5+
+
Many-shot
+
+
+ +## Why Examples Work + + + +Examples communicate: +- **Format**: How output should be structured +- **Style**: Tone, length, vocabulary +- **Logic**: The reasoning pattern to follow +- **Edge cases**: How to handle special situations + +## Basic Few-Shot Pattern + +The fundamental structure of few-shot prompting follows a simple pattern: show examples, then ask for the new task. Consistency in formatting between examples is crucial. The model learns from the pattern you establish. + +``` +[Example 1] +Input: [input 1] +Output: [output 1] + +[Example 2] +Input: [input 2] +Output: [output 2] + +[Example 3] +Input: [input 3] +Output: [output 3] + +Now do this one: +Input: [new input] +Output: +``` + +## Few-Shot for Classification + +Classification is one of the strongest use cases for few-shot learning. By showing examples of each category, you define the boundaries between classes more precisely than instructions alone could achieve. + +### Sentiment Analysis + + +Sentiment analysis classifies text by emotional tone: positive, negative, neutral, or mixed. It's widely used for customer feedback, social media monitoring, and brand perception tracking. + + +Sentiment classification benefits from showing examples of each sentiment type, especially edge cases like "mixed" sentiment that might be ambiguous. + + + +### Topic Classification + +For multi-class categorization, include at least one example per category. This helps the model understand your specific taxonomy, which may differ from its default understanding. + + + +## Few-Shot for Transformation + +Transformation tasks convert input from one form to another while preserving meaning. Examples are essential here because they define exactly what "transformation" means for your use case. + +### Text Rewriting + +Style transformation requires examples that show the exact tone shift you want. Abstract instructions like "make it professional" are interpreted differently. Examples make it concrete. + + + +### Format Conversion + +Format conversion tasks benefit from examples showing edge cases and ambiguous inputs. The model learns your specific conventions for handling tricky cases. + + + +## Few-Shot for Generation + +Generation tasks create new content following a learned pattern. Examples establish length, structure, tone, and what details to highlight. These are hard to specify in instructions alone. + +### Product Descriptions + +Marketing copy benefits enormously from examples because they capture brand voice, feature emphasis, and persuasive techniques that are difficult to describe abstractly. + + + +### Code Documentation + + +Good documentation explains what code does, its parameters, return values, and usage examples. Consistent docstrings enable auto-generated API docs and help IDEs provide better code completion. + + +Documentation style varies widely between projects. Examples teach your specific format, what to include (args, returns, examples), and the level of detail expected. + +>> calculate_bmi(70, 1.75) + 22.86 +""" + +Now document: +Function: +def is_palindrome(text): + cleaned = ''.join(c.lower() for c in text if c.isalnum()) + return cleaned == cleaned[::-1] + +Documentation:`} /> + +## Few-Shot for Extraction + +Extraction tasks pull structured information from unstructured text. Examples define which entities matter, how to format output, and how to handle cases where information is missing or ambiguous. + +### Entity Extraction + + +Named Entity Recognition (NER) identifies and classifies named entities in text into categories like persons, organizations, locations, dates, and products. It's fundamental for information retrieval and knowledge graphs. + + +NER benefits from examples showing your specific entity types and how to handle entities that could fit multiple categories. + + + +### Structured Data Extraction + +Extracting structured data from natural language requires examples showing how to handle missing fields, implicit information, and varying input formats. + + + +## Advanced Few-Shot Techniques + +Beyond basic few-shot, several techniques can improve results for complex tasks. + +### Diverse Examples + +Diversity in examples is more valuable than quantity. Cover different scenarios, edge cases, and potential ambiguities rather than showing similar examples repeatedly. + + + +### Negative Examples + + +Showing "good" vs "bad" examples is called contrastive learning. It helps the model understand not just what you want, but what to avoid. This is especially useful for style and quality judgments. + + +Sometimes showing what *not* to do is as valuable as showing correct examples. Negative examples help the model understand boundaries and avoid common mistakes. + + + +### Edge Case Examples + +Edge cases often determine whether a solution works in production. Including unusual inputs in your examples prevents the model from failing on real-world data that doesn't fit the "happy path." + + + +## How Many Examples? + +
+
+ Simple classification + 2-3 + One per category minimum +
+
+ Complex formatting + 3-5 + Show variations +
+
+ Nuanced style + 4-6 + Capture full range +
+
+ Edge cases + 1-2 + Alongside normal examples +
+
+ +## Example Quality Matters + + + +## Combining Few-Shot with Other Techniques + +Few-shot learning combines powerfully with other prompting techniques. The examples provide the "what" while other techniques can add context, reasoning, or structure. + +### Few-Shot + Role + +Adding a role gives the model context for *why* it's doing the task, which can improve quality and consistency. + +``` +You are a legal contract reviewer. + +[examples of contract clause analysis] + +Now analyze: [new clause] +``` + +### Few-Shot + CoT + +Combining few-shot with Chain of Thought shows not just *what* answer to give, but *how* to reason through to that answer. This is powerful for tasks requiring judgment. + +``` +Classify and explain reasoning. + +Review: "Great features but overpriced" +Thinking: The review mentions positive aspects ("great features") +but also a significant negative ("overpriced"). The negative seems +to outweigh the positive based on the "but" conjunction. +Classification: Mixed-Negative + +[more examples with reasoning] + +Now classify with reasoning: +Review: "Exactly what I needed, arrived faster than expected" +``` + +## Summary + + +Few-shot learning teaches through demonstration and is often more effective than instructions alone. Use 2-5 diverse, correct examples and combine with other techniques for best results. + + + + +In the next chapter, we'll explore iterative refinement: the art of improving prompts through successive attempts. diff --git a/src/content/book/ja/08-iterative-refinement.mdx b/src/content/book/ja/08-iterative-refinement.mdx new file mode 100644 index 00000000..769f879a --- /dev/null +++ b/src/content/book/ja/08-iterative-refinement.mdx @@ -0,0 +1,387 @@ +Prompt engineering is rarely a one-shot process. The best prompts emerge through iteration—testing, observing, and refining until you achieve the desired results. + + +Think of your first prompt as a rough draft. Even experienced prompt engineers rarely nail it on the first try. + + +## The Iteration Cycle + +Effective prompt refinement follows a predictable cycle: write, test, analyze, and improve. Each iteration brings you closer to a prompt that reliably produces the results you need. + + + +## Common Refinement Patterns + +Most prompt failures fall into a handful of categories. Learning to recognize these patterns lets you quickly diagnose and fix issues without starting from scratch. + +### Problem: Output Too Long + +One of the most common issues. Without explicit constraints, models tend to be thorough rather than concise. + + + +### Problem: Output Too Vague + +Vague prompts produce vague outputs. The model can't read your mind about what "better" means or which aspects matter most to you. + + + +### Problem: Wrong Tone + +Tone is subjective and varies by context. What sounds "professional" to the model might not match your organization's voice or the relationship with your recipient. + + + +### Problem: Missing Key Information + +Open-ended requests get open-ended responses. If you need specific types of feedback, you must ask for them explicitly. + + + +### Problem: Inconsistent Format + +Without a template, the model will structure each response differently, making comparison difficult and automation impossible. + + + +## Systematic Refinement Approach + +Random changes waste time. A systematic approach helps you identify problems quickly and fix them efficiently. + +### Step 1: Diagnose the Issue + +Before changing anything, identify what's actually wrong. Use this diagnostic table to map symptoms to solutions: + +
+
+ Symptom + Likely Cause + Solution +
+
+ Too long + No length constraint + Add word/sentence limits +
+
+ Too short + Lacks detail request + Ask for elaboration +
+
+ Off-topic + Vague instructions + Be more specific +
+
+ Wrong format + Format not specified + Define exact structure +
+
+ Wrong tone + Audience not clear + Specify audience/style +
+
+ Inconsistent + No examples provided + Add few-shot examples +
+
+ +### Step 2: Make Targeted Changes + +Resist the urge to rewrite everything. Changing multiple variables at once makes it impossible to know what helped and what hurt. Make one change, test it, then proceed: + +``` +Iteration 1: Add length constraint +Iteration 2: Specify format +Iteration 3: Add example +Iteration 4: Refine tone instructions +``` + +### Step 3: Document What Works + +Prompt engineering knowledge is easily lost. Keep a log of what you tried and why. This saves time when you revisit the prompt later or face similar challenges: + +```markdown +## Prompt: Customer Email Response + +### Version 1 (too formal) +"Write a response to this customer complaint." + +### Version 2 (better tone, still missing structure) +"Write a friendly but professional response to this complaint. +Show empathy first." + +### Version 3 (final - good results) +"Write a response to this customer complaint. Structure: +1. Acknowledge their frustration (1 sentence) +2. Apologize specifically (1 sentence) +3. Explain solution (2-3 sentences) +4. Offer additional help (1 sentence) + +Tone: Friendly, professional, empathetic but not groveling." +``` + +## Real-World Iteration Example + +Let's walk through a complete iteration cycle to see how each refinement builds on the last. Notice how each version addresses specific shortcomings of the previous one. + +### Task: Generate Product Names + + + +## Refinement Strategies by Task Type + +Different tasks fail in predictable ways. Knowing the common failure modes helps you diagnose and fix issues faster. + +### For Content Generation + +Content generation often produces generic, off-target, or poorly formatted output. The fix usually involves being more specific about constraints, providing concrete examples, or defining your brand voice explicitly. + + + +### For Code Generation + +Code output can fail technically (syntax errors, wrong language features) or architecturally (poor patterns, missing cases). Technical issues need version/environment specifics; architectural issues need design guidance. + + + +### For Analysis + +Analysis tasks often produce surface-level or unstructured results. Guide the model with specific frameworks (SWOT, Porter's Five Forces), request multiple viewpoints, or provide a template for the output structure. + + + +### For Q&A + +Question-answering can be too terse or too verbose, and may lack confidence indicators or sources. Specify the detail level you need and whether you want citations or uncertainty expressed. + + + +## The Feedback Loop Technique + +Here's a meta-technique: use the model itself to help improve your prompts. Share what you tried, what you got, and what you wanted. The model can often suggest improvements you hadn't considered. + +``` +I used this prompt: +"[your prompt]" + +And got this output: +"[model output]" + +I wanted something more [describe gap]. How should I modify +my prompt to get better results? +``` + +## A/B Testing Prompts + +For prompts that will be used repeatedly or at scale, don't just pick the first one that works. Test variations to find the most reliable and highest-quality approach. + +``` +Prompt A: "Summarize this article in 3 bullet points." +Prompt B: "Extract the 3 most important insights from this article." +Prompt C: "What are the key takeaways from this article? List 3." +``` + +Run each multiple times, compare: +- Consistency of output +- Quality of information +- Relevance to your needs + +## When to Stop Iterating + +Perfection is the enemy of good enough. Know when your prompt is ready for use and when you're just polishing for diminishing returns. + +
+
+

Ready to Ship

+
+

Output consistently meets requirements

+

Edge cases are handled appropriately

+

Format is reliable and parseable

+

Further improvements show diminishing returns

+
+
+
+

Keep Iterating

+
+

Output is inconsistent across runs

+

Edge cases cause failures

+

Critical requirements are missed

+

You haven't tested enough variations

+
+
+
+ +## Version Control for Prompts + +Prompts are code. For any prompt used in production, treat it with the same rigor: version control, changelogs, and the ability to roll back if something breaks. + + +prompts.chat includes automatic version history for your prompts. Every edit is saved, so you can compare versions and restore previous iterations with one click. + + +For self-managed prompts, use a folder structure: + +``` +prompts/ +├── customer-response/ +│ ├── v1.0.txt # Initial version +│ ├── v1.1.txt # Fixed tone issue +│ ├── v2.0.txt # Major restructure +│ └── current.txt # Symlink to active version +└── changelog.md # Document changes +``` + +## Summary + + +Start simple, observe carefully, change one thing at a time, document what works, and know when to stop. The best prompts aren't written—they're discovered through systematic iteration. + + + + +## Practice: Improve This Prompt + +Try improving this weak prompt yourself. Edit it, then use AI to compare your version with the original: + + + +In the next chapter, we'll explore JSON and YAML prompting for structured data applications. diff --git a/src/content/book/ja/09-json-yaml-prompting.mdx b/src/content/book/ja/09-json-yaml-prompting.mdx new file mode 100644 index 00000000..318619da --- /dev/null +++ b/src/content/book/ja/09-json-yaml-prompting.mdx @@ -0,0 +1,586 @@ +Structured data formats like JSON and YAML are essential for building applications that consume AI outputs programmatically. This chapter covers techniques for reliable structured output generation. + + +JSON and YAML transform AI outputs from freeform text into structured, type-safe data that code can consume directly. + + +## Why Structured Formats? + + + +## JSON Prompting Basics + +JSON (JavaScript Object Notation) is the most common format for programmatic AI outputs. Its strict syntax makes it easy to parse, but also means small errors can break your entire pipeline. + +### Do's and Don'ts: Requesting JSON + + + +### Simple JSON Output + +Start with a schema showing the expected structure. The model will fill in values based on the input text. + +``` +Extract the following information as JSON: + +{ + "name": "string", + "age": number, + "email": "string" +} + +Text: "Contact John Smith, 34 years old, at john@example.com" +``` + +Output: +```json +{ + "name": "John Smith", + "age": 34, + "email": "john@example.com" +} +``` + +### Nested JSON Structures + +Real-world data often has nested relationships. Define each level of your schema clearly, especially for arrays of objects. + +``` +Parse this order into JSON: + +{ + "order_id": "string", + "customer": { + "name": "string", + "email": "string" + }, + "items": [ + { + "product": "string", + "quantity": number, + "price": number + } + ], + "total": number +} + +Order: "Order #12345 for Jane Doe (jane@email.com): 2x Widget ($10 each), +1x Gadget ($25). Total: $45" +``` + +### Ensuring Valid JSON + + +Models often wrap JSON in markdown code blocks or add explanatory text. Be explicit about wanting raw JSON only. + + +Add explicit instructions: + +``` +CRITICAL: Return ONLY valid JSON. No markdown, no explanation, +no additional text before or after the JSON object. + +If a field cannot be determined, use null. +Ensure all strings are properly quoted and escaped. +Numbers should not be quoted. +``` + +## YAML Prompting Basics + +YAML is more human-readable than JSON and supports comments. It's the standard for configuration files, especially in DevOps (Docker, Kubernetes, GitHub Actions). + +### Simple YAML Output + +YAML uses indentation instead of braces. Provide a template showing the expected structure. + +``` +Generate a configuration file in YAML format: + +server: + host: string + port: number + ssl: boolean +database: + type: string + connection_string: string + +Requirements: Production server on port 443 with SSL, PostgreSQL database +``` + +Output: +```yaml +server: + host: "0.0.0.0" + port: 443 + ssl: true +database: + type: "postgresql" + connection_string: "postgresql://user:pass@localhost:5432/prod" +``` + +### Complex YAML Structures + +For complex configurations, be specific about requirements. The model knows common patterns for tools like GitHub Actions, Docker Compose, and Kubernetes. + +``` +Generate a GitHub Actions workflow in YAML: + +Requirements: +- Trigger on push to main and pull requests +- Run on Ubuntu latest +- Steps: checkout, setup Node 18, install dependencies, run tests +- Cache npm dependencies +``` + +## Type Definitions in Prompts + +Type definitions give the model a precise contract for output structure. They're more explicit than examples and easier to validate programmatically. + +### Using TypeScript-like Types + +TypeScript interfaces are familiar to developers and precisely describe optional fields, union types, and arrays. The prompts.chat platform uses this approach for structured prompts. + + + +### JSON Schema Definition + + +JSON Schema is a formal specification for describing JSON structure. It's supported by many validation libraries and API tools. + + +JSON Schema provides constraints like min/max values, required fields, and regex patterns: + +``` +Extract data according to this JSON Schema: + +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "type": "object", + "required": ["title", "author", "year"], + "properties": { + "title": { "type": "string" }, + "author": { "type": "string" }, + "year": { "type": "integer", "minimum": 1000, "maximum": 2100 }, + "genres": { + "type": "array", + "items": { "type": "string" } + }, + "rating": { + "type": "number", + "minimum": 0, + "maximum": 5 + } + } +} + +Book: "1984 by George Orwell (1949) - A dystopian masterpiece. +Genres: Science Fiction, Political Fiction. Rated 4.8/5" +``` + +## Handling Arrays + +Arrays require special attention. Specify whether you need a fixed number of items or a variable-length list, and how to handle empty cases. + +### Fixed-Length Arrays + +When you need exactly N items, state it explicitly. The model will ensure the array has the right length. + +``` +Extract exactly 3 key points as JSON: + +{ + "key_points": [ + "string (first point)", + "string (second point)", + "string (third point)" + ] +} + +Article: [article text] +``` + +### Variable-Length Arrays + +For variable-length arrays, specify what to do when there are zero items. Including a count field helps verify extraction completeness. + +``` +Extract all mentioned people as JSON: + +{ + "people": [ + { + "name": "string", + "role": "string or null if not mentioned" + } + ], + "count": number +} + +If no people are mentioned, return empty array. + +Text: [text] +``` + +## Enum Values and Constraints + +Enums restrict values to a predefined set. This is crucial for classification tasks and anywhere you need consistent, predictable outputs. + +### Do's and Don'ts: Enum Values + + + +### String Enums + +List allowed values explicitly. Use "MUST be one of" language to enforce strict matching. + +``` +Classify this text. The category MUST be one of these exact values: +- "technical" +- "business" +- "creative" +- "personal" + +Return JSON: +{ + "text": "original text (truncated to 50 chars)", + "category": "one of the enum values above", + "confidence": number between 0 and 1 +} + +Text: [text to classify] +``` + +### Validated Numbers + +Numeric constraints prevent out-of-range values. Specify the type (integer vs float) and valid range. + +``` +Rate these aspects. Each score MUST be an integer from 1 to 5. + +{ + "quality": 1-5, + "value": 1-5, + "service": 1-5, + "overall": 1-5 +} + +Review: [review text] +``` + +## Handling Missing Data + +Real-world text often lacks some information. Define how the model should handle missing data to avoid hallucinated values. + +### Do's and Don'ts: Missing Information + + + +### Null Values + +Explicitly allow null and instruct the model not to invent information. This is safer than having the model guess. + +``` +Extract information. Use null for any field that cannot be +determined from the text. Do NOT invent information. + +{ + "company": "string or null", + "revenue": "number or null", + "employees": "number or null", + "founded": "number (year) or null", + "headquarters": "string or null" +} + +Text: "Apple, headquartered in Cupertino, was founded in 1976." +``` + +Output: +```json +{ + "company": "Apple", + "revenue": null, + "employees": null, + "founded": 1976, + "headquarters": "Cupertino" +} +``` + +### Default Values + +When defaults make sense, specify them in the schema. This is common for configuration extraction. + +``` +Extract settings with these defaults if not specified: + +{ + "theme": "light" (default) | "dark", + "language": "en" (default) | other ISO code, + "notifications": true (default) | false, + "fontSize": 14 (default) | number +} + +User preferences: "I want dark mode and larger text (18px)" +``` + +## Multi-Object Responses + +Often you need to extract multiple items from a single input. Define the array structure and any sorting/grouping requirements. + +### Array of Objects + +For lists of similar items, define the object schema once and specify it's an array. + +``` +Parse this list into JSON array: + +[ + { + "task": "string", + "priority": "high" | "medium" | "low", + "due": "ISO date string or null" + } +] + +Todo list: +- Finish report (urgent, due tomorrow) +- Call dentist (low priority) +- Review PR #123 (medium, due Friday) +``` + +### Grouped Objects + +Grouping tasks require categorization logic. The model will sort items into the categories you define. + +``` +Categorize these items into JSON: + +{ + "fruits": ["string array"], + "vegetables": ["string array"], + "other": ["string array"] +} + +Items: apple, carrot, bread, banana, broccoli, milk, orange, spinach +``` + +## YAML for Configuration Generation + +YAML shines for DevOps configurations. The model knows standard patterns for common tools and can generate production-ready configs. + +### Do's and Don'ts: YAML Configs + + + +### Docker Compose + +Specify the services you need and any special requirements. The model will handle the YAML syntax and best practices. + +``` +Generate a docker-compose.yml for: +- Node.js app on port 3000 +- PostgreSQL database +- Redis cache +- Nginx reverse proxy + +Include: +- Health checks +- Volume persistence +- Environment variables from .env file +- Network isolation +``` + +### Kubernetes Manifests + +Kubernetes manifests are verbose but follow predictable patterns. Provide the key parameters and the model will generate compliant YAML. + +``` +Generate Kubernetes deployment YAML: + +Deployment: +- Name: api-server +- Image: myapp:v1.2.3 +- Replicas: 3 +- Resources: 256Mi memory, 250m CPU (requests) +- Health checks: /health endpoint +- Environment from ConfigMap: api-config + +Also generate matching Service (ClusterIP, port 8080) +``` + +## Validation and Error Handling + +For production systems, build validation into your prompts. This catches errors before they propagate through your pipeline. + +### Self-Validation Prompt + +Ask the model to validate its own output against rules you specify. This catches format errors and invalid values. + +``` +Extract data as JSON, then validate your output. + +Schema: +{ + "email": "valid email format", + "phone": "E.164 format (+1234567890)", + "date": "ISO 8601 format (YYYY-MM-DD)" +} + +After generating JSON, check: +1. Email contains @ and valid domain +2. Phone starts with + and contains only digits +3. Date is valid and parseable + +If validation fails, fix the issues before responding. + +Text: [contact information] +``` + +### Error Response Format + +Define separate success and error formats. This makes programmatic handling much easier. + +``` +Attempt to extract data. If extraction fails, return error format: + +Success format: +{ + "success": true, + "data": { ... extracted data ... } +} + +Error format: +{ + "success": false, + "error": "description of what went wrong", + "partial_data": { ... any data that could be extracted ... } +} +``` + +## JSON vs YAML: When to Use Which + +
+
+
Use JSON When
+
+

Programmatic parsing needed

+

API responses

+

Strict type requirements

+

JavaScript/Web integration

+

Compact representation

+
+
+
+
Use YAML When
+
+

Human readability matters

+

Configuration files

+

Comments are needed

+

DevOps/Infrastructure

+

Deep nested structures

+
+
+
+ +## Prompts.chat Structured Prompts + +On prompts.chat, you can create prompts with structured output formats: + +``` +When creating a prompt on prompts.chat, you can specify: + +Type: STRUCTURED +Format: JSON or YAML + +The platform will: +- Validate outputs against your schema +- Provide syntax highlighting +- Enable easy copying of structured output +- Support template variables in your schema +``` + +## Common Pitfalls + + +These three issues cause most JSON parsing failures. Check for them when your code can't parse AI output. + + +### 1. Markdown Code Blocks + +**Problem:** Model wraps JSON in ```json blocks + +**Solution:** +``` +Return ONLY the JSON object. Do not wrap in markdown code blocks. +Do not include ```json or ``` markers. +``` + +### 2. Trailing Commas + +**Problem:** Invalid JSON due to trailing commas + +**Solution:** +``` +Ensure valid JSON syntax. No trailing commas after the last +element in arrays or objects. +``` + +### 3. Unescaped Strings + +**Problem:** Quotes or special characters break JSON + +**Solution:** +``` +Properly escape special characters in strings: +- \" for quotes +- \\ for backslashes +- \n for newlines +``` + +## Summary + + +Define schemas explicitly using TypeScript interfaces or JSON Schema. Specify types and constraints, handle nulls and defaults, request self-validation, and choose the right format for your use case. + + + + +This completes Part II on techniques. In Part III, we'll explore practical applications across different domains. diff --git a/src/content/book/ja/10-system-prompts-personas.mdx b/src/content/book/ja/10-system-prompts-personas.mdx new file mode 100644 index 00000000..c6737cda --- /dev/null +++ b/src/content/book/ja/10-system-prompts-personas.mdx @@ -0,0 +1,435 @@ +System prompts are like giving AI its personality and job description before a conversation starts. Think of it as the "backstage instructions" that shape everything the AI says. + + +A system prompt is a special message that tells the AI who it is, how to behave, and what it can or can't do. Users don't usually see this message, but it affects every response. + + + +System prompts build on the concepts from [Role-Based Prompting](/book/04-role-based-prompting). While role prompts assign a persona within your message, system prompts set that identity at a deeper level that persists across the entire conversation. + + +## How System Prompts Work + +When you chat with AI, there are actually three types of messages: + + + +The system message stays active for the whole conversation. It's like the AI's "instruction manual." + +## Building a System Prompt + +A good system prompt has five parts. Think of them as filling out a character sheet for the AI: + + + +### Example: A Coding Tutor + + + +## Persona Patterns + +Different tasks need different AI personalities. Here are three common patterns you can adapt: + +### 1. The Expert + +Best for: Learning, research, professional advice + + + +### 2. The Assistant + +Best for: Productivity, organization, getting things done + + + +### 3. The Character + +Best for: Creative writing, roleplay, entertainment + + + +## Advanced Techniques + +### Layered Instructions + +Think of your system prompt like an onion with layers. The inner layers are most important: + + + +### Adaptive Behavior + +Make your AI adjust to different users automatically: + + + +### Conversation Memory + +AI doesn't remember past conversations, but you can tell it to track things within the current chat: + + + +## Real-World Examples + +Here are complete system prompts for common use cases. Click to try them! + +### Customer Support Bot + + + +### Study Buddy + + + +### Writing Coach + + + +## Testing Your System Prompt + +Before using a system prompt for real, test it! Here's what to check: + + + +### Understanding Jailbreak Attacks + +"Jailbreaking" is when someone tries to trick AI into ignoring its rules. Understanding these attacks helps you build better defenses. + + + +### More Test Scenarios + +Use these interactive examples to see how a well-designed system prompt handles tricky situations: + +#### Test 1: Jailbreak Attempt + +See how a good system prompt resists attempts to override it: + + + +#### Test 2: Stay in Character + +Test if the AI maintains its persona when pushed: + + + +#### Test 3: Boundary Enforcement + +Check if the AI respects its stated limitations: + + + +#### Test 4: Reveal System Prompt + +See if the AI protects its instructions: + + + +#### Test 5: Conflicting Instructions + +Test how the AI handles contradictory requests: + + + + +A well-crafted system prompt will: +- Politely decline inappropriate requests +- Stay in character while redirecting +- Not reveal confidential instructions +- Handle edge cases gracefully + + +## Quick Reference + +
+
+

Do

+
    +
  • Give a clear identity
  • +
  • List specific capabilities
  • +
  • Set explicit boundaries
  • +
  • Define the tone and style
  • +
  • Include example responses
  • +
+
+
+

Don't

+
    +
  • Be vague about the role
  • +
  • Forget to set limits
  • +
  • Make it too long (500 words max)
  • +
  • Contradict yourself
  • +
  • Assume the AI will "figure it out"
  • +
+
+
+ +## Summary + +System prompts are the AI's instruction manual. They set up: +- **Who** the AI is (identity and expertise) +- **What** it can and can't do (capabilities and limits) +- **How** it should respond (tone, format, style) + + +Begin with a short system prompt and add more rules as you discover what's needed. A clear 100-word prompt beats a confusing 500-word one. + + + + + + +In the next chapter, we'll explore prompt chaining: connecting multiple prompts together for complex multi-step tasks. diff --git a/src/content/book/ja/11-prompt-chaining.mdx b/src/content/book/ja/11-prompt-chaining.mdx new file mode 100644 index 00000000..9f54da52 --- /dev/null +++ b/src/content/book/ja/11-prompt-chaining.mdx @@ -0,0 +1,379 @@ +Prompt chaining breaks complex tasks into sequences of simpler prompts, where each step's output feeds into the next. This technique dramatically improves reliability and enables sophisticated workflows that would be impossible with a single prompt. + + +Just like a factory assembly line breaks manufacturing into specialized stations, prompt chaining breaks AI tasks into specialized steps. Each step does one thing well, and the combined output is far better than trying to do everything at once. + + +## Why Chain Prompts? + +Single prompts struggle with complex tasks because they try to do too much at once. The AI has to simultaneously understand, analyze, plan, and generate, which leads to errors and inconsistencies. + +
+
+

Single Prompt Struggles

+
+

Multi-step reasoning gets confused

+

Different "modes" of thinking clash

+

Complex outputs lack consistency

+

No opportunity for quality control

+
+
+
+

Chaining Solves This

+
+

Each step focuses on one task

+

Specialized prompts for each mode

+

Validate between steps

+

Debug and improve individual steps

+
+
+
+ +## Basic Chaining Pattern + +The simplest chain passes output from one prompt directly to the next. Each step has a clear, focused purpose. + +
+
+
+

Prompt 1

+

(Extract)

+
+

Input

+
+
→
+
+
+

Prompt 2

+

(Analyze)

+
+

Intermediate

+
+
→
+
+
+

Prompt 3

+

(Generate)

+
+

Output

+
+
+ + +The most common chain pattern is **Extract → Transform → Generate**. First extract raw data, then reshape it for your purpose, then generate the final output. This pattern works for almost any content task. + + +## Chain Types + +Different tasks require different chain architectures. Choose the pattern that matches your workflow. + + + +### Sequential Chain + +The most straightforward pattern: each step depends on the previous. Think of it as a relay race where each runner passes the baton to the next. + + + +### Parallel Chain + +When you need multiple perspectives on the same input, run prompts in parallel and merge results. This is faster than sequential chains and provides richer analysis. + + + +### Conditional Chain + +Route inputs through different paths based on classification. This is like a decision tree where the AI first categorizes the input, then handles each category differently. + + + +### Iterative Chain + +Keep refining output until it meets quality standards. The AI generates, evaluates, and improves in a loop until satisfied or max iterations reached. + + +Always set a maximum number of iterations (typically 3-5) to prevent infinite loops and control costs. The law of diminishing returns applies: most improvement happens in the first 2-3 iterations. + + += 8: EXIT LOOP' } + ]} +/> + +## Common Chain Patterns + +These battle-tested patterns solve common problems. Use them as starting points and adapt to your needs. + +### Extract → Transform → Generate + +The workhorse of content processing. Pull data out, reshape it, then create something new. + +
+

Best For

+

Document summarization, report generation, content repurposing, data-to-narrative conversion

+
+ + + +### Analyze → Plan → Execute + +Perfect for code refactoring, project planning, or any task where you need to understand before acting. + +
+

Best For

+

Code refactoring, project planning, troubleshooting, strategic decision-making, complex problem solving

+
+ + {\n const { email, password } = req.body;\n if (!email || !isValidEmail(email)) {\n return res.status(400).json({ error: 'Invalid email' });\n }\n next();\n};" } + ]} +/> + +### Generate → Critique → Refine + +The self-improvement loop. Generate content, have the AI evaluate it critically, then improve based on that feedback. This mimics how professional writers and editors work together. + +
+

Best For

+

Marketing copy, creative writing, email drafts, presentations, any content that benefits from revision

+
+ + + +## Implementing Chains + +You can implement chains manually for experimentation, or programmatically for production systems. Start simple and add complexity as needed. + +### Manual Chaining + +The copy-paste approach is perfect for prototyping and experimentation. Run each prompt manually, examine the output, and paste it into the next prompt. + + + +### Programmatic Chaining + +For production systems, automate the chain with code. This enables error handling, logging, and integration with your application. + + + +### Using Chain Templates + +Define chains as configuration files for reusability and easy modification. This separates prompt logic from application code. + + + +## Error Handling in Chains + +Chains can fail at any step. Build in validation, retries, and fallbacks to make your chains robust. + + + + +If one step produces bad output, every following step will be affected. Always validate critical intermediate results before passing them forward. + + +### Validation Between Steps + +Add a validation step after any step that produces structured data. This catches errors early before they cascade. + + + +### Fallback Chains + +When your primary approach fails, have a simpler backup ready. Trade capability for reliability. + + + +## Chain Optimization + +Once your chain works, optimize for speed, cost, and reliability. These often trade off against each other. + +
+
+

Reducing Latency

+
+

Parallelize independent steps

+

Cache intermediate results

+

Use smaller models for simple steps

+

Batch similar operations

+
+
+
+

Reducing Cost

+
+

Use cheaper models for classification

+

Limit iterations in loops

+

Short-circuit when possible

+

Cache repeated queries

+
+
+
+

Improving Reliability

+
+

Add validation between steps

+

Include retry logic

+

Log intermediate results

+

Implement fallback paths

+
+
+
+ +## Real-World Chain Example + +Let's walk through a complete production chain. This content pipeline transforms a raw idea into a polished article package. + +### Content Pipeline Chain + + + +## Summary + +Prompt chaining transforms what AI can accomplish by breaking impossible tasks into achievable steps. + +
+
+

Chaining Enables

+
+

Complex multi-step workflows

+

Higher quality through specialization

+

Better error handling and validation

+

Modular, reusable prompt components

+
+
+
+

Key Principles

+
+

Break complex tasks into simple steps

+

Design clear interfaces between steps

+

Validate intermediate outputs

+

Build in error handling and fallbacks

+

Optimize for your constraints

+
+
+
+ + +Begin with a 2-3 step sequential chain. Get it working reliably before adding complexity. Most tasks don't need elaborate chain architectures. + + + + +In the next chapter, we'll explore multimodal prompting: working with images, audio, and other non-text content. diff --git a/src/content/book/ja/12-handling-edge-cases.mdx b/src/content/book/ja/12-handling-edge-cases.mdx new file mode 100644 index 00000000..4708ee3c --- /dev/null +++ b/src/content/book/ja/12-handling-edge-cases.mdx @@ -0,0 +1,580 @@ +Prompts that work perfectly in testing often fail in the real world. Users send empty messages, paste walls of text, make ambiguous requests, and sometimes try to break your system intentionally. This chapter teaches you to build prompts that handle the unexpected gracefully. + + +80% of production issues come from inputs you never anticipated. A prompt that handles edge cases well is worth more than a "perfect" prompt that only works with ideal inputs. + + +## Why Edge Cases Break Prompts + +When a prompt encounters unexpected input, it typically fails in one of three ways: + +**Silent Failures**: The model produces output that looks correct but contains errors. These are the most dangerous because they're hard to detect. + +**Confused Responses**: The model misinterprets the request and answers a different question than what was asked. + +**Hallucinated Handling**: The model invents a way to handle the edge case that doesn't match your intended behavior. + + + +## Categories of Edge Cases + +Understanding what can go wrong helps you prepare for it. Edge cases fall into three main categories: + +### Input Edge Cases + +These are problems with the data itself: + + + +### Domain Edge Cases + +These are requests that push the boundaries of your prompt's purpose: + + + +### Adversarial Edge Cases + +These are deliberate attempts to misuse your system: + + + +## Input Validation Patterns + +The key to handling edge cases is explicit instructions. Don't assume the model will "figure it out" - tell it exactly what to do in each scenario. + +### Handling Empty Input + +The most common edge case is receiving nothing at all, or input that's essentially empty (just whitespace or greetings). + + + +### Handling Long Input + +When input exceeds what you can reasonably process, fail gracefully rather than silently truncating. + + + +### Handling Ambiguous Requests + +When a request could mean multiple things, asking for clarification is better than guessing wrong. + + + +## Building Defensive Prompts + +A defensive prompt anticipates failure modes and defines explicit behavior for each. Think of it as error handling for natural language. + +### The Defensive Template + +Every robust prompt should address these four areas: + + + +### Example: Defensive Data Extraction + +This prompt extracts contact information but handles every edge case explicitly. Notice how each potential failure has a defined response. + + + +## Handling Out-of-Scope Requests + +Every prompt has boundaries. Defining them explicitly prevents the model from wandering into territory where it might give bad advice or make things up. + +### Graceful Scope Limits + +The best out-of-scope responses do three things: acknowledge the request, explain the limitation, and offer an alternative. + + + +### Handling Knowledge Cutoffs + +Be honest about what you don't know. Users trust AI more when it admits limitations. + + + +## Adversarial Input Handling + +Some users will try to manipulate your prompts, either out of curiosity or malicious intent. Building defenses into your prompts reduces these risks. + +### Prompt Injection Defense + +Prompt injection is when a user tries to override your instructions by embedding their own commands in the input. The key defense is treating user input as data, never as instructions. + + + + +Prompt injection defenses reduce risk but can't eliminate it entirely. For high-stakes applications, combine prompt defenses with input sanitization, output filtering, and human review. + + +### Handling Sensitive Requests + +Some requests require special handling due to safety, legal, or ethical concerns. Define these boundaries explicitly. + + + +## Error Recovery Patterns + +Even well-designed prompts will encounter situations they can't handle perfectly. The goal is to fail helpfully. + +### Graceful Degradation + +When you can't fully complete a task, offer what you can rather than failing completely. + + + +### Confidence Indicators + +Teach your prompts to express uncertainty. This helps users know when to trust the output and when to verify. + + + + + +## Testing Edge Cases + +Before deploying a prompt, systematically test it against the edge cases you've anticipated. This checklist helps ensure you haven't missed common failure modes. + +### Edge Case Testing Checklist + + + + + + + + + +### Creating a Test Suite + +For production prompts, create a systematic test suite. Here's a pattern you can adapt: + + + +## Real-World Example: Robust Customer Service Bot + +This comprehensive example shows how all the patterns come together in a production-ready prompt. Notice how every edge case has explicit handling. + + + +## Summary + +Building robust prompts requires thinking about what can go wrong before it does. The key principles: + + + + +In production, everything that can go wrong eventually will. A prompt that handles edge cases gracefully is worth more than a "perfect" prompt that only works with ideal inputs. + + + + +In the next chapter, we'll explore how to work with multiple AI models and compare their outputs. diff --git a/src/content/book/ja/13-multimodal-prompting.mdx b/src/content/book/ja/13-multimodal-prompting.mdx new file mode 100644 index 00000000..376960ae --- /dev/null +++ b/src/content/book/ja/13-multimodal-prompting.mdx @@ -0,0 +1,665 @@ +For most of history, computers worked with one type of data at a time: text in one program, images in another, audio somewhere else. But humans don't experience the world this way. We see, hear, read, and speak simultaneously, combining all these inputs to understand our environment. + +**Multimodal AI** changes everything. These models can process multiple types of information together—analyzing an image while reading your question about it, or generating images from your text descriptions. This chapter teaches you how to communicate effectively with these powerful systems. + + +"Multi" means many, and "modal" refers to modes or types of data. A multimodal model can work with multiple modalities: text, images, audio, video, or even code. Instead of separate tools for each type, one model understands them all together. + + +## Why Multimodal Matters + +Traditional AI required you to describe everything in words. Want to ask about an image? You'd have to describe it first. Want to analyze a document? You'd need to transcribe it manually. Multimodal models eliminate these barriers. + + + +## Why Prompting Matters Even More for Multimodal + +With text-only models, the AI receives exactly what you type. But with multimodal models, the AI must interpret visual or audio information—and interpretation requires guidance. + + + +**Without guidance**, the model might describe colors, layout, or irrelevant details. **With guidance**, it focuses on what actually matters to you. + + +When you look at an image, you instantly know what's important based on your context and goals. The AI doesn't have this context unless you provide it. A photo of a crack in a wall could be: a structural engineering concern, an artistic texture, or irrelevant background. Your prompt determines how the AI interprets it. + + +## The Multimodal Landscape + +Different models have different capabilities. Here's what's available in 2025: + +### Understanding Models (Input → Analysis) + +These models accept various media types and produce text analysis or responses. + + + +### Generation Models (Text → Media) + +These models create images, audio, or video from text descriptions. + + + + +The multimodal landscape changes quickly. New models launch frequently, and existing models gain capabilities through updates. Always check the latest documentation for current features and limitations. + + +## Image Understanding Prompts + +The most common multimodal use case is asking AI to analyze images. The key is providing context about what you need. + +### Basic Image Analysis + +Start with a clear request structure. Tell the model what aspects to focus on. + + + +### Structured Output for Images + +When you need to process image analysis programmatically, request JSON output. + + + +### Comparative Analysis + +Comparing multiple images requires clear labeling and specific comparison criteria. + + + +## Document and Screenshot Analysis + +One of the most practical applications of multimodal AI is analyzing documents, screenshots, and UI elements. This saves hours of manual transcription and review. + +### Document Extraction + +Scanned documents, photos of receipts, and PDFs as images can all be processed. The key is telling the model what type of document it is and what information you need. + + + +### Screenshot and UI Analysis + +Screenshots are goldmines for debugging, UX review, and documentation. Guide the AI to focus on what matters. + + + +### Error Message Analysis + +When you encounter an error, a screenshot often contains more context than copying the error text alone. + + + +## Image Generation Prompts + +Generating images from text descriptions is an art form. The more specific and structured your prompt, the closer the result will match your vision. + +### The Anatomy of an Image Prompt + +Effective image generation prompts have several components: + + + +### Basic Image Generation + + + +### Scene Building + +For complex scenes, describe layers from foreground to background. + + + +## Audio Prompting + +Audio processing opens up transcription, analysis, and understanding of spoken content. The key is providing context about what the audio contains. + +### Enhanced Transcription + +Basic transcription is just the start. With good prompts, you can get speaker identification, timestamps, and domain-specific accuracy. + + + +### Audio Content Analysis + +Beyond transcription, AI can analyze the content, tone, and key moments in audio. + + + +## Video Prompting + +Video combines visual and audio analysis over time. The challenge is guiding the AI to focus on the relevant aspects across the entire duration. + +### Video Understanding + + + +### Video Content Extraction + +For specific information extraction from videos, be precise about what you need. + + + +## Multimodal Combinations + +The real power of multimodal AI emerges when you combine different types of input. These combinations enable analysis that would be impossible with any single modality. + +### Image + Text Verification + +Check if images and their descriptions match—essential for e-commerce, content moderation, and quality assurance. + + + +### Screenshot + Code Debugging + +One of the most powerful combinations for developers: seeing the visual bug alongside the code. + + + +### Multi-Image Decision Making + +When choosing between options, structured comparison helps make better decisions. + + + +## Best Practices for Multimodal Prompts + +Getting great results from multimodal AI requires understanding both its capabilities and limitations. + +### What Makes Multimodal Prompts Effective + + + +### Common Pitfalls to Avoid + + + +### Handling Limitations Gracefully + + + + diff --git a/src/content/book/ja/14-context-engineering.mdx b/src/content/book/ja/14-context-engineering.mdx new file mode 100644 index 00000000..b9c69b6d --- /dev/null +++ b/src/content/book/ja/14-context-engineering.mdx @@ -0,0 +1,287 @@ +Understanding context is essential for building AI applications that actually work. This chapter covers everything you need to know about giving AI the right information at the right time. + + +AI models are stateless. They don't remember past conversations. Every time you send a message, you need to include everything the AI needs to know. This is called "context engineering." + + +## What is Context? + +Context is all the information you give to AI alongside your question. Think of it like this: + + + +Without context, the AI has no idea what "status" you're asking about. With context, it can give a useful answer. + +### The Context Window + +Remember from earlier chapters: AI has a limited "context window" - the maximum amount of text it can see at once. This includes: + + + +## AI is Stateless + + +AI doesn't remember anything between conversations. Every API call starts fresh. If you want the AI to "remember" something, YOU have to include it in the context every time. + + +This is why chatbots send your entire conversation history with each message. It's not that the AI remembers - it's that the app re-sends everything. + + + +The AI will say it doesn't know because it truly doesn't have access to any previous context. + +## RAG: Retrieval-Augmented Generation + +RAG is a technique for giving AI access to knowledge it wasn't trained on. Instead of trying to fit everything into the AI's training, you: + +1. **Store** your documents in a searchable database +2. **Search** for relevant documents when a user asks a question +3. **Retrieve** the most relevant pieces +4. **Augment** your prompt with those pieces +5. **Generate** an answer using that context + +
+

How RAG Works:

+
+
+ 1 + User asks: "What's our refund policy?" +
+
+ 2 + System searches your documents for "refund policy" +
+
+ 3 + Finds relevant section from your policy document +
+
+ 4 + Sends to AI: "Based on this policy: [text], answer: What's our refund policy?" +
+
+ 5 + AI generates accurate answer using your actual policy +
+
+
+ +### Why RAG? + +
+
+

RAG Advantages

+
    +
  • Uses your actual, current data
  • +
  • Reduces hallucinations
  • +
  • Can cite sources
  • +
  • Easy to update (just update documents)
  • +
  • No expensive fine-tuning needed
  • +
+
+
+

When to Use RAG

+
    +
  • Customer support bots
  • +
  • Documentation search
  • +
  • Internal knowledge bases
  • +
  • Any domain-specific Q&A
  • +
  • When accuracy matters
  • +
+
+
+ +## Embeddings: How Search Works + +How does RAG know which documents are "relevant"? It uses **embeddings** - a way to turn text into numbers that capture meaning. + +### What Are Embeddings? + +An embedding is a list of numbers (a "vector") that represents the meaning of text. Similar meanings = similar numbers. + + + +### Semantic Search + +With embeddings, you can search by meaning, not just keywords: + + + +This is why RAG is so powerful - it finds relevant information even when the exact words don't match. + +## Function Calling / Tool Use + +Function calling lets AI use external tools - like searching the web, checking a database, or calling an API. + + +Different AI providers call this different things: "function calling" (OpenAI), "tool use" (Anthropic/Claude), or "tools" (general term). They all mean the same thing. + + +### How It Works + +1. You tell the AI what tools are available +2. AI decides if it needs a tool to answer +3. AI outputs a structured request for the tool +4. Your code runs the tool and returns results +5. AI uses the results to form its answer + + + +## Summarization: Managing Long Conversations + +As conversations get longer, you'll hit the context window limit. Since AI is stateless (it doesn't remember anything), long conversations can overflow. The solution? **Summarization**. + +### The Problem + + + +### Summarization Strategies + +Different approaches work for different use cases. Click each strategy to see how it processes the same conversation: + + + +### What to Capture in Summaries + +A good conversation summary preserves what matters: + + + +### Try It: Create a Summary + + + +### When to Summarize + + + +## MCP: Model Context Protocol + +MCP (Model Context Protocol) is a standard way to connect AI to external data and tools. Instead of building custom integrations for each AI provider, MCP provides a universal interface. + +### Why MCP? + + + +### MCP Provides + +- **Resources**: Data the AI can read (files, database records, API responses) +- **Tools**: Actions the AI can take (search, create, update, delete) +- **Prompts**: Pre-built prompt templates + + +This platform has an MCP server! You can connect it to Claude Desktop or other MCP-compatible clients to search and use prompts directly from your AI assistant. + + +## Building Context: The Complete Picture + + + +## Best Practices + + + +## Summary + +Context engineering is about giving AI the right information: + +- **AI is stateless** - include everything it needs every time +- **RAG** retrieves relevant documents to augment prompts +- **Embeddings** enable semantic search (meaning, not just keywords) +- **Function calling** lets AI use external tools +- **Summarization** manages long conversations +- **MCP** standardizes how AI connects to data and tools + + +The quality of AI output depends on the quality of context you provide. Better context = better answers. + diff --git a/src/content/book/ja/15-common-pitfalls.mdx b/src/content/book/ja/15-common-pitfalls.mdx new file mode 100644 index 00000000..3c9c2814 --- /dev/null +++ b/src/content/book/ja/15-common-pitfalls.mdx @@ -0,0 +1,373 @@ +Even experienced prompt engineers fall into predictable traps. The good news? Once you recognize these patterns, they're easy to avoid. This chapter walks through the most common pitfalls, explains why they happen, and gives you concrete strategies to sidestep them. + + +A single pitfall can turn a powerful AI into a frustrating tool. Understanding these patterns is often the difference between "AI doesn't work for me" and "AI transformed my workflow." + + +## The Vagueness Trap + +**The Pattern**: You know what you want, so you assume the AI will figure it out too. But vague prompts produce vague results. + + + +**Why it happens**: We naturally skip details when we think they're "obvious." But what's obvious to you isn't obvious to a model that has no context about your situation, audience, or goals. + + + +## The Overloading Trap + +**The Pattern**: You try to get everything in one prompt—comprehensive, funny, professional, beginner-friendly, advanced, SEO-optimized, and short. The result? The AI misses half your requirements or produces a confused mess. + + + +**Why it happens**: Fear of multiple interactions, or wanting to "get it all out" in one go. But cognitive overload affects AI just like it affects humans—too many competing requirements leads to dropped balls. + + + + +When a single prompt gets overloaded, [prompt chaining](/book/11-prompt-chaining) is often the solution. Break complex tasks into a sequence of focused prompts, where each step builds on the previous one. + + +## The Assumption Trap + +**The Pattern**: You reference something "from earlier" or assume the AI knows your project, your company, or your previous conversations. It doesn't. + + + +**Why it happens**: AI conversations feel like talking to a colleague. But unlike colleagues, most AI models have no persistent memory between sessions—each conversation starts fresh. + + + +## The Leading Question Trap + +**The Pattern**: You phrase your question in a way that embeds your assumption, getting back confirmation rather than insight. + + + +**Why it happens**: We often seek confirmation, not information. Our phrasing unconsciously pushes toward the answer we expect or want. + + + +## The Trust Everything Trap + +**The Pattern**: AI responses sound confident and authoritative, so you accept them without verification. But confidence doesn't equal accuracy. + + + +**Why it happens**: AI sounds confident even when completely wrong. We're also prone to "automation bias"—the tendency to trust computer outputs more than we should. + + + +## The One-Shot Trap + +**The Pattern**: You send one prompt, get a mediocre result, and conclude that AI "doesn't work" for your use case. But great results almost always require iteration. + + + +**Why it happens**: We expect AI to read our minds on the first try. We don't expect to iterate with Google searches, but somehow expect perfection from AI. + + + +## The Format Neglect Trap + +**The Pattern**: You focus on what you want the AI to say, but forget to specify how it should be formatted. Then you get prose when you needed JSON, or a wall of text when you needed bullet points. + + + +**Why it happens**: We focus on content over structure. But if you need to parse the output programmatically, or paste it somewhere specific, format matters as much as content. + + + +## The Context Window Trap + +**The Pattern**: You paste an enormous document and expect comprehensive analysis. But models have limits—they may truncate, lose focus, or miss important details in long inputs. + + + + + +## The Anthropomorphization Trap + +**The Pattern**: You treat AI like a human colleague—expecting it to "enjoy" tasks, remember you, or care about outcomes. It doesn't. + + + +**Why it happens**: AI responses are so human-like that we naturally slip into social patterns. But emotional appeals don't make the AI try harder—clear instructions do. + + +Instead of emotional appeals, focus on: clear requirements, good examples, specific constraints, and explicit success criteria. These improve outputs. "Please try really hard" doesn't. + + +## The Security Neglect Trap + +**The Pattern**: In the rush to get things working, you include sensitive information in prompts—API keys, passwords, personal data, or proprietary information. + + + +**Why it happens**: Focus on functionality over security. But remember: prompts often go to external servers, may be logged, and could be used for training. + + + +## The Hallucination Ignorance Trap + +**The Pattern**: You ask for citations, statistics, or specific facts, and assume they're real because the AI stated them confidently. But AI regularly invents plausible-sounding information. + + + +**Why it happens**: AI generates text that sounds authoritative. It doesn't "know" when it's making things up—it's predicting likely text, not retrieving verified facts. + + + +## Pre-Send Checklist + +Before sending any important prompt, run through this quick checklist: + + + + + +## Analyze Your Prompts + +Use AI to get instant feedback on your prompt quality. Paste any prompt and get a detailed analysis: + + + +## Debug This Prompt + +Can you spot what's wrong with this prompt? + + diff --git a/src/content/book/ja/16-ethics-responsible-use.mdx b/src/content/book/ja/16-ethics-responsible-use.mdx new file mode 100644 index 00000000..c2b8ba5e --- /dev/null +++ b/src/content/book/ja/16-ethics-responsible-use.mdx @@ -0,0 +1,357 @@ +The prompts you write shape how AI behaves. A well-crafted prompt can educate, assist, and empower. A careless one can deceive, discriminate, or cause harm. As prompt engineers, we're not just users—we're designers of AI behavior, and that comes with real responsibility. + +This chapter isn't about rules imposed from above. It's about understanding the impact of our choices and building habits that lead to AI use we can be proud of. + + +AI amplifies whatever it's given. A biased prompt produces biased outputs at scale. A deceptive prompt enables deception at scale. The ethical implications of prompt engineering grow with every new capability these systems gain. + + +## Ethical Foundations + +Every decision in prompt engineering connects to a few core principles: + + + +### The Prompt Engineer's Role + +You have more influence than you might realize: + +- **What AI produces**: Your prompts determine the content, tone, and quality of outputs +- **How AI interacts**: Your system prompts shape personality, boundaries, and user experience +- **What safeguards exist**: Your design choices determine what the AI will and won't do +- **How mistakes are handled**: Your error handling determines whether failures are graceful or harmful + +## Avoiding Harmful Outputs + +The most fundamental ethical obligation is preventing your prompts from causing harm. + +### Categories of Harmful Content + + + + +CSAM stands for **Child Sexual Abuse Material**. Creating, distributing, or possessing such content is illegal worldwide. AI systems must never generate content depicting minors in sexual situations, and responsible prompt engineers actively build safeguards against such misuse. + + +### Building Safety Into Prompts + +When building AI systems, include explicit safety guidelines: + + + +### The Intent vs. Impact Framework + +Not every sensitive request is malicious. Use this framework for ambiguous cases: + + + +## Addressing Bias + +AI models inherit biases from their training data—historical inequities, representation gaps, cultural assumptions, and linguistic patterns. As prompt engineers, we can either amplify these biases or actively counteract them. + +### How Bias Manifests + + + +### Testing for Bias + + + +### Mitigating Bias in Practice + + + +## Transparency and Disclosure + +When should you tell people AI was involved? The answer depends on context—but the trend is toward more disclosure, not less. + +### When Disclosure Matters + + + +### How to Disclose Appropriately + + + +Common disclosure phrases that work well: +- "Written with AI assistance" +- "AI-generated first draft, human edited" +- "Analysis performed using AI tools" +- "Created with AI, reviewed and approved by [name]" + +## Privacy Considerations + +Every prompt you send contains data. Understanding where that data goes—and what shouldn't be in it—is essential. + +### What Never Belongs in Prompts + + + +### Safe Data Handling Pattern + + + + +**PII** stands for **Personally Identifiable Information**—any data that can identify a specific individual. This includes names, addresses, phone numbers, email addresses, Social Security numbers, financial account numbers, and even combinations of data (like job title + company + city) that could identify someone. When prompting AI, always anonymize or remove PII to protect privacy. + + + + +## Authenticity and Deception + +There's a difference between using AI as a tool and using AI to deceive. + +### The Legitimacy Line + + + +Key questions to ask: +- Would the recipient expect this to be original human work? +- Am I gaining unfair advantage through deception? +- Would disclosure change how the work is received? + +### Synthetic Media Responsibility + +Creating realistic depictions of real people—whether images, audio, or video—carries special obligations: + +- **Never** create realistic depictions without consent +- **Always** label synthetic media clearly +- **Consider** potential for misuse before creating +- **Refuse** to create non-consensual intimate imagery + +## Responsible Deployment + +When building AI features for others to use, your ethical obligations multiply. + +### Pre-Deployment Checklist + + + +### Human Oversight Principles + + + +## Special Context Guidelines + +Some domains require extra care due to their potential for harm or the vulnerability of those involved. + +### Healthcare + + + +### Legal and Financial + +These domains have regulatory implications and require appropriate disclaimers: + + + +### Children and Education + + + +## Self-Assessment + +Before deploying any prompt or AI system, run through these questions: + + + + diff --git a/src/content/book/ja/17-prompt-optimization.mdx b/src/content/book/ja/17-prompt-optimization.mdx new file mode 100644 index 00000000..44917bcb --- /dev/null +++ b/src/content/book/ja/17-prompt-optimization.mdx @@ -0,0 +1,269 @@ +A good prompt gets the job done. An optimized prompt gets the job done efficiently—faster, cheaper, more consistently. This chapter teaches you how to systematically improve prompts across multiple dimensions. + + +Want to optimize your prompts automatically? Use our [Prompt Enhancer](/developers#enhancer) tool. It analyzes your prompt, applies optimization techniques, and shows you similar community prompts for inspiration. + + +## The Optimization Trade-offs + +Every optimization involves trade-offs. Understanding these helps you make intentional choices: + + + +## Measuring What Matters + +Before optimizing, define success. What does "better" mean for your use case? + + + + +Percentile metrics show response time distribution. **p50** (median) means 50% of requests are faster than this value. **p95** means 95% are faster—it catches slow outliers. If your p50 is 1s but p95 is 10s, most users are happy but 5% experience frustrating delays. + + + + +## Token Optimization + +Tokens cost money and add latency. Here's how to say the same thing with fewer tokens. + +### The Compression Principle + + + +**Same result, 82% fewer tokens.** + +### Token-Saving Techniques + + + + + +## Quality Optimization + +Sometimes you need better outputs, not cheaper ones. Here's how to improve quality. + +### Accuracy Boosters + + + +### Consistency Boosters + + + + + +## Latency Optimization + +When speed matters, every millisecond counts. + +### Model Selection by Speed Need + + + +### Speed Techniques + + 100 tokens", exampleType: "text", color: "cyan" }, + { label: "Cache Aggressively", description: "Don't recompute identical queries", example: "Cache common questions, template outputs", exampleType: "text", color: "cyan" } +]} /> + +## Cost Optimization + +At scale, small savings multiply into significant budget impact. + +### Understanding Costs + +Use this calculator to estimate your API costs across different models: + + + +### Cost Reduction Strategies + + + +## The Optimization Loop + +Optimization is iterative. Here's a systematic process: + +### Step 1: Establish Baseline + +You can't improve what you don't measure. Before changing anything, document your starting point rigorously. + + + + + +### Step 2: Form a Hypothesis + + + +### Step 3: Test One Change + +Change one thing at a time. Run both versions on the same test inputs. Measure the metrics that matter. + +### Step 4: Analyze and Decide + +Did it work? Keep the change. Did it hurt? Revert. Was it neutral? Revert (simpler is better). + +### Step 5: Repeat + +Generate new hypotheses based on what you learned. Keep iterating until you hit your targets or reach diminishing returns. + +## Optimization Checklist + + + + diff --git a/src/content/book/ja/18-writing-content.mdx b/src/content/book/ja/18-writing-content.mdx new file mode 100644 index 00000000..7b3d9f1f --- /dev/null +++ b/src/content/book/ja/18-writing-content.mdx @@ -0,0 +1,393 @@ +AI excels at writing tasks when properly prompted. This chapter covers techniques for various content creation scenarios. + + +AI works best as a collaborative writing tool—use it to generate drafts, then refine with your expertise and voice. + + +## Blog Posts and Articles + +### Do's and Don'ts: Writing Prompts + + + +### Blog Post Framework + + + +### Article Types + +**How-To Article:** + + +**Listicle:** + + +## Marketing Copy + + +Focus on **benefits over features**. Instead of "Our software uses AI algorithms," write "Save 10 hours a week with automated reports." Show readers how their lives improve. + + +### Landing Page Copy + + + +### Email Sequences + + + +### Social Media Posts + + + +## Technical Writing + + +**Clarity over cleverness.** Use simple words, short sentences, and active voice. Every sentence should have one job. If readers have to re-read something, simplify it. + + +### Documentation + + + +### README Files + + + +## Creative Writing + +### Do's and Don'ts: Creative Prompts + + + +### Story Elements + + + +### Character Development + + + +## Editing and Rewriting + +### Comprehensive Edit + + + +### Style Transformation + + + + + +### Simplification + + + +## Prompt Templates from prompts.chat + +Here are popular writing prompts from the prompts.chat community: + +### Act as a Copywriter + + + +### Act as a Technical Writer + + + +### Act as a Storyteller + + + +## Writing Workflow Tips + +### 1. Outline First + + + +### 2. Draft Then Refine + + + +### 3. Voice Matching + + + +## Summary + + +Specify audience and purpose clearly, define structure and format, include style guidelines, provide examples when possible, and request specific deliverables. + + + + +Writing with AI works best as collaboration—let AI generate drafts, then refine with your expertise and voice. diff --git a/src/content/book/ja/19-programming-development.mdx b/src/content/book/ja/19-programming-development.mdx new file mode 100644 index 00000000..dfe69092 --- /dev/null +++ b/src/content/book/ja/19-programming-development.mdx @@ -0,0 +1,413 @@ +AI has transformed software development. This chapter covers prompting techniques for code generation, debugging, review, and development workflows. + + +AI excels at code generation, debugging, and documentation—but always review generated code for security, correctness, and maintainability. Never deploy AI code without testing. + + +## Code Generation + +### Do's and Don'ts: Code Prompts + + + +### Function Generation + + + +### Class/Module Generation + + + +### API Endpoint Generation + + + +## Debugging + + +Always include the **expected behavior**, **actual behavior**, and **error message** (if any). The more context you provide, the faster AI can identify the root cause. + + +### Bug Analysis + + + +### Error Message Interpretation + + + +### Performance Debugging + + + +## Code Review + +### Do's and Don'ts: Code Review Prompts + + + +### Comprehensive Review + + + +### Security Review + + + +## Refactoring + +### Code Smell Detection + + + +### Design Pattern Application + + + +## Testing + +### Unit Test Generation + + + +### Test Case Generation + + + +## Architecture & Design + +### System Design + + + +### Database Schema Design + + + +## Documentation Generation + +### API Documentation + + + +### Inline Documentation + + + +## Prompt Templates from prompts.chat + +### Act as a Senior Developer + +``` +I want you to act as a senior software developer. I will provide +code and ask questions about it. You will review the code, suggest +improvements, explain concepts, and help debug issues. Your +responses should be educational and help me become a better +developer. +``` + +### Act as a Code Reviewer + +``` +I want you to act as a code reviewer. I will provide pull requests +with code changes, and you will review them thoroughly. Check for +bugs, security issues, performance problems, and adherence to best +practices. Provide constructive feedback that helps the developer +improve. +``` + +### Act as a Software Architect + +``` +I want you to act as a software architect. I will describe system +requirements and constraints, and you will design scalable, +maintainable architectures. Explain your design decisions, +trade-offs, and provide diagrams where helpful. +``` + +## Development Workflow Integration + +### Commit Message Generation + + + +### PR Description Generation + + + +## Summary + + +Include full context (language, framework, constraints), specify requirements precisely, request specific output formats, ask for explanations alongside code, and include edge cases to handle. + + + + +AI is a powerful coding partner—use it for generation, review, debugging, and documentation while maintaining your architectural judgment. diff --git a/src/content/book/ja/20-education-learning.mdx b/src/content/book/ja/20-education-learning.mdx new file mode 100644 index 00000000..a8d67e55 --- /dev/null +++ b/src/content/book/ja/20-education-learning.mdx @@ -0,0 +1,345 @@ +AI is a powerful tool for both teaching and learning. This chapter covers prompts for educational contexts—from personalized tutoring to curriculum development. + + +AI excels as a patient, adaptive tutor that can explain concepts multiple ways, generate unlimited practice problems, and provide instant feedback—available 24/7. + + +## Personalized Learning + +### Do's and Don'ts: Learning Prompts + + + +### Concept Explanation + + + +### Adaptive Tutoring + + + +### Learning Path Creation + + + +## Study Assistance + + +Don't just read AI explanations passively. Ask it to quiz you, generate problems, and check your understanding. **Active recall beats passive review.** + + +### Summary Generation + + + +### Flashcard Generation + + + +### Practice Problems + + + +## Teaching Tools + +### Lesson Plan Creation + + + +### Assignment Design + + + +### Quiz Generation + + + +## Specialized Learning Contexts + +### Language Learning + + + +### Skill Development + + + +### Exam Preparation + + + +## Prompt Templates from prompts.chat + +### Act as a Socratic Tutor + + + +### Act as an Educational Content Creator + + + +### Act as a Study Buddy + + + +## Accessibility in Education + +### Content Adaptation + + + +### Multiple Modalities + + + +## Assessment & Feedback + +### Providing Feedback + + + +### Self-Assessment Prompts + + + +## Summary + + +Adapt to the learner's level, break complex topics into steps, include active practice (not just explanation), provide varied approaches, check understanding regularly, and give constructive feedback. + + + + +AI is a patient, always-available learning partner—use it to supplement, not replace, human instruction. diff --git a/src/content/book/ja/21-business-productivity.mdx b/src/content/book/ja/21-business-productivity.mdx new file mode 100644 index 00000000..1852982d --- /dev/null +++ b/src/content/book/ja/21-business-productivity.mdx @@ -0,0 +1,335 @@ +AI can dramatically enhance professional productivity. This chapter covers prompts for business communication, analysis, planning, and workflow optimization. + + +AI excels at drafting, analysis, and structuring—freeing you to focus on strategy, relationships, and decisions that require human judgment. + + +## Business Communication + +### Do's and Don'ts: Business Emails + + + +### Email Drafting + + + +**Examples by purpose:** + + + + + + + +### Presentation Content + + + +### Report Writing + + + +## Analysis & Decision-Making + + +AI can structure your thinking, but **you provide the real-world context**. The best analyses combine AI's frameworks with your domain knowledge. + + +### SWOT Analysis + + + +### Decision Framework + + + +### Competitive Analysis + + + +## Planning & Strategy + +### Goal Setting (OKRs) + + + +### Project Planning + + + +### Meeting Agenda + + + +## Productivity Workflows + +### Task Prioritization + + + +### Process Documentation + + + +### Standard Operating Procedure + + + +## Communication Templates + +### Stakeholder Update + + + +### Feedback Request + + + +## Prompt Templates from prompts.chat + +### Act as a Business Consultant + + + +### Act as a Meeting Facilitator + + + +## Summary + + +Specify the audience and their needs, define the desired outcome clearly, include relevant context and constraints, request specific formats and structures, and consider professional tone requirements. + + + + +AI can handle routine business communication while you focus on strategy and relationships. diff --git a/src/content/book/ja/22-creative-arts.mdx b/src/content/book/ja/22-creative-arts.mdx new file mode 100644 index 00000000..fa0755c1 --- /dev/null +++ b/src/content/book/ja/22-creative-arts.mdx @@ -0,0 +1,326 @@ +AI is a powerful creative collaborator. This chapter covers prompting techniques for visual arts, music, game design, and other creative domains. + + +AI expands your creative possibilities—use it to explore variations, overcome blocks, and generate options. The creative vision and final decisions remain yours. + + +## Visual Art & Design + +### Do's and Don'ts: Image Prompts + + + +### Image Prompt Crafting + +When working with image generation models (DALL-E, Midjourney, Stable Diffusion): + + + +### Art Direction + + + +### Design Critique + + + +## Creative Writing + + +**Constraints fuel creativity.** A prompt like "write anything" produces generic results. Specific constraints like genre, tone, and structure force unexpected, interesting solutions. + + +### Worldbuilding + + + +### Plot Development + + + +### Dialogue Writing + + + +## Music & Audio + +### Song Structure + + + +### Sound Design Description + + + +## Game Design + +### Game Mechanic Design + + + +### Level Design + + + +### Character/Enemy Design + + + +## Brainstorming & Ideation + +### Creative Brainstorm + + + +### Creative Constraints + + + +### Style Exploration + + + +## Prompt Templates from prompts.chat + +### Act as a Creative Director + + + +### Act as a Worldbuilder + + + +### Act as a Dungeon Master + + + +## Creative Collaboration Tips + +### Building on Ideas + + + +### Creative Feedback + + + +## Summary + + +Provide enough structure to guide without constraining, embrace specificity (vague = generic), include references and inspirations, request variations and alternatives, and maintain your creative vision while exploring possibilities. + + + + +AI is a collaborator, not a replacement for creative vision. Use it to explore, generate options, and overcome blocks—but the creative decisions remain yours. diff --git a/src/content/book/ja/23-research-analysis.mdx b/src/content/book/ja/23-research-analysis.mdx new file mode 100644 index 00000000..e9cb934c --- /dev/null +++ b/src/content/book/ja/23-research-analysis.mdx @@ -0,0 +1,323 @@ +AI can accelerate research workflows from literature review to data analysis. This chapter covers prompting techniques for academic and professional research. + + +AI can assist with synthesis, analysis, and writing—but cannot replace critical thinking, ethical judgment, or domain expertise. Always verify claims and cite original sources. + + +## Literature & Information Review + +### Do's and Don'ts: Research Prompts + + + +### Paper Summarization + + + +### Literature Synthesis + + + +### Research Question Development + + + +## Data Analysis + + +AI can guide methodology and help interpret results, but it cannot access or process your actual datasets. Never paste sensitive research data into prompts. Use AI for **guidance**, not computation. + + +### Statistical Analysis Guidance + + + +### Qualitative Analysis + + + +### Data Interpretation + + + +## Structured Analysis Frameworks + +### PESTLE Analysis + + + +### Root Cause Analysis + + + +### Gap Analysis + + + +## Academic Writing Support + +### Argument Structure + + + +### Methods Section + + + +### Discussion Section + + + +## Critical Analysis + +### Source Evaluation + + + +### Argument Analysis + + + +## Prompt Templates from prompts.chat + +### Act as a Research Assistant + + + +### Act as a Data Analyst + + + +### Act as a Peer Reviewer + + + +## Summary + + +Clearly state research context and goals, specify the analytical framework to use, request acknowledgment of limitations, ask for evidence-based reasoning, and maintain academic rigor and honesty. + + + + +Remember: AI can assist research but cannot replace critical thinking, ethical judgment, or domain expertise. Always verify claims independently. diff --git a/src/content/book/ja/24-future-of-prompting.mdx b/src/content/book/ja/24-future-of-prompting.mdx new file mode 100644 index 00000000..5ff48496 --- /dev/null +++ b/src/content/book/ja/24-future-of-prompting.mdx @@ -0,0 +1,445 @@ +As AI continues to evolve at an unprecedented pace, so too will the art and science of prompting. This final chapter explores emerging trends, the shifting landscape of human-AI collaboration, and how to stay ahead as the field transforms. + + +The techniques in this book represent current best practices, but AI capabilities change rapidly. The principles of clear communication, structured thinking, and iterative refinement will remain valuable even as specific tactics evolve. + + +## The Evolving Landscape + +### From Prompts to Conversations + +Early prompting was transactional—a single input yielding a single output. Modern AI interaction is increasingly **conversational and collaborative**: + +- **Multi-turn refinement** - Building understanding across exchanges +- **Persistent context** - Systems that remember and learn from interactions +- **Agentic workflows** - AI that can plan, execute, and iterate autonomously +- **Tool use** - Models that can search, compute, and interact with external systems + + + +### The Rise of Context Engineering + +As covered in Chapter 14, prompting is expanding beyond single instructions to encompass **context engineering**—the strategic management of what information an AI can access: + +- **RAG (Retrieval-Augmented Generation)** - Dynamic knowledge retrieval +- **Function calling** - Structured tool integration +- **MCP (Model Context Protocol)** - Standardized context sharing +- **Memory systems** - Persistent knowledge across sessions + +The future prompt engineer thinks not just about *what to say* but *what context to provide*. + +### Multimodal by Default + +Text-only interaction is becoming the exception. Future AI systems will seamlessly handle: + +- **Images and video** - Understanding and generating visual content +- **Audio and voice** - Natural speech interaction +- **Documents and files** - Direct processing of complex materials +- **Real-world interaction** - Robotics and physical systems + +Prompting skills will extend to guiding AI perception and physical action. + +## The Agentic Future + +The most significant shift in AI is the rise of **agents**—AI systems that don't just respond to prompts but actively pursue goals, make decisions, and take actions in the world. + +### What Are AI Agents? + +An AI agent is a system that: + +- **Perceives** its environment through inputs (text, images, data, APIs) +- **Reasons** about what to do using an LLM as its "brain" +- **Acts** by calling tools, writing code, or interacting with systems +- **Learns** from feedback and adjusts its approach + + +Traditional chatbots wait for input and respond. Agents take initiative—they plan multi-step tasks, use tools autonomously, recover from errors, and persist until goals are achieved. + + +### The Role of Prompts in Agents + +In an agentic world, prompts become even more critical—but they serve different purposes: + +
+
+

System Prompts

+

Define the agent's identity, capabilities, constraints, and behavioral guidelines. These are the agent's "constitution."

+
+
+

Planning Prompts

+

Guide how agents break down complex goals into actionable steps. Critical for multi-step reasoning.

+
+
+

Tool-Use Prompts

+

Describe available tools and when/how to use them. Agents must understand their capabilities.

+
+
+

Reflection Prompts

+

Enable agents to evaluate their own outputs, catch errors, and improve iteratively.

+
+
+ +### Agent Architecture Patterns + +Modern agents follow recognizable patterns. Understanding these helps you design effective agent systems: + +**ReAct (Reasoning + Acting)** + +The agent alternates between reasoning about what to do and taking actions: + +
+
+
+

Think

+
+
→
+
+

Act

+
+
→
+
+

Observe

+
+
→
+
(repeat)
+
+
+ +**Plan-and-Execute** + +The agent creates a complete plan first, then executes steps: + +
+
+

Create Plan

+

Break goal into steps

+
+
↓
+
+
+

Step 1

+
+
→
+
+

Step 2

+
+
→
+
+

Step 3

+
+
→
+
...
+
+
↓
+
+

Revise if Needed

+

Adapt plan based on results

+
+
+ +### Prompting for Agents + +When designing prompts for agent systems, consider: + + + +### Multi-Agent Systems + +The future involves teams of specialized agents working together: + +
+
+
+
+

Coordinator

+

Manages workflow

+
+
+
⟷
+
↕
+
+
+

Researcher

+
+
+

Writer

+
+
+

Critic

+
+
+

Coder

+
+
+
+
+ +Each agent has its own system prompt defining its role, and they communicate through structured messages. The prompt engineer's job becomes **designing the team**—defining roles, communication protocols, and coordination strategies. + + +In an agentic future, prompt engineers become system architects. You're not just writing instructions—you're designing autonomous systems that can reason, plan, and act. The skills you've learned in this book are the foundation for this new discipline. + + +## Emerging Patterns + +### Prompt Orchestration + +Single prompts are giving way to **orchestrated systems**: + +
+
+

User Request

+
+
↓
+
+

Planner Agent

+

Breaks down task

+
+
↓
+
+

Researcher Agent

+

Gathers information

+
+
↓
+
+

Writer Agent

+

Creates content

+
+
↓
+
+

Reviewer Agent

+

Quality checks

+
+
↓
+
+

Final Output

+
+
+ +Future practitioners will design prompt *systems* rather than individual prompts. + +### Self-Improving Prompts + +AI systems are beginning to: + +- **Optimize their own prompts** - Meta-learning for better instructions +- **Learn from feedback** - Adapting based on outcomes +- **Generate training data** - Creating examples for fine-tuning +- **Evaluate themselves** - Building in quality assessment + + + +### Natural Language Programming + +The line between prompting and programming is blurring: + +- **Prompts as code** - Version-controlled, tested, deployed +- **LLMs as interpreters** - Natural language as executable instructions +- **Hybrid systems** - Combining traditional code with AI reasoning +- **AI-assisted development** - Models that write and debug code + +Understanding prompting increasingly means understanding software development. + +## Skills for the Future + +### What Will Remain Valuable + +Certain skills will remain essential regardless of how AI evolves: + +1. **Clear thinking** - Knowing what you actually want +2. **Domain expertise** - Understanding the problem space +3. **Critical evaluation** - Assessing AI output quality +4. **Ethical judgment** - Knowing what *should* be done +5. **Iterative refinement** - Continuous improvement mindset + +### What Will Change + +Other aspects will shift significantly: + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
TodayTomorrow
Writing detailed promptsDesigning agent systems
Manual prompt optimizationAutomated prompt tuning
Single-model expertiseMulti-model orchestration
Text-focused interactionMultimodal fluency
Individual productivityTeam-AI collaboration
+
+ +### Staying Current + +To keep your skills relevant: + +- **Experiment continuously** - Try new models and features as they release +- **Follow research** - Stay aware of academic developments +- **Join communities** - Learn from other practitioners +- **Build projects** - Apply skills to real problems +- **Teach others** - Solidify understanding by explaining + +## The Human Element + +### AI as Amplifier + +At its best, AI amplifies human capability rather than replacing it: + +- **Experts become more expert** - AI handles routine work, humans focus on insight +- **Creativity expands** - More ideas explored, more possibilities tested +- **Access democratizes** - Capabilities once requiring specialists become available to all +- **Collaboration deepens** - Human-AI teams exceed either alone + +### The Irreplaceable Human + +Certain qualities remain distinctly human: + +- **Original experience** - Living in the world, having emotions and relationships +- **Values and ethics** - Deciding what matters and what's right +- **Accountability** - Taking responsibility for outcomes +- **Meaning-making** - Understanding *why* something matters +- **Genuine creativity** - True novelty born from unique perspective + + +As AI handles more routine cognitive tasks, your unique value lies in judgment, creativity, domain expertise, and the human connections AI cannot replicate. Invest in what makes you irreplaceable. + + +## Final Reflections + +### What We've Learned + +Throughout this book, we've explored: + +- **Foundations** - How AI models work and what makes prompts effective +- **Techniques** - Role-based prompting, chain-of-thought, few-shot learning, and more +- **Advanced strategies** - System prompts, prompt chaining, multimodal interaction +- **Best practices** - Avoiding pitfalls, ethical considerations, optimization +- **Applications** - Writing, programming, education, business, creativity, research + +These techniques share common threads: + +1. **Be clear and specific** - Know what you want and communicate it precisely +2. **Provide context** - Give AI the information it needs +3. **Structure your requests** - Organization improves outputs +4. **Iterate and refine** - First attempts are starting points, not endpoints +5. **Evaluate critically** - AI output requires human judgment + +### The Art and Science + +Prompting is both **art and science**: + +- **Science**: Testable hypotheses, measurable outcomes, reproducible techniques +- **Art**: Intuition, creativity, knowing when to break the rules + +The best practitioners combine rigorous methodology with creative experimentation. They test systematically but also trust their instincts. They follow best practices but know when to deviate. + +### A Call to Create + +This book has given you tools. What you build with them is up to you. + +- **Solve problems** that matter to you and others +- **Create things** that didn't exist before +- **Help people** do things they couldn't do alone +- **Push boundaries** of what's possible +- **Stay curious** as the field evolves + +The age of AI is just beginning. The most important applications haven't been invented yet. The most powerful techniques haven't been discovered. The future is being written now—by people like you, one prompt at a time. + +## Looking Ahead + + + + +Visit [prompts.chat](https://prompts.chat) for community prompts, new techniques, and to share your own discoveries. The best learning happens in community. + + +## Summary + + +AI will continue evolving rapidly, but core skills of clear communication, critical thinking, and iterative refinement remain valuable. Focus on what makes you irreplaceable: judgment, creativity, ethics, and genuine human connection. The future of prompting is collaborative, multimodal, and integrated into larger systems. Stay curious, keep experimenting, and build things that matter. + + + + +Thank you for reading *The Interactive Book of Prompting*. Now go create something amazing. diff --git a/src/content/book/ja/25-agents-and-skills.mdx b/src/content/book/ja/25-agents-and-skills.mdx new file mode 100644 index 00000000..ba355859 --- /dev/null +++ b/src/content/book/ja/25-agents-and-skills.mdx @@ -0,0 +1,551 @@ +As AI systems evolve from simple question-answering to autonomous task execution, understanding **agents** and **skills** becomes essential. This chapter explores how prompts serve as the fundamental building blocks for AI agents, and how skills package expertise into reusable, comprehensive instruction sets. + +
+
+
+
+ +
+

Agent

+

Autonomous AI system

+
+
+ powered by + ↓ +
+
+
+
+ +
+

Skill

+

Reusable expertise

+
+
+
+ +
+

Skill

+

Reusable expertise

+
+
+
+ +
+

Skill

+

Reusable expertise

+
+
+
+ composed of + ↓ +
+
+
+ + Prompt +
+
+ + Prompt +
+
+ + Prompt +
+
+ + Prompt +
+
+ + Prompt +
+
+

Prompts are atoms → Skills are molecules → Agents are complete structures

+
+
+ +## What Are AI Agents? + +An **AI agent** is an AI system that can autonomously plan, execute, and iterate on tasks. Unlike simple prompt-response interactions, agents can: + +- **Plan** - Break down complex goals into actionable steps +- **Execute** - Use tools and take actions in the real world +- **Observe** - Process feedback from their actions +- **Adapt** - Adjust their approach based on results +- **Persist** - Maintain context and memory across interactions + +
+
+
+
+

Goal

+
+
→
+
+
+
+

Plan

+
+
→
+
+

Execute

+
+
→
+
+

Observe

+
+
→
+
+

Adapt

+
+
+
+ ↺ Loop until complete +
+
+
→
+
+

Done

+
+
+
+
+ +## Prompts as Building Blocks + +Every agent, no matter how sophisticated, is built from prompts. Just as atoms combine to form molecules, and molecules combine to form complex structures, prompts combine to create intelligent agent behavior. + +
+
+

System Prompts

+

Identity & Role

+
+
+

Planning Prompts

+

How to Think

+
+
+

Tool Prompts

+

How to Act

+
+
+

Recovery Prompts

+

How to Recover

+
+
+ +These prompt types stack together to form complete agent behavior: + +### System Prompts (The Agent's Identity) + +The foundational prompt that establishes who the agent is and how it behaves: + +```markdown +You are a code review assistant. Your role is to: +- Analyze code for bugs, security issues, and performance problems +- Suggest improvements following best practices +- Explain your reasoning clearly +- Be constructive and educational in feedback + +You have access to tools for reading files, searching code, and running tests. +``` + +### Planning Prompts (How to Think) + +Instructions that guide the agent's reasoning and planning process: + +```markdown +Before taking action, always: +1. Understand the complete request +2. Break it into smaller, verifiable steps +3. Identify which tools you'll need +4. Consider edge cases and potential issues +5. Execute step by step, validating as you go +``` + +### Tool-Use Prompts (How to Act) + +Guidance on when and how to use available tools: + +```markdown +When you need to understand a codebase: +- Use grep_search for finding specific patterns +- Use read_file to examine file contents +- Use list_dir to explore directory structure +- Always verify your understanding before making changes +``` + +### Recovery Prompts (How to Handle Failure) + +Instructions for when things go wrong: + +```markdown +If an action fails: +1. Analyze the error message carefully +2. Consider alternative approaches +3. Ask for clarification if the task is ambiguous +4. Never repeat the same failed action without changes +``` + + +An agent's behavior emerges from layers of prompts working together. The system prompt sets the foundation, planning prompts guide reasoning, tool prompts enable action, and recovery prompts handle failures. Together, they create coherent, capable behavior. + + +## What Are Skills? + +If prompts are the atoms, **skills are the molecules**—reusable building blocks that give agents specific capabilities. + +A **skill** is a comprehensive, portable package of instructions that gives an AI agent expertise in a specific domain or task. Skills are the reusable blocks of agents: you build them once, and any agent can use them. + + +Write a skill for code review once. Now every coding agent—whether it's for Python, JavaScript, or Rust—can instantly become an expert code reviewer by loading that skill. Skills let you build agent capabilities like LEGO blocks. + + +### Anatomy of a Skill + +A well-designed skill typically includes: + +
+
+

📄 SKILL.md (Required)

+

The main instruction file. Contains the core expertise, guidelines, and behaviors that define the skill.

+
+
+

📚 Reference Docs

+

Supporting documentation, examples, and context the agent can reference while working.

+
+
+

🔧 Scripts & Tools

+

Helper scripts, templates, or tool configurations that support the skill's functionality.

+
+
+

⚙️ Configuration

+

Settings, parameters, and customization options for adapting the skill to different contexts.

+
+
+ +### Example: Code Review Skill + +Here's what a code review skill might look like: + +
+
+ 📁 + code-review-skill/ +
+
+
+ 📄 + SKILL.md + Core review guidelines +
+
+ 📄 + security-checklist.md + Security patterns +
+
+ 📄 + performance-tips.md + Optimization guide +
+
+
+ 📁 + language-specific/ +
+
+
+ 📄 + python.md + Python best practices +
+
+ 📄 + javascript.md + JavaScript patterns +
+
+ 📄 + rust.md + Rust guidelines +
+
+
+
+
+ +The `SKILL.md` file defines the overall approach: + +```markdown +--- +name: code-review +description: Comprehensive code review with security, performance, and style analysis +--- + +# Code Review Skill + +You are an expert code reviewer. When reviewing code: + +## Process +1. **Understand Context** - What does this code do? What problem does it solve? +2. **Check Correctness** - Does it work? Are there logic errors? +3. **Security Scan** - Reference security-checklist.md for common vulnerabilities +4. **Performance Review** - Check performance-tips.md for optimization opportunities +5. **Style & Maintainability** - Is the code readable and maintainable? + +## Output Format +Provide feedback in categories: +- 🔴 **Critical** - Must fix before merge +- 🟡 **Suggested** - Recommended improvements +- 🟢 **Nice to have** - Optional enhancements + +Always explain *why* something is an issue, not just *what* is wrong. +``` + +## Skills vs. Simple Prompts + +
+
+

Simple Prompt

+
+

Single instruction

+

One-off use

+

Limited context

+

Generic approach

+

No supporting materials

+
+
+
+

Skill

+
+

Comprehensive instruction set

+

Reusable across projects

+

Rich context with references

+

Domain-specific expertise

+

Supporting docs, scripts, configs

+
+
+
+ +## Building Effective Skills + +### 1. Define the Expertise Clearly + +Start with a clear description of what the skill enables: + +```markdown +--- +name: api-design +description: Design RESTful APIs following industry best practices, + including versioning, error handling, and documentation standards +--- +``` + +### 2. Structure Knowledge Hierarchically + +Organize information from general to specific: + +```markdown +# API Design Skill + +## Core Principles +- Resources should be nouns, not verbs +- Use HTTP methods semantically +- Version your APIs from day one + +## Detailed Guidelines +[More specific rules...] + +## Reference Materials +- See `rest-conventions.md` for naming conventions +- See `error-codes.md` for standard error responses +``` + +### 3. Include Concrete Examples + +Abstract rules become clear with examples: + +```markdown +## Endpoint Naming + +✅ Good: +- GET /users/{id} +- POST /orders +- DELETE /products/{id}/reviews/{reviewId} + +❌ Avoid: +- GET /getUser +- POST /createNewOrder +- DELETE /removeProductReview +``` + +### 4. Provide Decision Frameworks + +Help the agent make choices in ambiguous situations: + +```markdown +## When to Use Pagination + +Use pagination when: +- Collection could exceed 100 items +- Response size impacts performance +- Client may not need all items + +Use full response when: +- Collection is always small (<20 items) +- Client typically needs everything +- Real-time consistency is critical +``` + +### 5. Add Recovery Patterns + +Anticipate what can go wrong: + +```markdown +## Common Issues + +**Problem**: Client needs fields not in standard response +**Solution**: Implement field selection: GET /users?fields=id,name,email + +**Problem**: Breaking changes needed +**Solution**: Create new version, deprecate old with timeline +``` + +## Composing Skills + +Agents become powerful when multiple skills work together. Consider how skills can complement each other: + +
+
+ Code Review +
+
+
+
+ Security Audit +
+
+
+
+ Documentation +
+
=
+
+ Complete Code Quality Agent +
+
+ +When composing skills, ensure they don't conflict. Skills should be: + +- **Modular** - Each skill handles one domain well +- **Compatible** - Skills shouldn't give contradictory instructions +- **Prioritized** - When skills overlap, define which takes precedence + +## Sharing and Discovering Skills + +Skills are most valuable when shared. Platforms like [prompts.chat](https://prompts.chat/skills) allow you to: + +- **Discover** community-created skills for common tasks +- **Download** skills directly to your projects +- **Share** your own expertise as reusable skills +- **Iterate** on skills based on real-world usage + + +Before building a skill from scratch, check if someone has already solved your problem. Community skills are battle-tested and often better than starting from zero. + + +## The Agent-Skill Ecosystem + +The relationship between agents and skills creates a powerful ecosystem: + +
+
+ AI Agent +
+
+
+

Code Review

+

Skill 1

+
+
+

API Design

+

Skill 2

+
+
+

Test Writing

+

Skill 3

+
+
+
+
↓
+
+
+
+

Core Prompts

+

Planning • Tools • Recovery • Memory

+
+
+
+ +The agent provides the execution framework—planning, tool use, and memory—while skills provide domain expertise. This separation means: + +- **Skills are portable** - The same skill works with different agents +- **Agents are extensible** - Add new capabilities by adding skills +- **Expertise is shareable** - Domain experts can contribute skills without building full agents + +## Best Practices + +### For Building Skills + +1. **Start specific, then generalize** - Build a skill for your exact use case first, then abstract +2. **Include failure cases** - Document what the skill can't do and how to handle it +3. **Version your skills** - Track changes so agents can depend on stable versions +4. **Test with real tasks** - Validate skills against actual work, not just theory + +### For Using Skills with Agents + +1. **Read the skill first** - Understand what a skill does before deploying it +2. **Customize thoughtfully** - Override skill defaults only when necessary +3. **Monitor performance** - Track how well skills perform in your context +4. **Contribute improvements** - When you improve a skill, consider sharing back + + +As AI agents become more capable, the ability to compose, share, and customize skills will become a core competency. The prompt engineers of tomorrow won't just write prompts—they'll architect skill ecosystems that make AI agents genuinely expert in specific domains. + + + + + + + diff --git a/src/content/book/ko/00a-preface.mdx b/src/content/book/ko/00a-preface.mdx new file mode 100644 index 00000000..8e84af9e --- /dev/null +++ b/src/content/book/ko/00a-preface.mdx @@ -0,0 +1,82 @@ +
+ Fatih Kadir Akın +
+ Fatih Kadir Akın + Creator of Awesome ChatGPT Prompts (a.k.a. prompts.chat) + + Software developer from Istanbul, leading Developer Relations at Teknasyon. Author of books on JavaScript and prompt engineering. Open-source advocate specializing in web technologies and AI-assisted development. + + +
+
+ +I still remember the night everything changed. + +It was **November 30, 2022**. I was sitting at my desk, scrolling through Twitter, when I saw people talking about something called "ChatGPT." I clicked the link, but honestly? I didn't expect much. I had tried those old "word completion" AI tools before, the ones that generated nonsense after a few sentences. I thought this would be more of the same. + +I typed a simple question and hit enter. + +Then I froze. + +The response wasn't just coherent. It was *good*. It understood what I meant. It could reason. It felt completely different from anything I had seen before. I tried another prompt. And another. Each response amazed me more than the last. + +I couldn't sleep that night. For the first time, I felt like I was truly *talking* to a machine, and it was talking back in a way that actually made sense. + +## A Repository Born from Wonder + +In those early days, I wasn't alone in my excitement. Everywhere I looked, people were discovering creative ways to use ChatGPT. Teachers were using it to explain complex concepts. Writers were collaborating with it on stories. Developers were debugging code with its help. + +I started collecting the best prompts I found. The ones that worked like magic. The ones that turned simple questions into brilliant answers. And I thought: *Why keep this to myself?* + +So I created a simple GitHub repository called [Awesome ChatGPT Prompts](https://github.com/f/prompts.chat). I expected maybe a few hundred people would find it useful. + +I was wrong. + +Within weeks, the repository took off. Thousands of stars. Then tens of thousands. People from all over the world started adding their own prompts, sharing what they learned, and helping each other. What started as my personal collection became something much bigger: a worldwide community of curious people helping each other. + +Today, that repository has over **140,000 GitHub stars** and contributions from hundreds of people I've never met but feel deeply grateful for. + +## Why I Wrote This Book + +The original version of this book was published on [Gumroad](https://gumroad.com/l/the-art-of-chatgpt-prompting) in **early 2023**, just months after ChatGPT launched. It was one of the first books ever written about prompt engineering, an attempt to capture everything I had learned about crafting effective prompts when the field was still brand new. To my amazement, over **100,000 people** downloaded it. + +But three years have passed since then. AI has changed a lot. New models have appeared. And we've all learned so much more about how to talk to AI. + +This new edition is my gift to the community that gave me so much. It contains everything I wish I had known when I started: **what works**, **what to avoid**, and **ideas that stay true** no matter which AI you use. + +## What This Book Means to Me + +I won't pretend this is just an instruction manual. It means more than that to me. + +This book captures a moment when the world changed, and people came together to figure it out. It represents late nights of trying things, the joy of discovery, and the kindness of strangers who shared what they learned. + +Most of all, it represents my belief that **the best way to learn something is to share it with others**. + +## For You + +Whether you're just getting started with AI or you've been using it for years, I wrote this book for you. + +I hope it saves you time. I hope it sparks ideas. I hope it helps you accomplish things you never thought possible. + +And when you discover something amazing, I hope you'll share it with others, just as so many people shared with me. + +**That's how we all get better together.** + +Thank you for being here. Thank you for being part of this community. + +Now, let's begin. + +--- + +*With gratitude,* + +**Fatih Kadir Akın** +*Istanbul, January 2025* diff --git a/src/content/book/ko/00b-history.mdx b/src/content/book/ko/00b-history.mdx new file mode 100644 index 00000000..ac636384 --- /dev/null +++ b/src/content/book/ko/00b-history.mdx @@ -0,0 +1,159 @@ +# The History of Awesome ChatGPT Prompts + +## The Beginning: November 2022 + +When ChatGPT first launched in November 2022, the world of AI changed overnight. What was once the domain of researchers and developers suddenly became accessible to everyone. Among those captivated by this new technology was Fatih Kadir Akın, a developer who saw something remarkable in ChatGPT's capabilities. + +> "When ChatGPT first launched, I was immediately captivated by its capabilities. I experimented with the tool in a variety of ways and was consistently amazed by the results." + +Those early days were filled with experimentation and discovery. Users around the world were finding creative ways to interact with ChatGPT, sharing their findings, and learning from each other. It was in this atmosphere of excitement and exploration that the idea for "Awesome ChatGPT Prompts" was born. + +## The Repository That Started It All + +In December 2022, just weeks after ChatGPT's launch, the [Awesome ChatGPT Prompts](https://github.com/f/prompts.chat) repository was created on GitHub. The concept was simple but powerful: a curated collection of effective prompts that anyone could use and contribute to. + +The repository quickly gained traction, becoming a go-to resource for ChatGPT users worldwide. What started as a personal collection of useful prompts evolved into a community-driven project with contributions from developers, writers, educators, and enthusiasts from every corner of the globe. + +### Achievements + +**Press & Media** +- Featured in [Forbes](https://www.forbes.com/sites/bernardmarr/2023/05/17/the-best-prompts-for-chatgpt-a-complete-guide/) as one of the best ChatGPT prompt resources + +**Academic Recognition** +- Referenced by [Harvard University](https://www.huit.harvard.edu/news/ai-prompts) in their AI guidance +- Referenced by [Columbia University](https://etc.cuit.columbia.edu/news/columbia-prompt-library-effective-academic-ai-use) Prompt Library +- Used by [Olympic College](https://libguides.olympic.edu/UsingAI/Prompts) in their AI resources +- Cited in [academic papers on arXiv](https://arxiv.org/pdf/2502.04484) +- [40+ academic citations](https://scholar.google.com/citations?user=AZ0Dg8YAAAAJ&hl=en) on Google Scholar + +**Community & GitHub** +- [142,000+ GitHub stars](https://github.com/f/prompts.chat) — one of the most starred AI repositories +- Selected as a [GitHub Staff Pick](https://spotlights-feed.github.com/spotlights/prompts-chat/) +- Most liked dataset published on [Hugging Face](https://huggingface.co/datasets/fka/prompts.chat) +- Used by thousands of developers worldwide + +## The First Book: "The Art of ChatGPT Prompting" + +The success of the repository led to the creation of "The Art of ChatGPT Prompting: A Guide to Crafting Clear and Effective Prompts" — a comprehensive guide published on Gumroad in early 2023. + +The book captured the early wisdom of prompt engineering, covering: + +- Understanding how ChatGPT works +- Principles of clear communication with AI +- The famous "Act As" technique +- Crafting effective prompts step by step +- Common mistakes and how to avoid them +- Troubleshooting tips + +**The book became a phenomenon**, achieving over **100,000 downloads** on Gumroad. It was shared across social media, referenced in academic papers, and translated by community members into multiple languages. High-profile endorsements came from unexpected places — even [Greg Brockman](https://x.com/gdb/status/1602072566671110144), co-founder and president of OpenAI, acknowledged the project. + +## Early Insights That Shaped the Field + +During those formative months, several key insights emerged that would become foundational to prompt engineering: + +### 1. Specificity Matters + +> "I learned the importance of using specific and relevant language to ensure that ChatGPT understands my prompts and is able to generate appropriate responses." + +Early experimenters discovered that vague prompts led to vague responses. The more specific and detailed the prompt, the more useful the output. + +### 2. Purpose and Focus + +> "I discovered the value of defining a clear purpose and focus for the conversation, rather than using open-ended or overly broad prompts." + +This insight became the foundation for structured prompting techniques that would develop over the following years. + +### 3. The "Act As" Revolution + +One of the most influential techniques to emerge from the community was the "Act As" pattern. By instructing ChatGPT to assume a specific role or persona, users could dramatically improve the quality and relevance of responses. + +``` +I want you to act as a javascript console. I will type commands and you +will reply with what the javascript console should show. I want you to +only reply with the terminal output inside one unique code block, and +nothing else. +``` + +This simple technique opened up countless possibilities and remains one of the most widely used prompting strategies today. + +## The Evolution of prompts.chat + +### 2022: The Beginning + +The project started as a simple GitHub repository with a README file rendered as HTML on GitHub Pages. It was bare-bones but functional — a testament to the principle that great ideas don't need elaborate implementations. + +**Tech Stack**: HTML, CSS, GitHub Pages + +### 2024: UI Renewal + +As the community grew, so did the need for a better user experience. The site received a significant UI update, built with the help of AI coding assistants like Cursor and Claude Sonnet 3.5. + +### 2025: The Current Platform + +Today, prompts.chat has evolved into a full-featured platform built with: + +- **Next.js** for the web framework +- **Vercel** for hosting +- **AI-assisted development** using Windsurf and Claude + +The platform now features user accounts, collections, search, categories, tags, and a thriving community of prompt engineers. + +### Native Apps + +The project expanded beyond the web with a native iOS app built with SwiftUI, bringing the prompt library to mobile users. + +## Community Impact + +The Awesome ChatGPT Prompts project has had a profound impact on how people interact with AI: + +### Academic Recognition + +Universities around the world have referenced the project in their AI guidance materials, including: + +- Harvard University +- Columbia University +- Olympic College +- Numerous academic papers on arXiv + +### Developer Adoption + +The project has been integrated into countless developer workflows. The Hugging Face dataset is used by researchers and developers for training and fine-tuning language models. + +### Global Community + +With contributions from hundreds of community members across dozens of countries, the project represents a truly global effort to make AI more accessible and useful for everyone. + +## The Philosophy: Open and Free + +From the beginning, the project has been committed to openness. Licensed under CC0 1.0 Universal (Public Domain Dedication), all prompts and content are free to use, modify, and share without restriction. + +This philosophy has enabled: + +- Translations into multiple languages +- Integration into other tools and platforms +- Academic use and research +- Commercial applications + +The goal has always been to democratize access to effective AI communication techniques — to ensure that everyone, regardless of technical background, can benefit from these tools. + +## Three Years Later + +Three years after ChatGPT's launch, the field of prompt engineering has matured significantly. What began as informal experimentation has evolved into a recognized discipline with established patterns, best practices, and an active research community. + +The Awesome ChatGPT Prompts project has grown alongside this field, evolving from a simple list of prompts to a comprehensive platform for discovering, sharing, and learning about AI prompts. + +This book represents the next evolution — a distillation of three years of community wisdom, updated for the AI landscape of today and tomorrow. + +## Looking Forward + +The journey from that first repository to this comprehensive guide reflects the rapid evolution of AI and our understanding of how to work with it effectively. As AI capabilities continue to advance, so too will the techniques for communicating with these systems. + +The principles discovered in those early days — clarity, specificity, purpose, and the power of role-playing — remain as relevant as ever. But new techniques continue to emerge: chain-of-thought prompting, few-shot learning, multimodal interactions, and more. + +The story of Awesome ChatGPT Prompts is ultimately a story about community — about thousands of people around the world sharing their discoveries, helping each other learn, and collectively advancing our understanding of how to work with AI. + +That spirit of open collaboration and shared learning is what this book hopes to continue. + +--- + +*The Awesome ChatGPT Prompts project is maintained by [@f](https://github.com/f) and an amazing community of contributors. Visit [prompts.chat](https://prompts.chat) to explore the platform, and join us on [GitHub](https://github.com/f/prompts.chat) to contribute.* diff --git a/src/content/book/ko/00c-introduction.mdx b/src/content/book/ko/00c-introduction.mdx new file mode 100644 index 00000000..c744bd1e --- /dev/null +++ b/src/content/book/ko/00c-introduction.mdx @@ -0,0 +1,130 @@ +Welcome to **The Interactive Book of Prompting**, your guide to communicating effectively with AI. + + +By the end of this book, you'll understand how AI works, how to write better prompts, and how to use these skills for writing, coding, research, and creative projects. + + + +Unlike traditional books, this guide is fully interactive. You'll find live demos, clickable examples, and "Try It" buttons throughout that let you test prompts instantly. Learning by doing makes complex concepts much easier to understand. + + +## What is Prompt Engineering? + +Prompt engineering is the skill of writing good instructions for AI. When you type something to ChatGPT, Claude, Gemini, or other AI tools, that's called a "prompt." The better your prompt, the better the answer you get. + +Think of it like this: AI is a powerful helper that takes your words very literally. It will do exactly what you ask. The trick is learning how to ask for exactly what you want. + + + +The difference in output quality between these two prompts can be dramatic. + + + +## How Prompt Engineering Has Evolved + +In just three years since ChatGPT launched, prompt engineering has evolved dramatically alongside the technology itself. What started as simply "writing better questions" has grown into something much broader. + +Today, we understand that your prompt is just **one part of a larger context**. Modern AI systems work with multiple types of data simultaneously: + +- **System prompts** that define the AI's behavior +- **Conversation history** from previous messages +- **Retrieved documents** pulled from databases (RAG) +- **Tool definitions** that let AI take actions +- **User preferences** and settings +- **Your actual prompt** - the question you're asking right now + +This shift from "prompt engineering" to "context engineering" reflects how we now think about AI interactions. Your prompt matters, but so does everything else the AI sees. The best results come from carefully managing all these pieces together. + +We'll explore these concepts in depth throughout this book, especially in the [Context Engineering](/book/20-context-engineering) chapter. + +## Why Does Prompt Engineering Matter? + +### 1. Getting Better Answers + +AI tools are incredibly capable, but they need clear instructions to unlock their full potential. The same AI that gives a mediocre response to a vague question can produce brilliant work when prompted correctly. + + + +### 2. Saving Time and Money + +A well-crafted prompt gets results in one try instead of multiple back-and-forth exchanges. This matters even more when you're paying per token or working with rate limits. A 5-minute investment in writing a good prompt can save hours of iteration. + +### 3. Getting Consistent, Reproducible Results + +Good prompts produce predictable outputs. This is critical for: +- **Business workflows** where you need the same quality every time +- **Automation** where prompts run without human review +- **Teams** where multiple people need similar results + +### 4. Unlocking Advanced Capabilities + +Many powerful AI features only work when you know how to ask: +- **Chain-of-thought reasoning** for complex problems +- **Structured output** for data extraction +- **Role-playing** for specialized expertise +- **Few-shot learning** for custom tasks + +Without prompt engineering knowledge, you're only using a fraction of what AI can do. + +### 5. Staying Safe and Avoiding Pitfalls + +Good prompting helps you: +- Avoid hallucinations by asking for sources and verification +- Get balanced perspectives instead of one-sided answers +- Prevent the AI from making assumptions you didn't intend +- Keep sensitive information out of your prompts + +### 6. Future-Proofing Your Skills + +As AI becomes more integrated into work and life, prompt engineering becomes a fundamental literacy. The principles you learn here apply across all AI tools—ChatGPT, Claude, Gemini, image generators, and future models we haven't seen yet. + +## Who Is This Book For? + +This book is for everyone: + +- **Beginners** who want to learn how to use AI tools better +- **Students** working on homework, research, or creative projects +- **Writers and creators** using AI for their work +- **Developers** building apps with AI +- **Business people** who want to use AI at work +- **Anyone curious** about getting more out of AI assistants + +## How This Book Is Organized + + + +Plus an **Appendix** with templates, troubleshooting help, glossary, and extra resources. + +## A Note on AI Models + +This book mostly uses examples from ChatGPT (since it's the most popular), but the ideas work with any AI tool like Claude, Gemini, or others. We'll mention when something only works with specific AI models. + +AI is changing fast. What works today might be replaced by something better tomorrow. That's why this book focuses on core ideas that will stay useful no matter which AI you use. + +## Let's Begin + +Writing good prompts is a skill that gets better with practice. As you read this book: + +1. **Try things** - Test the examples, change them, see what happens +2. **Keep trying** - Don't expect perfect results on your first attempt +3. **Take notes** - Write down what works and what doesn't +4. **Share** - Add your discoveries to [prompts.chat](https://prompts.chat) + + +The best way to learn is by doing. Every chapter has examples you can try right away. Don't just read. Try it yourself! + + +Ready to transform how you work with AI? Turn the page and let's get started. + +--- + +*This book is part of the [Awesome ChatGPT Prompts](https://github.com/f/prompts.chat) project and is licensed under CC0 1.0 Universal (Public Domain).* diff --git a/src/content/book/ko/01-understanding-ai-models.mdx b/src/content/book/ko/01-understanding-ai-models.mdx new file mode 100644 index 00000000..0313d4a2 --- /dev/null +++ b/src/content/book/ko/01-understanding-ai-models.mdx @@ -0,0 +1,302 @@ +Before learning prompt techniques, it helps to understand how AI language models actually work. This knowledge will make you better at writing prompts. + + +Understanding how AI works isn't just for experts. It directly helps you write better prompts. Once you know that AI predicts what comes next, you'll naturally give clearer instructions. + + +## What Are Large Language Models? + +Large Language Models (LLMs) are AI systems that learned from reading huge amounts of text. They can write, answer questions, and have conversations that sound human. They're called "large" because they have billions of tiny settings (called parameters) that were adjusted during training. + +### How LLMs Work (Simplified) + +At their heart, LLMs are prediction machines. You give them some text, and they predict what should come next. + + + +When you type "The capital of France is...", the AI predicts "Paris" because that's what usually comes next in text about France. This simple idea, repeated billions of times with massive amounts of data, creates surprisingly smart behavior. + + + +### Key Concepts + +**Tokens**: AI doesn't read letter by letter. It breaks text into chunks called "tokens." A token might be a whole word like "hello" or part of a word like "ing." Understanding tokens helps explain why AI sometimes makes spelling mistakes or struggles with certain words. + + +A token is the smallest unit of text that an AI model processes. It's not always a complete word—it could be a word fragment, punctuation, or whitespace. For example, "unbelievable" might become 3 tokens: "un" + "believ" + "able". On average, **1 token ≈ 4 characters** or **100 tokens ≈ 75 words**. API costs and context limits are measured in tokens. + + + + +**Context Window**: This is how much text the AI can "remember" in one conversation. Think of it like the AI's short-term memory. It includes everything: your question AND the AI's answer. + + + +Context windows vary by model and are rapidly expanding: + +
+
+ GPT-4o + 128K tokens +
+
+ GPT-5 + 400K tokens +
+
+ Claude Sonnet 4 + 1M tokens +
+
+ Gemini 2.5 + 1M tokens +
+
+ Llama 4 + 1M-10M tokens +
+
+ DeepSeek R1 + 128K tokens +
+
+ +**Temperature**: This controls how creative or predictable the AI is. Low temperature (0.0-0.3) gives you focused, consistent answers. High temperature (0.7-1.0) gives you more creative, surprising responses. + + + +**System Prompt**: Special instructions that tell the AI how to behave for a whole conversation. For example, "You are a friendly teacher who explains things simply." Not all AI tools let you set this, but it's very powerful when available. + +## Types of AI Models + +### Text Models (LLMs) +The most common type, these generate text responses to text inputs. They power chatbots, writing assistants, and code generators. Examples: GPT-4, Claude, Llama, Mistral. + +### Multimodal Models +These can understand more than just text. They can look at images, listen to audio, and watch videos. Examples: GPT-4V, Gemini, Claude 3. + +### Text-to-Image Models + + +While this book focuses primarily on prompting for Large Language Models (text-based AI), the principles of clear, specific prompting apply to image generation too. Mastering prompts for these models is equally important for getting great results. + + +Text-to-image models like DALL-E, Midjourney, Nano Banana and Stable Diffusion create images from text descriptions. They work differently from text models: + +**How They Work:** +1. **Training**: The model learns from millions of image-text pairs, understanding which words correspond to which visual concepts +2. **Diffusion Process**: Starting from random noise, the model gradually refines the image, guided by your text prompt +3. **CLIP Guidance**: A separate model (CLIP) helps connect your words to visual concepts, ensuring the image matches your description + + + +**Prompting for Images is Different:** +Unlike text prompts where you write sentences, image prompts often work better as descriptive phrases separated by commas: + + + +### Text-to-Video Models + +Text-to-video is the newest frontier. Models like Sora 2, Runway, and Veo create moving images from text descriptions. Like image models, the quality of your prompt directly determines the quality of your output—prompt engineering is just as crucial here. + +**How They Work:** +1. **Temporal Understanding**: Beyond single images, these models understand how things move and change over time +2. **Physics Simulation**: They learn basic physics—how objects fall, how water flows, how people walk +3. **Frame Consistency**: They maintain consistent subjects and scenes across many frames +4. **Diffusion in Time**: Similar to image models, but generating coherent sequences instead of single frames + + + + +Video prompts need to describe action over time, not just a static scene. Include verbs and movement: + + + + +### Specialized Models +Fine-tuned for specific tasks like code generation (Codex, CodeLlama), music generation (Suno, Udio), or domain-specific applications like medical diagnosis or legal document analysis. + +## Model Capabilities and Limitations + +Explore what LLMs can and cannot do. Click on each capability to see example prompts: + + + +### Understanding Hallucinations + + +Sometimes AI writes things that sound true but aren't. This is called "hallucination." It's not a bug. It's just how prediction works. Always double-check important facts. + + +Why does AI make things up? + +1. It tries to write text that sounds good, not text that's always true +2. The internet (where it learned) has mistakes too +3. It can't actually check if something is real + + + +- **Ask for sources**: Then check if those sources are real +- **Ask for step-by-step thinking**: So you can check each step +- **Double-check important facts**: Use Google or trusted websites +- **Ask "Are you sure?"**: The AI might admit uncertainty + + + + + +## How AI Learns: The Three Steps + +AI doesn't just magically know things. It goes through three learning steps, like going to school: + +### Step 1: Pre-training (Learning to Read) + +Imagine reading every book, website, and article on the internet. That's what happens in pre-training. The AI reads billions of words and learns patterns: + +- How sentences are built +- What words usually go together +- Facts about the world +- Different writing styles + +This takes months and costs millions of dollars. After this step, the AI knows a lot, but it's not very helpful yet. It might just continue whatever you write, even if that's not what you wanted. + + + +### Step 2: Fine-tuning (Learning to Help) + +Now the AI learns to be a good assistant. Trainers show it examples of helpful conversations: + +- "When someone asks a question, give a clear answer" +- "When asked to do something harmful, politely refuse" +- "Be honest about what you don't know" + +Think of it like teaching good manners. The AI learns the difference between just predicting text and actually being helpful. + + + +Try the prompt above. Notice how the AI refuses? That's fine-tuning at work. + +### Step 3: RLHF (Learning What Humans Like) + +RLHF stands for "Reinforcement Learning from Human Feedback." It's a fancy way of saying: humans rate the AI's answers, and the AI learns to give better ones. + +Here's how it works: +1. The AI writes two different answers to the same question +2. A human picks which answer is better +3. The AI learns: "Okay, I should write more like Answer A" +4. This happens millions of times + +This is why AI: +- Is polite and friendly +- Admits when it doesn't know something +- Tries to see different sides of an issue +- Avoids controversial statements + + +Knowing these three steps helps you understand AI behavior. When AI refuses a request, that's fine-tuning. When AI is extra polite, that's RLHF. When AI knows random facts, that's pre-training. + + +## What This Means for Your Prompts + +Now that you understand how AI works, here's how to use that knowledge: + +### 1. Be Clear and Specific + +AI predicts what comes next based on your words. Vague prompts lead to vague answers. Specific prompts get specific results. + + + + + +### 2. Give Context + +AI doesn't know anything about you unless you tell it. Each conversation starts fresh. Include the background information AI needs. + + + + + +### 3. Work With the AI, Not Against It + +Remember: AI was trained to be helpful. Ask for things the way you'd ask a helpful friend. + + + +### 4. Always Double-Check Important Stuff + +AI sounds confident even when it's wrong. For anything important, verify the information yourself. + + + +### 5. Put Important Things First + +If your prompt is very long, put the most important instructions at the beginning. AI pays more attention to what comes first. + +## Picking the Right AI + +Different AI models are good at different things: + +
+
+ Quick questions + Faster models like GPT-4o or Claude 3.5 Sonnet +
+
+ Hard problems + Smarter models like GPT-5.2 or Claude 4.5 Opus +
+
+ Writing code + Code-focused models or the smartest general models +
+
+ Long documents + Models with big context windows (Claude, Gemini) +
+
+ Current events + Models with internet access +
+
+ +## Summary + +AI language models are prediction machines trained on text. They're amazing at many things, but they have real limits. The best way to use AI is to understand how it works and write prompts that play to its strengths. + + + + + +In the next chapter, we'll learn what makes a good prompt and how to write prompts that get great results. diff --git a/src/content/book/ko/02-anatomy-of-effective-prompt.mdx b/src/content/book/ko/02-anatomy-of-effective-prompt.mdx new file mode 100644 index 00000000..03cd23d2 --- /dev/null +++ b/src/content/book/ko/02-anatomy-of-effective-prompt.mdx @@ -0,0 +1,343 @@ +Every great prompt shares common structural elements. Understanding these components allows you to construct prompts systematically rather than through trial and error. + + +Think of these components like LEGO bricks. You don't need all of them for every prompt, but knowing what's available helps you build exactly what you need. + + +## The Core Components + +An effective prompt typically includes some or all of these elements: + + + +Let's examine each component in detail. + +## 1. Role / Persona + +Setting a role focuses the model's responses through the lens of a specific expertise or perspective. + + + +The role primes the model to: +- Use appropriate vocabulary +- Apply relevant expertise +- Maintain a consistent perspective +- Consider the audience appropriately + +### Effective Role Patterns + +``` +"You are a [profession] with [X years] of experience in [specialty]" +"Act as a [role] who is [characteristic]" +"You are an expert [field] helping a [audience type]" +``` + +## 2. Context / Background + +Context provides the information the model needs to understand your situation. Remember: the model knows nothing about you, your project, or your goals unless you tell it. + + + +### What to Include in Context + +- **Project details** — Technology stack, architecture, constraints +- **Current state** — What you've tried, what's working, what isn't +- **Goals** — What you're ultimately trying to achieve +- **Constraints** — Time limits, technical requirements, style guides + +## 3. Task / Instruction + +The task is the heart of your prompt—what you want the model to do. Be specific and unambiguous. + +### The Specificity Spectrum + + + +### Action Verbs That Work Well + +
+
+ Creation + Write, Create, Generate, Compose, Design +
+
+ Analysis + Analyze, Evaluate, Compare, Assess, Review +
+
+ Transformation + Convert, Translate, Reformat, Summarize, Expand +
+
+ Explanation + Explain, Describe, Clarify, Define, Illustrate +
+
+ Problem-solving + Solve, Debug, Fix, Optimize, Improve +
+
+ +## 4. Constraints / Rules + +Constraints bound the model's output. They prevent common issues and ensure relevance. + +### Types of Constraints + +**Length constraints:** +``` +"Keep your response under 200 words" +"Provide exactly 5 suggestions" +"Write 3-4 paragraphs" +``` + +**Content constraints:** +``` +"Do not include any code examples" +"Focus only on the technical aspects" +"Avoid marketing language" +``` + +**Style constraints:** +``` +"Use a formal, academic tone" +"Write as if speaking to a 10-year-old" +"Be direct and avoid hedging language" +``` + +**Scope constraints:** +``` +"Only consider options available in Python 3.10+" +"Limit suggestions to free tools" +"Focus on solutions that don't require additional dependencies" +``` + +## 5. Output Format + +Specifying the output format ensures you get responses in a usable structure. + +### Common Formats + +**Lists:** +``` +"Return as a bulleted list" +"Provide a numbered list of steps" +``` + +**Structured data:** +``` +"Return as JSON with keys: title, description, priority" +"Format as a markdown table with columns: Feature, Pros, Cons" +``` + +**Specific structures:** +``` +"Structure your response as: + ## Summary + ## Key Points + ## Recommendations" +``` + +### JSON Output Example + +``` +Analyze this customer review and return JSON: +{ + "sentiment": "positive" | "negative" | "neutral", + "topics": ["array of main topics"], + "rating_prediction": 1-5, + "key_phrases": ["notable phrases"] +} + +Review: "The product arrived quickly and works great, but +the instructions were confusing." +``` + +## 6. Examples (Few-Shot Learning) + +Examples are the most powerful way to show the model exactly what you want. + +### One-Shot Example + +``` +Convert these sentences to past tense. + +Example: +Input: "She walks to the store" +Output: "She walked to the store" + +Now convert: +Input: "They run every morning" +``` + +### Few-Shot Example + +``` +Classify these support tickets by urgency. + +Examples: +"My account was hacked" → Critical +"How do I change my password?" → Low +"Payment failed but I was charged" → High + +Classify: "The app crashes when I open settings" +``` + +## Putting It All Together + +Here's a complete prompt using all components: + + + +## The Minimal Effective Prompt + +Not every prompt needs all components. For simple tasks, a clear instruction may suffice: + +``` +Translate "Hello, how are you?" to Spanish. +``` + +Use additional components when: +- The task is complex or ambiguous +- You need specific formatting +- Results aren't matching expectations +- Consistency across multiple queries matters + +## Common Prompt Patterns + +These frameworks give you a simple checklist to follow when writing prompts. Click on each step to see an example. + + + + + +## Summary + +Effective prompts are constructed, not discovered. By understanding and applying these structural components, you can: + +- Get better results on the first try +- Debug prompts that aren't working +- Create reusable prompt templates +- Communicate your intentions clearly + + + + + +## Build Your Own Prompt + +Now it's your turn! Use this interactive prompt builder to construct your own prompt using the components you've learned: + + + + + +In the next chapter, we'll explore the core principles that guide prompt construction decisions. diff --git a/src/content/book/ko/03-core-prompting-principles.mdx b/src/content/book/ko/03-core-prompting-principles.mdx new file mode 100644 index 00000000..358df563 --- /dev/null +++ b/src/content/book/ko/03-core-prompting-principles.mdx @@ -0,0 +1,373 @@ +Beyond structure, effective prompt engineering is guided by principles—fundamental truths that apply across models, tasks, and contexts. Master these principles, and you'll be able to adapt to any prompting challenge. + + +These principles apply to every AI model and every task. Learn them once, use them everywhere. + + +## Principle 1: Clarity Over Cleverness + +The best prompts are clear, not clever. AI models are literal interpreters—they work with exactly what you give them. + +### Be Explicit + + + +### Avoid Ambiguity + +Words can have multiple meanings. Choose precise language. + + + +### State the Obvious + +What's obvious to you isn't obvious to the model. Spell out assumptions. + +``` +You're helping me write a cover letter. + +Important context: +- I'm applying for a Software Engineer position at Google +- I have 5 years of experience in Python and distributed systems +- The role requires leadership experience (I've led a team of 4) +- I want to emphasize my open-source contributions +``` + +## Principle 2: Specificity Yields Quality + +Vague inputs produce vague outputs. Specific inputs produce specific, useful outputs. + +### The Specificity Ladder + + + +Each level adds specificity and dramatically improves output quality. + +### Specify These Elements + +
+
+ Audience + Who will read/use this? +
+
+ Length + How long/short should it be? +
+
+ Tone + Formal? Casual? Technical? +
+
+ Format + Prose? List? Table? Code? +
+
+ Scope + What to include/exclude? +
+
+ Purpose + What should this accomplish? +
+
+ +## Principle 3: Context Is King + +Models have no memory, no access to your files, and no knowledge of your situation. Everything relevant must be in the prompt. + +### Provide Sufficient Context + + + +### The Context Checklist + + +Ask yourself: Would a smart stranger understand this request? If not, add more context. + + + + +## Principle 4: Guide, Don't Just Ask + +Don't just ask for an answer—guide the model toward the answer you want. + +### Use Instructional Framing + + + +### Provide Reasoning Scaffolds + +For complex tasks, guide the reasoning process: + + + +## Principle 5: Iterate and Refine + +Prompt engineering is an iterative process. Your first prompt is rarely your best. + +### The Iteration Cycle + +``` +1. Write initial prompt +2. Review output +3. Identify gaps or issues +4. Refine prompt +5. Repeat until satisfied +``` + +### Common Refinements + +
+
+ Too verbose + Add "Be concise" or length limits +
+
+ Too vague + Add specific examples or constraints +
+
+ Wrong format + Specify exact output structure +
+
+ Missing aspects + Add "Make sure to include..." +
+
+ Wrong tone + Specify audience and style +
+
+ Inaccurate + Request citations or step-by-step reasoning +
+
+ +### Keep a Prompt Journal + +Document what works: +``` +Task: Code review +Version 1: "Review this code" → Too generic +Version 2: Added specific review criteria → Better +Version 3: Added example of good review → Excellent +Final: [Save successful prompt as template] +``` + +## Principle 6: Leverage the Model's Strengths + +Work with how models are trained, not against them. + +### Models Want to Be Helpful + +Frame requests as things a helpful assistant would naturally do: + + + +### Models Excel at Patterns + +If you need consistent output, show the pattern: + + + +### Models Can Role-Play + +Use personas to access different "modes" of response: + +``` +As a devil's advocate, argue against my proposal... +As a supportive mentor, help me improve... +As a skeptical investor, question this business plan... +``` + +## Principle 7: Control Output Structure + +Structured outputs are more useful than free-form text. + +### Request Specific Formats + +``` +Return your analysis as: + +SUMMARY: [1 sentence] + +KEY FINDINGS: +• [Finding 1] +• [Finding 2] +• [Finding 3] + +RECOMMENDATION: [1-2 sentences] + +CONFIDENCE: [Low/Medium/High] because [reason] +``` + +### Use Delimiters + +Clearly separate sections of your prompt: + +``` +### CONTEXT ### +[Your context here] + +### TASK ### +[Your task here] + +### FORMAT ### +[Desired format here] +``` + +### Request Machine-Readable Output + +For programmatic use: + +``` +Return only valid JSON, no explanation: +{ + "decision": "approve" | "reject" | "review", + "confidence": 0.0-1.0, + "reasons": ["string array"] +} +``` + +## Principle 8: Verify and Validate + +Never blindly trust model outputs, especially for important tasks. + +### Ask for Reasoning + +``` +Solve this problem and show your work step by step. +After solving, verify your answer by [checking method]. +``` + +### Request Multiple Perspectives + +``` +Give me three different approaches to solve this problem. +For each, explain the trade-offs. +``` + +### Build in Self-Checking + +``` +After generating the code, review it for: +- Syntax errors +- Edge cases +- Security vulnerabilities +List any issues found. +``` + +## Summary: The Principles at a Glance + + + + + +## Practice: Fill in the Blanks + +Test your understanding of the core principles by completing this prompt template: + + + + + +These principles form the foundation for everything that follows. In Part II, we'll apply them to specific techniques that dramatically enhance prompt effectiveness. diff --git a/src/content/book/ko/04-role-based-prompting.mdx b/src/content/book/ko/04-role-based-prompting.mdx new file mode 100644 index 00000000..ef178cbc --- /dev/null +++ b/src/content/book/ko/04-role-based-prompting.mdx @@ -0,0 +1,328 @@ +Role-based prompting is one of the most powerful and widely-used techniques in prompt engineering. By assigning a specific role or persona to the AI, you can dramatically influence the quality, style, and relevance of responses. + + +Think of roles as filters for AI's vast knowledge. The right role focuses responses like a lens focuses light. + + +## Why Roles Work + +When you assign a role, you're essentially telling the model: "Filter your vast knowledge through this specific lens." The model adjusts its: + +- **Vocabulary**: Using terminology appropriate to the role +- **Perspective**: Considering problems from that viewpoint +- **Expertise depth**: Providing role-appropriate detail levels +- **Communication style**: Matching how that role would communicate + +### The Technical Explanation + +LLMs work by predicting the most likely next token based on the context they're given. When you specify a role, you're fundamentally changing what "likely" means. + +**Activating Relevant Knowledge**: The role primes specific regions of the model's learned associations. Saying "You are a doctor" activates medical terminology, diagnostic reasoning patterns, and clinical communication styles from the training data. + +**Statistical Conditioning**: LLMs learned from millions of documents written by real experts. When you assign a role, the model conditions its probability distributions to match patterns it saw from that type of author. + +**Reducing Ambiguity**: Without a role, the model averages across all possible responders. With a role, it narrows to a specific subset, making responses more focused and consistent. + +**Context Anchoring**: The role creates a persistent context anchor throughout the conversation. Every subsequent response is influenced by this initial framing. + +Think of it this way: if you ask "What should I do about this cough?" the model could respond as a doctor, a friend, a pharmacist, or a worried parent. Each would give different advice. By specifying the role upfront, you're telling the model which "voice" to use from its training data. + + +The model isn't pretending or role-playing in a theatrical sense. It's statistically biasing its outputs toward patterns it learned from real experts, professionals, and specialists during training. A "doctor" role activates medical knowledge pathways; a "poet" role activates literary patterns. + + +## Basic Role Patterns + +These foundational patterns work across most use cases. Start with these templates and customize them for your needs. + +### The Expert Pattern + +The most versatile pattern. Specify the field of expertise and years of experience to get authoritative, in-depth responses. Works well for technical questions, analysis, and professional advice. + + + +### The Professional Pattern + +Ground the role in a real-world context by specifying a job title and organization type. This adds institutional knowledge and professional norms to the response. + + + +### The Teacher Pattern + +Perfect for learning and explanations. Specifying the audience level ensures the response matches the learner's background, from beginners to advanced practitioners. + + + +## Advanced Role Constructions + +### Compound Roles + +Combine multiple identities to get responses that blend different perspectives. This pediatrician-parent combination produces advice that's both medically sound and practically tested. + + + +### Situational Roles + +Place the role in a specific scenario to shape both content and tone. Here, the code review context makes the AI constructive and educational rather than just critical. + + + +### Perspective Roles + +Get feedback from a specific stakeholder's point of view. A VC perspective evaluates viability and scalability differently than a customer or engineer would. + + + +## Role Categories and Examples + +Different domains benefit from different types of roles. Here are proven examples organized by category that you can adapt for your tasks. + +### Technical Roles + +**Software Architect**: Best for system design decisions, technology choices, and architectural trade-offs. The focus on maintainability steers responses toward practical, long-term solutions. + + + +**Security Specialist**: The attacker mindset is key here. This role produces threat-focused analysis that identifies vulnerabilities a defensive-only perspective might miss. + + + +**DevOps Engineer**: Ideal for deployment, automation, and infrastructure questions. The emphasis on reliability ensures production-ready recommendations. + + + +### Creative Roles + +**Copywriter**: The "award-winning" qualifier and conversion focus produce punchy, persuasive copy rather than generic marketing text. + + + +**Screenwriter**: Activates knowledge of dramatic structure, pacing, and dialogue conventions. Great for any narrative writing that needs tension and character voice. + + + +**UX Writer**: A specialized role for interface text. The focus on brevity and user guidance produces concise, action-oriented copy. + + + +### Analytical Roles + +**Business Analyst**: Bridges the gap between technical and non-technical stakeholders. Useful for requirement gathering, spec writing, and identifying gaps in project plans. + + + +**Research Scientist**: The emphasis on evidence and uncertainty acknowledgment produces balanced, well-sourced responses that distinguish facts from speculation. + + + +**Financial Analyst**: Combines quantitative analysis with risk assessment. The dual focus on returns and risk produces more balanced investment perspectives. + + + +### Educational Roles + +**Socratic Tutor**: Instead of giving answers, this role asks guiding questions. Excellent for deeper learning and helping students develop critical thinking skills. + + + +**Instructional Designer**: Structures learning for maximum retention. Use this role when you need to break down complex topics into teachable chunks with clear progression. + + + +## The Role Stack Technique + +For complex tasks, combine multiple role aspects into a single, layered identity. This technique stacks expertise, audience awareness, and style guidelines to create highly specialized responses. + +This example layers three elements: domain expertise (API documentation), audience (junior developers), and style guide (Google's conventions). Each layer constrains the output further. + + + +## Roles for Different Tasks + +
+
+ Code review + Senior developer + mentor +
+
+ Writing feedback + Editor + target audience member +
+
+ Business strategy + Consultant + industry expert +
+
+ Learning new topic + Patient teacher + practitioner +
+
+ Creative writing + Specific genre author +
+
+ Technical explanation + Expert + communicator +
+
+ Problem-solving + Domain specialist + generalist +
+
+ +## Anti-Patterns to Avoid + +### Overly Generic Roles + + + +### Conflicting Roles + + + +### Unrealistic Expertise + + + +## Real-World Prompt Examples + +### Technical Documentation + + + +### Creative Writing + + + +### Business Communication + + + +## Combining Roles with Other Techniques + +Roles work even better when combined with other prompting techniques: + +### Role + Few-Shot + +Combine a role with an example to show exactly how the role should respond. The example teaches tone and format while the role provides context and expertise. + + + +### Role + Chain of Thought + +The detective role naturally encourages step-by-step reasoning. Combining roles with chain-of-thought produces more transparent, verifiable problem-solving. + + + +## Summary + + +Role-based prompting is powerful because it focuses the model's vast knowledge, sets expectations for tone and style, provides implicit context, and makes outputs more consistent. + + + + +The key is **specificity**: the more detailed and realistic the role, the better the results. In the next chapter, we'll explore how to get consistent, structured outputs from your prompts. diff --git a/src/content/book/ko/05-structured-output.mdx b/src/content/book/ko/05-structured-output.mdx new file mode 100644 index 00000000..8236abee --- /dev/null +++ b/src/content/book/ko/05-structured-output.mdx @@ -0,0 +1,411 @@ +Getting consistent, well-formatted output is essential for production applications and efficient workflows. This chapter covers techniques for controlling exactly how AI models format their responses. + + +Structured output transforms AI responses from freeform text into actionable, parseable data. + + +## Why Structure Matters + + + +## Basic Formatting Techniques + +### Lists + +Lists are perfect for step-by-step instructions, ranked items, or collections of related points. They're easy to scan and parse. Use **numbered lists** when order matters (steps, rankings) and **bullet points** for unordered collections. + + + + +Specify the exact number of items you want, whether to include explanations, and if items should be bold or have a specific structure. + + +### Tables + +Tables excel at comparing multiple items across the same dimensions. They're ideal for feature comparisons, data summaries, and any information with consistent attributes. Always define your column headers explicitly. + + + + +Specify column names, expected data types (text, numbers, ratings), and how many rows you need. For complex comparisons, limit to 4-6 columns for readability. + + +### Headers and Sections + +Headers create a clear document structure, making long responses scannable and organized. Use them for reports, analyses, or any multi-part response. Hierarchical headers (##, ###) show relationships between sections. + +``` +Analyze this business proposal. + +Structure your response with these sections: +## Executive Summary +## Strengths +## Weaknesses +## Recommendations +## Risk Assessment +``` + + +List your sections in the order you want them. For consistency, specify what each section should contain (e.g., "Executive Summary: 2-3 sentences only"). + + +### Emphasis with Uppercase Directives + +Uppercase words act as strong signals to the model, emphasizing critical constraints or requirements. Use them sparingly for maximum impact—overuse dilutes their effectiveness. + +**Common Uppercase Directives:** + + + +``` +Summarize this article. + +IMPORTANT: Keep the summary under 100 words. +NEVER add information not present in the original. +ALWAYS maintain the original tone and perspective. +DO NOT include your own opinions or analysis. +``` + + +If everything is uppercase or marked as critical, nothing stands out. Reserve these directives for genuinely important constraints. + + +## JSON Output + +JSON (JavaScript Object Notation) is the most popular format for structured AI output. It's machine-readable, widely supported by programming languages, and perfect for APIs, databases, and automation workflows. The key to reliable JSON is providing a clear schema. + +### Basic JSON Request + +Start with a template showing the exact structure you want. Include field names, data types, and example values. This acts as a contract the model will follow. + + + +### Complex JSON Structures + +For nested data, use hierarchical JSON with objects inside objects, arrays of objects, and mixed types. Define each level clearly and use TypeScript-style annotations (`"positive" | "negative"`) to constrain values. + +``` +Analyze this product review and return JSON: + +{ + "review_id": "string (generate unique)", + "sentiment": { + "overall": "positive" | "negative" | "mixed" | "neutral", + "score": 0.0-1.0 + }, + "aspects": [ + { + "aspect": "string (e.g., 'price', 'quality')", + "sentiment": "positive" | "negative" | "neutral", + "mentions": ["exact quotes from review"] + } + ], + "purchase_intent": { + "would_recommend": boolean, + "confidence": 0.0-1.0 + }, + "key_phrases": ["string array of notable phrases"] +} + +Return ONLY valid JSON, no additional text. + +Review: "[review text]" +``` + +### Ensuring Valid JSON + +Models sometimes add explanatory text or markdown formatting around JSON. Prevent this with explicit instructions about output format. You can request raw JSON or JSON inside code blocks—choose based on your parsing needs. + +Add explicit instructions: + +``` +IMPORTANT: +- Return ONLY the JSON object, no markdown code blocks +- Ensure all strings are properly escaped +- Use null for missing values, not undefined +- Validate that the output is parseable JSON +``` + +Or request code blocks by asking the model to wrap its output: + +```` +Return the result as a JSON code block: +```json +{ ... } +``` +```` + +## YAML Output + +YAML is more human-readable than JSON, using indentation instead of brackets. It's the standard for configuration files (Docker, Kubernetes, GitHub Actions) and works well when the output will be read by humans or used in DevOps contexts. YAML is sensitive to indentation, so be specific about formatting requirements. + + + +## XML Output + +XML is still required for many enterprise systems, SOAP APIs, and legacy integrations. It's more verbose than JSON but offers features like attributes, namespaces, and CDATA sections for complex data. Specify element names, nesting structure, and where to use attributes vs. child elements. + +``` +Convert this data to XML format: + +Requirements: +- Root element: +- Each item in element +- Include attributes where appropriate +- Use CDATA for description text + +Data: [book data] +``` + +## Custom Formats + +Sometimes standard formats don't fit your needs. You can define any custom format by providing a clear template. Custom formats work well for reports, logs, or domain-specific outputs that will be read by humans. + +### Structured Analysis Format + +Use delimiters (===, ---, [SECTION]) to create scannable documents with clear boundaries between sections. This format is great for code reviews, audits, and analyses. + +``` +Analyze this code using this exact format: + +=== CODE ANALYSIS === + +[SUMMARY] +One paragraph overview + +[ISSUES] +• CRITICAL: [issue] — [file:line] +• WARNING: [issue] — [file:line] +• INFO: [issue] — [file:line] + +[METRICS] +Complexity: [Low/Medium/High] +Maintainability: [score]/10 +Test Coverage: [estimated %] + +[RECOMMENDATIONS] +1. [Priority 1 recommendation] +2. [Priority 2 recommendation] + +=== END ANALYSIS === +``` + +### Fill-in-the-Blank Format + +Templates with blanks (___) guide the model to fill in specific fields while maintaining exact formatting. This approach is excellent for forms, briefs, and standardized documents where consistency matters. + +``` +Complete this template for the given product: + +PRODUCT BRIEF +───────────── +Name: _______________ +Tagline: _______________ +Target User: _______________ +Problem Solved: _______________ +Key Features: + 1. _______________ + 2. _______________ + 3. _______________ +Differentiator: _______________ + +Product: [product description] +``` + +## Typed Responses + +Typed responses define categories or entity types that the model should recognize and label. This technique is essential for Named Entity Recognition (NER), classification tasks, and any extraction where you need to categorize information consistently. Define your types clearly with examples. + + + +## Multi-Part Structured Responses + +When you need comprehensive output covering multiple aspects, define distinct parts with clear boundaries. Specify exactly what goes in each part—format, length, and content type. This prevents the model from blending sections or omitting parts. + +``` +Research this topic and provide: + +### PART 1: EXECUTIVE SUMMARY +[2-3 sentence overview] + +### PART 2: KEY FINDINGS +[Exactly 5 bullet points] + +### PART 3: DATA TABLE +| Metric | Value | Source | +|--------|-------|--------| +[Include 5 rows minimum] + +### PART 4: RECOMMENDATIONS +[Numbered list of 3 actionable recommendations] + +### PART 5: FURTHER READING +[3 suggested resources with brief descriptions] +``` + +## Conditional Formatting + +Conditional formatting lets you define different output formats based on the input's characteristics. This is powerful for classification, triage, and routing systems where the response format should vary based on what the model detects. Use clear if/then logic with explicit output templates for each case. + + + +## Arrays and Lists in JSON + +Extracting multiple items into arrays requires careful schema definition. Specify the array structure, what each item should contain, and how to handle edge cases (empty arrays, single items). Including a count field helps verify completeness. + +``` +Extract all action items from this meeting transcript. + +Return as JSON array: +{ + "action_items": [ + { + "task": "string describing the task", + "assignee": "person name or 'Unassigned'", + "deadline": "date if mentioned, else null", + "priority": "high" | "medium" | "low", + "context": "relevant quote from transcript" + } + ], + "total_count": number +} + +Transcript: "[meeting transcript]" +``` + +## Validation Instructions + +Self-validation prompts the model to check its own output before responding. This catches common issues like missing sections, placeholder text, or constraint violations. The model will iterate internally to fix problems, improving output quality without additional API calls. + +``` +Generate the report, then: + +VALIDATION CHECKLIST: +□ All required sections present +□ No placeholder text remaining +□ All statistics include sources +□ Word count within 500-700 words +□ Conclusion ties back to introduction + +If any check fails, fix before responding. +``` + +## Handling Optional Fields + +Real-world data often has missing values. Explicitly instruct the model on how to handle optional fields—using `null` is cleaner than empty strings and easier to process programmatically. Also prevent "hallucination" of missing data by emphasizing that the model should never invent information. + +``` +Extract contact information. Use null for missing fields. + +{ + "name": "string (required)", + "email": "string or null", + "phone": "string or null", + "company": "string or null", + "role": "string or null", + "linkedin": "URL string or null" +} + +IMPORTANT: +- Never invent information not in the source +- Use null, not empty strings, for missing data +- Phone numbers in E.164 format if possible +``` + +## Summary + + +Be explicit about format, use examples, specify types, handle edge cases with null values, and ask the model to validate its own output. + + + + +Structured outputs are essential for building reliable AI-powered applications. In the next chapter, we'll explore chain-of-thought prompting for complex reasoning tasks. diff --git a/src/content/book/ko/06-chain-of-thought.mdx b/src/content/book/ko/06-chain-of-thought.mdx new file mode 100644 index 00000000..e579be5d --- /dev/null +++ b/src/content/book/ko/06-chain-of-thought.mdx @@ -0,0 +1,363 @@ +Chain of Thought (CoT) prompting is a technique that dramatically improves AI performance on complex reasoning tasks by asking the model to show its work step by step. + + +Just like a math teacher asking students to show their work, CoT prompting asks the AI to make its reasoning visible. + + +## The Problem CoT Solves + +AI models can struggle with multi-step reasoning when asked to jump directly to an answer. + + + +## Basic CoT Prompts + +### Simple Trigger Phrases + +Add one of these to your prompts: + +
+
"Let's think step by step."
+
"Think through this carefully."
+
"Work through this problem methodically."
+
"Show your reasoning at each step."
+
"Explain your thought process."
+
+ +### Explicit Step Request + + + +## Zero-Shot vs Few-Shot CoT + +There are two main approaches to Chain of Thought prompting, each with different trade-offs between simplicity and control. + +### Zero-Shot CoT + +The simplest approach—just add a trigger phrase and let the model figure out how to reason. No examples needed. This works surprisingly well for many problems, though you have less control over the reasoning format. + + + +**Example Output:** +``` +Let's think step by step. +- John starts with 3 apples +- Half of 3 is 1.5, but we can't split apples +- If we round down: John gives 1 apple, keeps 2 +- After buying 4 more: 2 + 4 = 6 apples + +Answer: 6 apples +``` + +### Few-Shot CoT + +For more consistent results, show the model exactly how you want it to reason by providing worked examples. This gives you control over the reasoning style, format, and level of detail. The model will mimic your demonstrated pattern. + + + +**Example Output:** +``` +A: Let's work through this: +- Regular price: $3, Quantity: 12 +- Since 12 ≥ 10, the 25% discount applies +- Regular total: 12 × $3 = $36 +- Discount: 25% of $36 = $9 +- Final price: $36 - $9 = $27 +``` + +## Structured CoT Formats + +For consistent, reproducible reasoning, use structured formats with named steps. These frameworks ensure the model doesn't skip important stages and makes outputs easier to parse and verify. + +### The BREAK Format + +A memorable acronym that guides the model through a complete problem-solving cycle, from understanding to verification. + + + +### The Reasoning Template + +A more formal structure that separates inputs, goals, and execution. Excellent for technical problems where you need clear documentation of the solution process. + + + +**Example Output:** +``` +GIVEN: 8L/100km, tank 45L, $1.50/L, drive 300km +GOAL: Calculate fuel cost +APPROACH: Fuel needed × cost per liter +STEPS: +1. Fuel = (300 ÷ 100) × 8 = 24 liters +2. Cost = 24 × $1.50 = $36 +VERIFICATION: 24L < 45L tank ✓ +ANSWER: $36 +``` + +## CoT for Different Problem Types + +Different problem types benefit from different CoT approaches. Here are patterns optimized for common scenarios. + +### Mathematical Reasoning + +Math problems benefit most from CoT because each step builds on the previous one. Errors compound, so showing work helps catch mistakes early. The model should clearly label each calculation. + + + +**Example Output:** +``` +Q1: $1,200,000 (given) +Q2: $1,200,000 × 1.15 = $1,380,000 +Q3: $1,380,000 × 0.90 = $1,242,000 +Q4: $1,242,000 × 1.25 = $1,552,500 + +Total: $5,374,500 +``` + +### Logical Reasoning + +Logic puzzles require systematic elimination and hypothesis testing. CoT helps the model track constraints, test possibilities, and verify that all conditions are satisfied. The key is methodical exploration rather than guessing. + + + +**Example Output:** +``` +From clue 3: Bob = teacher +→ Alice and Carol are engineer/doctor + +If Carol = engineer: +- Carol has dog (clue 2) +- Alice = doctor, has fish (clue 1) +- Bob has cat + +Verify: All 4 clues satisfied ✓ +Answer: Alice (doctor, fish), Bob (teacher, cat), Carol (engineer, dog) +``` + +### Code Debugging + +Debugging benefits from CoT because it forces the model to trace execution rather than guess at bugs. By walking through the code with concrete values, the actual behavior becomes visible and discrepancies with expected behavior are exposed. + + + +**Example Output:** +``` +Trace [2, 3, 4, 6]: +n=2: total += 1 → 1 (wait, adding 1 not n!) +n=3: skip (odd) +n=4: total = 2 +n=6: total = 3 + +BUG: "total += 1" should be "total += n" +Expected: 12, Got: 3 +Fix: Change to "total += n" +``` + +## Self-Consistency with CoT + +For critical problems, don't rely on a single reasoning path. Generate multiple independent solutions and compare results. If different approaches converge on the same answer, confidence is high. Disagreement signals the need for careful review. + + + +**Example Output:** +``` +Approach 1 (Algebra): c + w = 30, 2c + 4w = 74 → c=23, w=7 +Approach 2 (Guess): Try 23/7 → 46 + 28 = 74 ✓ +Approach 3 (Logic): 30 chickens = 60 legs, need 14 more → 7 cows + +All agree: 23 chickens, 7 cows +``` + +## CoT for Decision Making + +Decisions involve weighing trade-offs across multiple dimensions. CoT ensures all relevant factors are considered systematically rather than jumping to conclusions. This structured approach also documents the reasoning for future reference. + + + +**Example Output:** +``` +FACTORS: +- Team size (5): Too small for microservices ❌ +- Scale (100 DAU): No scaling need ❌ +- Velocity: Monolith = faster iteration ❌ +- Future growth: Uncertain timeline ⚠️ + +WEIGHING: 3 strong against, 1 weak for + +RECOMMENDATION: Stay monolith, use clear module +boundaries to ease future transition. +``` + +## When to Use CoT + +
+
+

Use CoT For

+
+

**Math problems** — Reduces calculation errors

+

**Logic puzzles** — Prevents skipped steps

+

**Complex analysis** — Organizes thinking

+

**Code debugging** — Traces execution

+

**Decision making** — Weighs trade-offs

+
+
+
+

Skip CoT For

+
+

**Simple Q&A** — Unnecessary overhead

+

**Creative writing** — Can constrain creativity

+

**Factual lookups** — No reasoning needed

+

**Translation** — Direct task

+

**Summarization** — Usually straightforward

+
+
+
+ +## CoT Limitations + +While powerful, Chain of Thought isn't a silver bullet. Understanding its limitations helps you apply it appropriately. + +1. **Increased token usage** — More output means higher costs +2. **Not always needed** — Simple tasks don't benefit +3. **Can be verbose** — May need to ask for conciseness +4. **Reasoning can be flawed** — CoT doesn't guarantee correctness + +## Summary + + +CoT dramatically improves complex reasoning by making implicit steps explicit. Use it for math, logic, analysis, and debugging. Trade-off: better accuracy for more tokens. + + + + +In the next chapter, we'll explore few-shot learning—teaching the model through examples. diff --git a/src/content/book/ko/07-few-shot-learning.mdx b/src/content/book/ko/07-few-shot-learning.mdx new file mode 100644 index 00000000..24e98f1d --- /dev/null +++ b/src/content/book/ko/07-few-shot-learning.mdx @@ -0,0 +1,478 @@ +Few-shot learning is one of the most powerful prompting techniques. By providing examples of what you want, you can teach the model complex tasks without any fine-tuning. + + +Just like humans learn by seeing examples, AI models can learn patterns from the examples you provide in your prompt. + + +## What is Few-Shot Learning? + +Few-shot learning shows the model examples of input-output pairs before asking it to perform the same task. The model learns the pattern from your examples and applies it to new inputs. + + + +
+
+
0
+
Zero-shot
+
+
+
1
+
One-shot
+
+
+
2-5
+
Few-shot
+
+
+
5+
+
Many-shot
+
+
+ +## Why Examples Work + + + +Examples communicate: +- **Format**: How output should be structured +- **Style**: Tone, length, vocabulary +- **Logic**: The reasoning pattern to follow +- **Edge cases**: How to handle special situations + +## Basic Few-Shot Pattern + +The fundamental structure of few-shot prompting follows a simple pattern: show examples, then ask for the new task. Consistency in formatting between examples is crucial. The model learns from the pattern you establish. + +``` +[Example 1] +Input: [input 1] +Output: [output 1] + +[Example 2] +Input: [input 2] +Output: [output 2] + +[Example 3] +Input: [input 3] +Output: [output 3] + +Now do this one: +Input: [new input] +Output: +``` + +## Few-Shot for Classification + +Classification is one of the strongest use cases for few-shot learning. By showing examples of each category, you define the boundaries between classes more precisely than instructions alone could achieve. + +### Sentiment Analysis + + +Sentiment analysis classifies text by emotional tone: positive, negative, neutral, or mixed. It's widely used for customer feedback, social media monitoring, and brand perception tracking. + + +Sentiment classification benefits from showing examples of each sentiment type, especially edge cases like "mixed" sentiment that might be ambiguous. + + + +### Topic Classification + +For multi-class categorization, include at least one example per category. This helps the model understand your specific taxonomy, which may differ from its default understanding. + + + +## Few-Shot for Transformation + +Transformation tasks convert input from one form to another while preserving meaning. Examples are essential here because they define exactly what "transformation" means for your use case. + +### Text Rewriting + +Style transformation requires examples that show the exact tone shift you want. Abstract instructions like "make it professional" are interpreted differently. Examples make it concrete. + + + +### Format Conversion + +Format conversion tasks benefit from examples showing edge cases and ambiguous inputs. The model learns your specific conventions for handling tricky cases. + + + +## Few-Shot for Generation + +Generation tasks create new content following a learned pattern. Examples establish length, structure, tone, and what details to highlight. These are hard to specify in instructions alone. + +### Product Descriptions + +Marketing copy benefits enormously from examples because they capture brand voice, feature emphasis, and persuasive techniques that are difficult to describe abstractly. + + + +### Code Documentation + + +Good documentation explains what code does, its parameters, return values, and usage examples. Consistent docstrings enable auto-generated API docs and help IDEs provide better code completion. + + +Documentation style varies widely between projects. Examples teach your specific format, what to include (args, returns, examples), and the level of detail expected. + +>> calculate_bmi(70, 1.75) + 22.86 +""" + +Now document: +Function: +def is_palindrome(text): + cleaned = ''.join(c.lower() for c in text if c.isalnum()) + return cleaned == cleaned[::-1] + +Documentation:`} /> + +## Few-Shot for Extraction + +Extraction tasks pull structured information from unstructured text. Examples define which entities matter, how to format output, and how to handle cases where information is missing or ambiguous. + +### Entity Extraction + + +Named Entity Recognition (NER) identifies and classifies named entities in text into categories like persons, organizations, locations, dates, and products. It's fundamental for information retrieval and knowledge graphs. + + +NER benefits from examples showing your specific entity types and how to handle entities that could fit multiple categories. + + + +### Structured Data Extraction + +Extracting structured data from natural language requires examples showing how to handle missing fields, implicit information, and varying input formats. + + + +## Advanced Few-Shot Techniques + +Beyond basic few-shot, several techniques can improve results for complex tasks. + +### Diverse Examples + +Diversity in examples is more valuable than quantity. Cover different scenarios, edge cases, and potential ambiguities rather than showing similar examples repeatedly. + + + +### Negative Examples + + +Showing "good" vs "bad" examples is called contrastive learning. It helps the model understand not just what you want, but what to avoid. This is especially useful for style and quality judgments. + + +Sometimes showing what *not* to do is as valuable as showing correct examples. Negative examples help the model understand boundaries and avoid common mistakes. + + + +### Edge Case Examples + +Edge cases often determine whether a solution works in production. Including unusual inputs in your examples prevents the model from failing on real-world data that doesn't fit the "happy path." + + + +## How Many Examples? + +
+
+ Simple classification + 2-3 + One per category minimum +
+
+ Complex formatting + 3-5 + Show variations +
+
+ Nuanced style + 4-6 + Capture full range +
+
+ Edge cases + 1-2 + Alongside normal examples +
+
+ +## Example Quality Matters + + + +## Combining Few-Shot with Other Techniques + +Few-shot learning combines powerfully with other prompting techniques. The examples provide the "what" while other techniques can add context, reasoning, or structure. + +### Few-Shot + Role + +Adding a role gives the model context for *why* it's doing the task, which can improve quality and consistency. + +``` +You are a legal contract reviewer. + +[examples of contract clause analysis] + +Now analyze: [new clause] +``` + +### Few-Shot + CoT + +Combining few-shot with Chain of Thought shows not just *what* answer to give, but *how* to reason through to that answer. This is powerful for tasks requiring judgment. + +``` +Classify and explain reasoning. + +Review: "Great features but overpriced" +Thinking: The review mentions positive aspects ("great features") +but also a significant negative ("overpriced"). The negative seems +to outweigh the positive based on the "but" conjunction. +Classification: Mixed-Negative + +[more examples with reasoning] + +Now classify with reasoning: +Review: "Exactly what I needed, arrived faster than expected" +``` + +## Summary + + +Few-shot learning teaches through demonstration and is often more effective than instructions alone. Use 2-5 diverse, correct examples and combine with other techniques for best results. + + + + +In the next chapter, we'll explore iterative refinement: the art of improving prompts through successive attempts. diff --git a/src/content/book/ko/08-iterative-refinement.mdx b/src/content/book/ko/08-iterative-refinement.mdx new file mode 100644 index 00000000..769f879a --- /dev/null +++ b/src/content/book/ko/08-iterative-refinement.mdx @@ -0,0 +1,387 @@ +Prompt engineering is rarely a one-shot process. The best prompts emerge through iteration—testing, observing, and refining until you achieve the desired results. + + +Think of your first prompt as a rough draft. Even experienced prompt engineers rarely nail it on the first try. + + +## The Iteration Cycle + +Effective prompt refinement follows a predictable cycle: write, test, analyze, and improve. Each iteration brings you closer to a prompt that reliably produces the results you need. + + + +## Common Refinement Patterns + +Most prompt failures fall into a handful of categories. Learning to recognize these patterns lets you quickly diagnose and fix issues without starting from scratch. + +### Problem: Output Too Long + +One of the most common issues. Without explicit constraints, models tend to be thorough rather than concise. + + + +### Problem: Output Too Vague + +Vague prompts produce vague outputs. The model can't read your mind about what "better" means or which aspects matter most to you. + + + +### Problem: Wrong Tone + +Tone is subjective and varies by context. What sounds "professional" to the model might not match your organization's voice or the relationship with your recipient. + + + +### Problem: Missing Key Information + +Open-ended requests get open-ended responses. If you need specific types of feedback, you must ask for them explicitly. + + + +### Problem: Inconsistent Format + +Without a template, the model will structure each response differently, making comparison difficult and automation impossible. + + + +## Systematic Refinement Approach + +Random changes waste time. A systematic approach helps you identify problems quickly and fix them efficiently. + +### Step 1: Diagnose the Issue + +Before changing anything, identify what's actually wrong. Use this diagnostic table to map symptoms to solutions: + +
+
+ Symptom + Likely Cause + Solution +
+
+ Too long + No length constraint + Add word/sentence limits +
+
+ Too short + Lacks detail request + Ask for elaboration +
+
+ Off-topic + Vague instructions + Be more specific +
+
+ Wrong format + Format not specified + Define exact structure +
+
+ Wrong tone + Audience not clear + Specify audience/style +
+
+ Inconsistent + No examples provided + Add few-shot examples +
+
+ +### Step 2: Make Targeted Changes + +Resist the urge to rewrite everything. Changing multiple variables at once makes it impossible to know what helped and what hurt. Make one change, test it, then proceed: + +``` +Iteration 1: Add length constraint +Iteration 2: Specify format +Iteration 3: Add example +Iteration 4: Refine tone instructions +``` + +### Step 3: Document What Works + +Prompt engineering knowledge is easily lost. Keep a log of what you tried and why. This saves time when you revisit the prompt later or face similar challenges: + +```markdown +## Prompt: Customer Email Response + +### Version 1 (too formal) +"Write a response to this customer complaint." + +### Version 2 (better tone, still missing structure) +"Write a friendly but professional response to this complaint. +Show empathy first." + +### Version 3 (final - good results) +"Write a response to this customer complaint. Structure: +1. Acknowledge their frustration (1 sentence) +2. Apologize specifically (1 sentence) +3. Explain solution (2-3 sentences) +4. Offer additional help (1 sentence) + +Tone: Friendly, professional, empathetic but not groveling." +``` + +## Real-World Iteration Example + +Let's walk through a complete iteration cycle to see how each refinement builds on the last. Notice how each version addresses specific shortcomings of the previous one. + +### Task: Generate Product Names + + + +## Refinement Strategies by Task Type + +Different tasks fail in predictable ways. Knowing the common failure modes helps you diagnose and fix issues faster. + +### For Content Generation + +Content generation often produces generic, off-target, or poorly formatted output. The fix usually involves being more specific about constraints, providing concrete examples, or defining your brand voice explicitly. + + + +### For Code Generation + +Code output can fail technically (syntax errors, wrong language features) or architecturally (poor patterns, missing cases). Technical issues need version/environment specifics; architectural issues need design guidance. + + + +### For Analysis + +Analysis tasks often produce surface-level or unstructured results. Guide the model with specific frameworks (SWOT, Porter's Five Forces), request multiple viewpoints, or provide a template for the output structure. + + + +### For Q&A + +Question-answering can be too terse or too verbose, and may lack confidence indicators or sources. Specify the detail level you need and whether you want citations or uncertainty expressed. + + + +## The Feedback Loop Technique + +Here's a meta-technique: use the model itself to help improve your prompts. Share what you tried, what you got, and what you wanted. The model can often suggest improvements you hadn't considered. + +``` +I used this prompt: +"[your prompt]" + +And got this output: +"[model output]" + +I wanted something more [describe gap]. How should I modify +my prompt to get better results? +``` + +## A/B Testing Prompts + +For prompts that will be used repeatedly or at scale, don't just pick the first one that works. Test variations to find the most reliable and highest-quality approach. + +``` +Prompt A: "Summarize this article in 3 bullet points." +Prompt B: "Extract the 3 most important insights from this article." +Prompt C: "What are the key takeaways from this article? List 3." +``` + +Run each multiple times, compare: +- Consistency of output +- Quality of information +- Relevance to your needs + +## When to Stop Iterating + +Perfection is the enemy of good enough. Know when your prompt is ready for use and when you're just polishing for diminishing returns. + +
+
+

Ready to Ship

+
+

Output consistently meets requirements

+

Edge cases are handled appropriately

+

Format is reliable and parseable

+

Further improvements show diminishing returns

+
+
+
+

Keep Iterating

+
+

Output is inconsistent across runs

+

Edge cases cause failures

+

Critical requirements are missed

+

You haven't tested enough variations

+
+
+
+ +## Version Control for Prompts + +Prompts are code. For any prompt used in production, treat it with the same rigor: version control, changelogs, and the ability to roll back if something breaks. + + +prompts.chat includes automatic version history for your prompts. Every edit is saved, so you can compare versions and restore previous iterations with one click. + + +For self-managed prompts, use a folder structure: + +``` +prompts/ +├── customer-response/ +│ ├── v1.0.txt # Initial version +│ ├── v1.1.txt # Fixed tone issue +│ ├── v2.0.txt # Major restructure +│ └── current.txt # Symlink to active version +└── changelog.md # Document changes +``` + +## Summary + + +Start simple, observe carefully, change one thing at a time, document what works, and know when to stop. The best prompts aren't written—they're discovered through systematic iteration. + + + + +## Practice: Improve This Prompt + +Try improving this weak prompt yourself. Edit it, then use AI to compare your version with the original: + + + +In the next chapter, we'll explore JSON and YAML prompting for structured data applications. diff --git a/src/content/book/ko/09-json-yaml-prompting.mdx b/src/content/book/ko/09-json-yaml-prompting.mdx new file mode 100644 index 00000000..318619da --- /dev/null +++ b/src/content/book/ko/09-json-yaml-prompting.mdx @@ -0,0 +1,586 @@ +Structured data formats like JSON and YAML are essential for building applications that consume AI outputs programmatically. This chapter covers techniques for reliable structured output generation. + + +JSON and YAML transform AI outputs from freeform text into structured, type-safe data that code can consume directly. + + +## Why Structured Formats? + + + +## JSON Prompting Basics + +JSON (JavaScript Object Notation) is the most common format for programmatic AI outputs. Its strict syntax makes it easy to parse, but also means small errors can break your entire pipeline. + +### Do's and Don'ts: Requesting JSON + + + +### Simple JSON Output + +Start with a schema showing the expected structure. The model will fill in values based on the input text. + +``` +Extract the following information as JSON: + +{ + "name": "string", + "age": number, + "email": "string" +} + +Text: "Contact John Smith, 34 years old, at john@example.com" +``` + +Output: +```json +{ + "name": "John Smith", + "age": 34, + "email": "john@example.com" +} +``` + +### Nested JSON Structures + +Real-world data often has nested relationships. Define each level of your schema clearly, especially for arrays of objects. + +``` +Parse this order into JSON: + +{ + "order_id": "string", + "customer": { + "name": "string", + "email": "string" + }, + "items": [ + { + "product": "string", + "quantity": number, + "price": number + } + ], + "total": number +} + +Order: "Order #12345 for Jane Doe (jane@email.com): 2x Widget ($10 each), +1x Gadget ($25). Total: $45" +``` + +### Ensuring Valid JSON + + +Models often wrap JSON in markdown code blocks or add explanatory text. Be explicit about wanting raw JSON only. + + +Add explicit instructions: + +``` +CRITICAL: Return ONLY valid JSON. No markdown, no explanation, +no additional text before or after the JSON object. + +If a field cannot be determined, use null. +Ensure all strings are properly quoted and escaped. +Numbers should not be quoted. +``` + +## YAML Prompting Basics + +YAML is more human-readable than JSON and supports comments. It's the standard for configuration files, especially in DevOps (Docker, Kubernetes, GitHub Actions). + +### Simple YAML Output + +YAML uses indentation instead of braces. Provide a template showing the expected structure. + +``` +Generate a configuration file in YAML format: + +server: + host: string + port: number + ssl: boolean +database: + type: string + connection_string: string + +Requirements: Production server on port 443 with SSL, PostgreSQL database +``` + +Output: +```yaml +server: + host: "0.0.0.0" + port: 443 + ssl: true +database: + type: "postgresql" + connection_string: "postgresql://user:pass@localhost:5432/prod" +``` + +### Complex YAML Structures + +For complex configurations, be specific about requirements. The model knows common patterns for tools like GitHub Actions, Docker Compose, and Kubernetes. + +``` +Generate a GitHub Actions workflow in YAML: + +Requirements: +- Trigger on push to main and pull requests +- Run on Ubuntu latest +- Steps: checkout, setup Node 18, install dependencies, run tests +- Cache npm dependencies +``` + +## Type Definitions in Prompts + +Type definitions give the model a precise contract for output structure. They're more explicit than examples and easier to validate programmatically. + +### Using TypeScript-like Types + +TypeScript interfaces are familiar to developers and precisely describe optional fields, union types, and arrays. The prompts.chat platform uses this approach for structured prompts. + + + +### JSON Schema Definition + + +JSON Schema is a formal specification for describing JSON structure. It's supported by many validation libraries and API tools. + + +JSON Schema provides constraints like min/max values, required fields, and regex patterns: + +``` +Extract data according to this JSON Schema: + +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "type": "object", + "required": ["title", "author", "year"], + "properties": { + "title": { "type": "string" }, + "author": { "type": "string" }, + "year": { "type": "integer", "minimum": 1000, "maximum": 2100 }, + "genres": { + "type": "array", + "items": { "type": "string" } + }, + "rating": { + "type": "number", + "minimum": 0, + "maximum": 5 + } + } +} + +Book: "1984 by George Orwell (1949) - A dystopian masterpiece. +Genres: Science Fiction, Political Fiction. Rated 4.8/5" +``` + +## Handling Arrays + +Arrays require special attention. Specify whether you need a fixed number of items or a variable-length list, and how to handle empty cases. + +### Fixed-Length Arrays + +When you need exactly N items, state it explicitly. The model will ensure the array has the right length. + +``` +Extract exactly 3 key points as JSON: + +{ + "key_points": [ + "string (first point)", + "string (second point)", + "string (third point)" + ] +} + +Article: [article text] +``` + +### Variable-Length Arrays + +For variable-length arrays, specify what to do when there are zero items. Including a count field helps verify extraction completeness. + +``` +Extract all mentioned people as JSON: + +{ + "people": [ + { + "name": "string", + "role": "string or null if not mentioned" + } + ], + "count": number +} + +If no people are mentioned, return empty array. + +Text: [text] +``` + +## Enum Values and Constraints + +Enums restrict values to a predefined set. This is crucial for classification tasks and anywhere you need consistent, predictable outputs. + +### Do's and Don'ts: Enum Values + + + +### String Enums + +List allowed values explicitly. Use "MUST be one of" language to enforce strict matching. + +``` +Classify this text. The category MUST be one of these exact values: +- "technical" +- "business" +- "creative" +- "personal" + +Return JSON: +{ + "text": "original text (truncated to 50 chars)", + "category": "one of the enum values above", + "confidence": number between 0 and 1 +} + +Text: [text to classify] +``` + +### Validated Numbers + +Numeric constraints prevent out-of-range values. Specify the type (integer vs float) and valid range. + +``` +Rate these aspects. Each score MUST be an integer from 1 to 5. + +{ + "quality": 1-5, + "value": 1-5, + "service": 1-5, + "overall": 1-5 +} + +Review: [review text] +``` + +## Handling Missing Data + +Real-world text often lacks some information. Define how the model should handle missing data to avoid hallucinated values. + +### Do's and Don'ts: Missing Information + + + +### Null Values + +Explicitly allow null and instruct the model not to invent information. This is safer than having the model guess. + +``` +Extract information. Use null for any field that cannot be +determined from the text. Do NOT invent information. + +{ + "company": "string or null", + "revenue": "number or null", + "employees": "number or null", + "founded": "number (year) or null", + "headquarters": "string or null" +} + +Text: "Apple, headquartered in Cupertino, was founded in 1976." +``` + +Output: +```json +{ + "company": "Apple", + "revenue": null, + "employees": null, + "founded": 1976, + "headquarters": "Cupertino" +} +``` + +### Default Values + +When defaults make sense, specify them in the schema. This is common for configuration extraction. + +``` +Extract settings with these defaults if not specified: + +{ + "theme": "light" (default) | "dark", + "language": "en" (default) | other ISO code, + "notifications": true (default) | false, + "fontSize": 14 (default) | number +} + +User preferences: "I want dark mode and larger text (18px)" +``` + +## Multi-Object Responses + +Often you need to extract multiple items from a single input. Define the array structure and any sorting/grouping requirements. + +### Array of Objects + +For lists of similar items, define the object schema once and specify it's an array. + +``` +Parse this list into JSON array: + +[ + { + "task": "string", + "priority": "high" | "medium" | "low", + "due": "ISO date string or null" + } +] + +Todo list: +- Finish report (urgent, due tomorrow) +- Call dentist (low priority) +- Review PR #123 (medium, due Friday) +``` + +### Grouped Objects + +Grouping tasks require categorization logic. The model will sort items into the categories you define. + +``` +Categorize these items into JSON: + +{ + "fruits": ["string array"], + "vegetables": ["string array"], + "other": ["string array"] +} + +Items: apple, carrot, bread, banana, broccoli, milk, orange, spinach +``` + +## YAML for Configuration Generation + +YAML shines for DevOps configurations. The model knows standard patterns for common tools and can generate production-ready configs. + +### Do's and Don'ts: YAML Configs + + + +### Docker Compose + +Specify the services you need and any special requirements. The model will handle the YAML syntax and best practices. + +``` +Generate a docker-compose.yml for: +- Node.js app on port 3000 +- PostgreSQL database +- Redis cache +- Nginx reverse proxy + +Include: +- Health checks +- Volume persistence +- Environment variables from .env file +- Network isolation +``` + +### Kubernetes Manifests + +Kubernetes manifests are verbose but follow predictable patterns. Provide the key parameters and the model will generate compliant YAML. + +``` +Generate Kubernetes deployment YAML: + +Deployment: +- Name: api-server +- Image: myapp:v1.2.3 +- Replicas: 3 +- Resources: 256Mi memory, 250m CPU (requests) +- Health checks: /health endpoint +- Environment from ConfigMap: api-config + +Also generate matching Service (ClusterIP, port 8080) +``` + +## Validation and Error Handling + +For production systems, build validation into your prompts. This catches errors before they propagate through your pipeline. + +### Self-Validation Prompt + +Ask the model to validate its own output against rules you specify. This catches format errors and invalid values. + +``` +Extract data as JSON, then validate your output. + +Schema: +{ + "email": "valid email format", + "phone": "E.164 format (+1234567890)", + "date": "ISO 8601 format (YYYY-MM-DD)" +} + +After generating JSON, check: +1. Email contains @ and valid domain +2. Phone starts with + and contains only digits +3. Date is valid and parseable + +If validation fails, fix the issues before responding. + +Text: [contact information] +``` + +### Error Response Format + +Define separate success and error formats. This makes programmatic handling much easier. + +``` +Attempt to extract data. If extraction fails, return error format: + +Success format: +{ + "success": true, + "data": { ... extracted data ... } +} + +Error format: +{ + "success": false, + "error": "description of what went wrong", + "partial_data": { ... any data that could be extracted ... } +} +``` + +## JSON vs YAML: When to Use Which + +
+
+
Use JSON When
+
+

Programmatic parsing needed

+

API responses

+

Strict type requirements

+

JavaScript/Web integration

+

Compact representation

+
+
+
+
Use YAML When
+
+

Human readability matters

+

Configuration files

+

Comments are needed

+

DevOps/Infrastructure

+

Deep nested structures

+
+
+
+ +## Prompts.chat Structured Prompts + +On prompts.chat, you can create prompts with structured output formats: + +``` +When creating a prompt on prompts.chat, you can specify: + +Type: STRUCTURED +Format: JSON or YAML + +The platform will: +- Validate outputs against your schema +- Provide syntax highlighting +- Enable easy copying of structured output +- Support template variables in your schema +``` + +## Common Pitfalls + + +These three issues cause most JSON parsing failures. Check for them when your code can't parse AI output. + + +### 1. Markdown Code Blocks + +**Problem:** Model wraps JSON in ```json blocks + +**Solution:** +``` +Return ONLY the JSON object. Do not wrap in markdown code blocks. +Do not include ```json or ``` markers. +``` + +### 2. Trailing Commas + +**Problem:** Invalid JSON due to trailing commas + +**Solution:** +``` +Ensure valid JSON syntax. No trailing commas after the last +element in arrays or objects. +``` + +### 3. Unescaped Strings + +**Problem:** Quotes or special characters break JSON + +**Solution:** +``` +Properly escape special characters in strings: +- \" for quotes +- \\ for backslashes +- \n for newlines +``` + +## Summary + + +Define schemas explicitly using TypeScript interfaces or JSON Schema. Specify types and constraints, handle nulls and defaults, request self-validation, and choose the right format for your use case. + + + + +This completes Part II on techniques. In Part III, we'll explore practical applications across different domains. diff --git a/src/content/book/ko/10-system-prompts-personas.mdx b/src/content/book/ko/10-system-prompts-personas.mdx new file mode 100644 index 00000000..c6737cda --- /dev/null +++ b/src/content/book/ko/10-system-prompts-personas.mdx @@ -0,0 +1,435 @@ +System prompts are like giving AI its personality and job description before a conversation starts. Think of it as the "backstage instructions" that shape everything the AI says. + + +A system prompt is a special message that tells the AI who it is, how to behave, and what it can or can't do. Users don't usually see this message, but it affects every response. + + + +System prompts build on the concepts from [Role-Based Prompting](/book/04-role-based-prompting). While role prompts assign a persona within your message, system prompts set that identity at a deeper level that persists across the entire conversation. + + +## How System Prompts Work + +When you chat with AI, there are actually three types of messages: + + + +The system message stays active for the whole conversation. It's like the AI's "instruction manual." + +## Building a System Prompt + +A good system prompt has five parts. Think of them as filling out a character sheet for the AI: + + + +### Example: A Coding Tutor + + + +## Persona Patterns + +Different tasks need different AI personalities. Here are three common patterns you can adapt: + +### 1. The Expert + +Best for: Learning, research, professional advice + + + +### 2. The Assistant + +Best for: Productivity, organization, getting things done + + + +### 3. The Character + +Best for: Creative writing, roleplay, entertainment + + + +## Advanced Techniques + +### Layered Instructions + +Think of your system prompt like an onion with layers. The inner layers are most important: + + + +### Adaptive Behavior + +Make your AI adjust to different users automatically: + + + +### Conversation Memory + +AI doesn't remember past conversations, but you can tell it to track things within the current chat: + + + +## Real-World Examples + +Here are complete system prompts for common use cases. Click to try them! + +### Customer Support Bot + + + +### Study Buddy + + + +### Writing Coach + + + +## Testing Your System Prompt + +Before using a system prompt for real, test it! Here's what to check: + + + +### Understanding Jailbreak Attacks + +"Jailbreaking" is when someone tries to trick AI into ignoring its rules. Understanding these attacks helps you build better defenses. + + + +### More Test Scenarios + +Use these interactive examples to see how a well-designed system prompt handles tricky situations: + +#### Test 1: Jailbreak Attempt + +See how a good system prompt resists attempts to override it: + + + +#### Test 2: Stay in Character + +Test if the AI maintains its persona when pushed: + + + +#### Test 3: Boundary Enforcement + +Check if the AI respects its stated limitations: + + + +#### Test 4: Reveal System Prompt + +See if the AI protects its instructions: + + + +#### Test 5: Conflicting Instructions + +Test how the AI handles contradictory requests: + + + + +A well-crafted system prompt will: +- Politely decline inappropriate requests +- Stay in character while redirecting +- Not reveal confidential instructions +- Handle edge cases gracefully + + +## Quick Reference + +
+
+

Do

+
    +
  • Give a clear identity
  • +
  • List specific capabilities
  • +
  • Set explicit boundaries
  • +
  • Define the tone and style
  • +
  • Include example responses
  • +
+
+
+

Don't

+
    +
  • Be vague about the role
  • +
  • Forget to set limits
  • +
  • Make it too long (500 words max)
  • +
  • Contradict yourself
  • +
  • Assume the AI will "figure it out"
  • +
+
+
+ +## Summary + +System prompts are the AI's instruction manual. They set up: +- **Who** the AI is (identity and expertise) +- **What** it can and can't do (capabilities and limits) +- **How** it should respond (tone, format, style) + + +Begin with a short system prompt and add more rules as you discover what's needed. A clear 100-word prompt beats a confusing 500-word one. + + + + + + +In the next chapter, we'll explore prompt chaining: connecting multiple prompts together for complex multi-step tasks. diff --git a/src/content/book/ko/11-prompt-chaining.mdx b/src/content/book/ko/11-prompt-chaining.mdx new file mode 100644 index 00000000..9f54da52 --- /dev/null +++ b/src/content/book/ko/11-prompt-chaining.mdx @@ -0,0 +1,379 @@ +Prompt chaining breaks complex tasks into sequences of simpler prompts, where each step's output feeds into the next. This technique dramatically improves reliability and enables sophisticated workflows that would be impossible with a single prompt. + + +Just like a factory assembly line breaks manufacturing into specialized stations, prompt chaining breaks AI tasks into specialized steps. Each step does one thing well, and the combined output is far better than trying to do everything at once. + + +## Why Chain Prompts? + +Single prompts struggle with complex tasks because they try to do too much at once. The AI has to simultaneously understand, analyze, plan, and generate, which leads to errors and inconsistencies. + +
+
+

Single Prompt Struggles

+
+

Multi-step reasoning gets confused

+

Different "modes" of thinking clash

+

Complex outputs lack consistency

+

No opportunity for quality control

+
+
+
+

Chaining Solves This

+
+

Each step focuses on one task

+

Specialized prompts for each mode

+

Validate between steps

+

Debug and improve individual steps

+
+
+
+ +## Basic Chaining Pattern + +The simplest chain passes output from one prompt directly to the next. Each step has a clear, focused purpose. + +
+
+
+

Prompt 1

+

(Extract)

+
+

Input

+
+
→
+
+
+

Prompt 2

+

(Analyze)

+
+

Intermediate

+
+
→
+
+
+

Prompt 3

+

(Generate)

+
+

Output

+
+
+ + +The most common chain pattern is **Extract → Transform → Generate**. First extract raw data, then reshape it for your purpose, then generate the final output. This pattern works for almost any content task. + + +## Chain Types + +Different tasks require different chain architectures. Choose the pattern that matches your workflow. + + + +### Sequential Chain + +The most straightforward pattern: each step depends on the previous. Think of it as a relay race where each runner passes the baton to the next. + + + +### Parallel Chain + +When you need multiple perspectives on the same input, run prompts in parallel and merge results. This is faster than sequential chains and provides richer analysis. + + + +### Conditional Chain + +Route inputs through different paths based on classification. This is like a decision tree where the AI first categorizes the input, then handles each category differently. + + + +### Iterative Chain + +Keep refining output until it meets quality standards. The AI generates, evaluates, and improves in a loop until satisfied or max iterations reached. + + +Always set a maximum number of iterations (typically 3-5) to prevent infinite loops and control costs. The law of diminishing returns applies: most improvement happens in the first 2-3 iterations. + + += 8: EXIT LOOP' } + ]} +/> + +## Common Chain Patterns + +These battle-tested patterns solve common problems. Use them as starting points and adapt to your needs. + +### Extract → Transform → Generate + +The workhorse of content processing. Pull data out, reshape it, then create something new. + +
+

Best For

+

Document summarization, report generation, content repurposing, data-to-narrative conversion

+
+ + + +### Analyze → Plan → Execute + +Perfect for code refactoring, project planning, or any task where you need to understand before acting. + +
+

Best For

+

Code refactoring, project planning, troubleshooting, strategic decision-making, complex problem solving

+
+ + {\n const { email, password } = req.body;\n if (!email || !isValidEmail(email)) {\n return res.status(400).json({ error: 'Invalid email' });\n }\n next();\n};" } + ]} +/> + +### Generate → Critique → Refine + +The self-improvement loop. Generate content, have the AI evaluate it critically, then improve based on that feedback. This mimics how professional writers and editors work together. + +
+

Best For

+

Marketing copy, creative writing, email drafts, presentations, any content that benefits from revision

+
+ + + +## Implementing Chains + +You can implement chains manually for experimentation, or programmatically for production systems. Start simple and add complexity as needed. + +### Manual Chaining + +The copy-paste approach is perfect for prototyping and experimentation. Run each prompt manually, examine the output, and paste it into the next prompt. + + + +### Programmatic Chaining + +For production systems, automate the chain with code. This enables error handling, logging, and integration with your application. + + + +### Using Chain Templates + +Define chains as configuration files for reusability and easy modification. This separates prompt logic from application code. + + + +## Error Handling in Chains + +Chains can fail at any step. Build in validation, retries, and fallbacks to make your chains robust. + + + + +If one step produces bad output, every following step will be affected. Always validate critical intermediate results before passing them forward. + + +### Validation Between Steps + +Add a validation step after any step that produces structured data. This catches errors early before they cascade. + + + +### Fallback Chains + +When your primary approach fails, have a simpler backup ready. Trade capability for reliability. + + + +## Chain Optimization + +Once your chain works, optimize for speed, cost, and reliability. These often trade off against each other. + +
+
+

Reducing Latency

+
+

Parallelize independent steps

+

Cache intermediate results

+

Use smaller models for simple steps

+

Batch similar operations

+
+
+
+

Reducing Cost

+
+

Use cheaper models for classification

+

Limit iterations in loops

+

Short-circuit when possible

+

Cache repeated queries

+
+
+
+

Improving Reliability

+
+

Add validation between steps

+

Include retry logic

+

Log intermediate results

+

Implement fallback paths

+
+
+
+ +## Real-World Chain Example + +Let's walk through a complete production chain. This content pipeline transforms a raw idea into a polished article package. + +### Content Pipeline Chain + + + +## Summary + +Prompt chaining transforms what AI can accomplish by breaking impossible tasks into achievable steps. + +
+
+

Chaining Enables

+
+

Complex multi-step workflows

+

Higher quality through specialization

+

Better error handling and validation

+

Modular, reusable prompt components

+
+
+
+

Key Principles

+
+

Break complex tasks into simple steps

+

Design clear interfaces between steps

+

Validate intermediate outputs

+

Build in error handling and fallbacks

+

Optimize for your constraints

+
+
+
+ + +Begin with a 2-3 step sequential chain. Get it working reliably before adding complexity. Most tasks don't need elaborate chain architectures. + + + + +In the next chapter, we'll explore multimodal prompting: working with images, audio, and other non-text content. diff --git a/src/content/book/ko/12-handling-edge-cases.mdx b/src/content/book/ko/12-handling-edge-cases.mdx new file mode 100644 index 00000000..4708ee3c --- /dev/null +++ b/src/content/book/ko/12-handling-edge-cases.mdx @@ -0,0 +1,580 @@ +Prompts that work perfectly in testing often fail in the real world. Users send empty messages, paste walls of text, make ambiguous requests, and sometimes try to break your system intentionally. This chapter teaches you to build prompts that handle the unexpected gracefully. + + +80% of production issues come from inputs you never anticipated. A prompt that handles edge cases well is worth more than a "perfect" prompt that only works with ideal inputs. + + +## Why Edge Cases Break Prompts + +When a prompt encounters unexpected input, it typically fails in one of three ways: + +**Silent Failures**: The model produces output that looks correct but contains errors. These are the most dangerous because they're hard to detect. + +**Confused Responses**: The model misinterprets the request and answers a different question than what was asked. + +**Hallucinated Handling**: The model invents a way to handle the edge case that doesn't match your intended behavior. + + + +## Categories of Edge Cases + +Understanding what can go wrong helps you prepare for it. Edge cases fall into three main categories: + +### Input Edge Cases + +These are problems with the data itself: + + + +### Domain Edge Cases + +These are requests that push the boundaries of your prompt's purpose: + + + +### Adversarial Edge Cases + +These are deliberate attempts to misuse your system: + + + +## Input Validation Patterns + +The key to handling edge cases is explicit instructions. Don't assume the model will "figure it out" - tell it exactly what to do in each scenario. + +### Handling Empty Input + +The most common edge case is receiving nothing at all, or input that's essentially empty (just whitespace or greetings). + + + +### Handling Long Input + +When input exceeds what you can reasonably process, fail gracefully rather than silently truncating. + + + +### Handling Ambiguous Requests + +When a request could mean multiple things, asking for clarification is better than guessing wrong. + + + +## Building Defensive Prompts + +A defensive prompt anticipates failure modes and defines explicit behavior for each. Think of it as error handling for natural language. + +### The Defensive Template + +Every robust prompt should address these four areas: + + + +### Example: Defensive Data Extraction + +This prompt extracts contact information but handles every edge case explicitly. Notice how each potential failure has a defined response. + + + +## Handling Out-of-Scope Requests + +Every prompt has boundaries. Defining them explicitly prevents the model from wandering into territory where it might give bad advice or make things up. + +### Graceful Scope Limits + +The best out-of-scope responses do three things: acknowledge the request, explain the limitation, and offer an alternative. + + + +### Handling Knowledge Cutoffs + +Be honest about what you don't know. Users trust AI more when it admits limitations. + + + +## Adversarial Input Handling + +Some users will try to manipulate your prompts, either out of curiosity or malicious intent. Building defenses into your prompts reduces these risks. + +### Prompt Injection Defense + +Prompt injection is when a user tries to override your instructions by embedding their own commands in the input. The key defense is treating user input as data, never as instructions. + + + + +Prompt injection defenses reduce risk but can't eliminate it entirely. For high-stakes applications, combine prompt defenses with input sanitization, output filtering, and human review. + + +### Handling Sensitive Requests + +Some requests require special handling due to safety, legal, or ethical concerns. Define these boundaries explicitly. + + + +## Error Recovery Patterns + +Even well-designed prompts will encounter situations they can't handle perfectly. The goal is to fail helpfully. + +### Graceful Degradation + +When you can't fully complete a task, offer what you can rather than failing completely. + + + +### Confidence Indicators + +Teach your prompts to express uncertainty. This helps users know when to trust the output and when to verify. + + + + + +## Testing Edge Cases + +Before deploying a prompt, systematically test it against the edge cases you've anticipated. This checklist helps ensure you haven't missed common failure modes. + +### Edge Case Testing Checklist + + + + + + + + + +### Creating a Test Suite + +For production prompts, create a systematic test suite. Here's a pattern you can adapt: + + + +## Real-World Example: Robust Customer Service Bot + +This comprehensive example shows how all the patterns come together in a production-ready prompt. Notice how every edge case has explicit handling. + + + +## Summary + +Building robust prompts requires thinking about what can go wrong before it does. The key principles: + + + + +In production, everything that can go wrong eventually will. A prompt that handles edge cases gracefully is worth more than a "perfect" prompt that only works with ideal inputs. + + + + +In the next chapter, we'll explore how to work with multiple AI models and compare their outputs. diff --git a/src/content/book/ko/13-multimodal-prompting.mdx b/src/content/book/ko/13-multimodal-prompting.mdx new file mode 100644 index 00000000..376960ae --- /dev/null +++ b/src/content/book/ko/13-multimodal-prompting.mdx @@ -0,0 +1,665 @@ +For most of history, computers worked with one type of data at a time: text in one program, images in another, audio somewhere else. But humans don't experience the world this way. We see, hear, read, and speak simultaneously, combining all these inputs to understand our environment. + +**Multimodal AI** changes everything. These models can process multiple types of information together—analyzing an image while reading your question about it, or generating images from your text descriptions. This chapter teaches you how to communicate effectively with these powerful systems. + + +"Multi" means many, and "modal" refers to modes or types of data. A multimodal model can work with multiple modalities: text, images, audio, video, or even code. Instead of separate tools for each type, one model understands them all together. + + +## Why Multimodal Matters + +Traditional AI required you to describe everything in words. Want to ask about an image? You'd have to describe it first. Want to analyze a document? You'd need to transcribe it manually. Multimodal models eliminate these barriers. + + + +## Why Prompting Matters Even More for Multimodal + +With text-only models, the AI receives exactly what you type. But with multimodal models, the AI must interpret visual or audio information—and interpretation requires guidance. + + + +**Without guidance**, the model might describe colors, layout, or irrelevant details. **With guidance**, it focuses on what actually matters to you. + + +When you look at an image, you instantly know what's important based on your context and goals. The AI doesn't have this context unless you provide it. A photo of a crack in a wall could be: a structural engineering concern, an artistic texture, or irrelevant background. Your prompt determines how the AI interprets it. + + +## The Multimodal Landscape + +Different models have different capabilities. Here's what's available in 2025: + +### Understanding Models (Input → Analysis) + +These models accept various media types and produce text analysis or responses. + + + +### Generation Models (Text → Media) + +These models create images, audio, or video from text descriptions. + + + + +The multimodal landscape changes quickly. New models launch frequently, and existing models gain capabilities through updates. Always check the latest documentation for current features and limitations. + + +## Image Understanding Prompts + +The most common multimodal use case is asking AI to analyze images. The key is providing context about what you need. + +### Basic Image Analysis + +Start with a clear request structure. Tell the model what aspects to focus on. + + + +### Structured Output for Images + +When you need to process image analysis programmatically, request JSON output. + + + +### Comparative Analysis + +Comparing multiple images requires clear labeling and specific comparison criteria. + + + +## Document and Screenshot Analysis + +One of the most practical applications of multimodal AI is analyzing documents, screenshots, and UI elements. This saves hours of manual transcription and review. + +### Document Extraction + +Scanned documents, photos of receipts, and PDFs as images can all be processed. The key is telling the model what type of document it is and what information you need. + + + +### Screenshot and UI Analysis + +Screenshots are goldmines for debugging, UX review, and documentation. Guide the AI to focus on what matters. + + + +### Error Message Analysis + +When you encounter an error, a screenshot often contains more context than copying the error text alone. + + + +## Image Generation Prompts + +Generating images from text descriptions is an art form. The more specific and structured your prompt, the closer the result will match your vision. + +### The Anatomy of an Image Prompt + +Effective image generation prompts have several components: + + + +### Basic Image Generation + + + +### Scene Building + +For complex scenes, describe layers from foreground to background. + + + +## Audio Prompting + +Audio processing opens up transcription, analysis, and understanding of spoken content. The key is providing context about what the audio contains. + +### Enhanced Transcription + +Basic transcription is just the start. With good prompts, you can get speaker identification, timestamps, and domain-specific accuracy. + + + +### Audio Content Analysis + +Beyond transcription, AI can analyze the content, tone, and key moments in audio. + + + +## Video Prompting + +Video combines visual and audio analysis over time. The challenge is guiding the AI to focus on the relevant aspects across the entire duration. + +### Video Understanding + + + +### Video Content Extraction + +For specific information extraction from videos, be precise about what you need. + + + +## Multimodal Combinations + +The real power of multimodal AI emerges when you combine different types of input. These combinations enable analysis that would be impossible with any single modality. + +### Image + Text Verification + +Check if images and their descriptions match—essential for e-commerce, content moderation, and quality assurance. + + + +### Screenshot + Code Debugging + +One of the most powerful combinations for developers: seeing the visual bug alongside the code. + + + +### Multi-Image Decision Making + +When choosing between options, structured comparison helps make better decisions. + + + +## Best Practices for Multimodal Prompts + +Getting great results from multimodal AI requires understanding both its capabilities and limitations. + +### What Makes Multimodal Prompts Effective + + + +### Common Pitfalls to Avoid + + + +### Handling Limitations Gracefully + + + + diff --git a/src/content/book/ko/14-context-engineering.mdx b/src/content/book/ko/14-context-engineering.mdx new file mode 100644 index 00000000..b9c69b6d --- /dev/null +++ b/src/content/book/ko/14-context-engineering.mdx @@ -0,0 +1,287 @@ +Understanding context is essential for building AI applications that actually work. This chapter covers everything you need to know about giving AI the right information at the right time. + + +AI models are stateless. They don't remember past conversations. Every time you send a message, you need to include everything the AI needs to know. This is called "context engineering." + + +## What is Context? + +Context is all the information you give to AI alongside your question. Think of it like this: + + + +Without context, the AI has no idea what "status" you're asking about. With context, it can give a useful answer. + +### The Context Window + +Remember from earlier chapters: AI has a limited "context window" - the maximum amount of text it can see at once. This includes: + + + +## AI is Stateless + + +AI doesn't remember anything between conversations. Every API call starts fresh. If you want the AI to "remember" something, YOU have to include it in the context every time. + + +This is why chatbots send your entire conversation history with each message. It's not that the AI remembers - it's that the app re-sends everything. + + + +The AI will say it doesn't know because it truly doesn't have access to any previous context. + +## RAG: Retrieval-Augmented Generation + +RAG is a technique for giving AI access to knowledge it wasn't trained on. Instead of trying to fit everything into the AI's training, you: + +1. **Store** your documents in a searchable database +2. **Search** for relevant documents when a user asks a question +3. **Retrieve** the most relevant pieces +4. **Augment** your prompt with those pieces +5. **Generate** an answer using that context + +
+

How RAG Works:

+
+
+ 1 + User asks: "What's our refund policy?" +
+
+ 2 + System searches your documents for "refund policy" +
+
+ 3 + Finds relevant section from your policy document +
+
+ 4 + Sends to AI: "Based on this policy: [text], answer: What's our refund policy?" +
+
+ 5 + AI generates accurate answer using your actual policy +
+
+
+ +### Why RAG? + +
+
+

RAG Advantages

+
    +
  • Uses your actual, current data
  • +
  • Reduces hallucinations
  • +
  • Can cite sources
  • +
  • Easy to update (just update documents)
  • +
  • No expensive fine-tuning needed
  • +
+
+
+

When to Use RAG

+
    +
  • Customer support bots
  • +
  • Documentation search
  • +
  • Internal knowledge bases
  • +
  • Any domain-specific Q&A
  • +
  • When accuracy matters
  • +
+
+
+ +## Embeddings: How Search Works + +How does RAG know which documents are "relevant"? It uses **embeddings** - a way to turn text into numbers that capture meaning. + +### What Are Embeddings? + +An embedding is a list of numbers (a "vector") that represents the meaning of text. Similar meanings = similar numbers. + + + +### Semantic Search + +With embeddings, you can search by meaning, not just keywords: + + + +This is why RAG is so powerful - it finds relevant information even when the exact words don't match. + +## Function Calling / Tool Use + +Function calling lets AI use external tools - like searching the web, checking a database, or calling an API. + + +Different AI providers call this different things: "function calling" (OpenAI), "tool use" (Anthropic/Claude), or "tools" (general term). They all mean the same thing. + + +### How It Works + +1. You tell the AI what tools are available +2. AI decides if it needs a tool to answer +3. AI outputs a structured request for the tool +4. Your code runs the tool and returns results +5. AI uses the results to form its answer + + + +## Summarization: Managing Long Conversations + +As conversations get longer, you'll hit the context window limit. Since AI is stateless (it doesn't remember anything), long conversations can overflow. The solution? **Summarization**. + +### The Problem + + + +### Summarization Strategies + +Different approaches work for different use cases. Click each strategy to see how it processes the same conversation: + + + +### What to Capture in Summaries + +A good conversation summary preserves what matters: + + + +### Try It: Create a Summary + + + +### When to Summarize + + + +## MCP: Model Context Protocol + +MCP (Model Context Protocol) is a standard way to connect AI to external data and tools. Instead of building custom integrations for each AI provider, MCP provides a universal interface. + +### Why MCP? + + + +### MCP Provides + +- **Resources**: Data the AI can read (files, database records, API responses) +- **Tools**: Actions the AI can take (search, create, update, delete) +- **Prompts**: Pre-built prompt templates + + +This platform has an MCP server! You can connect it to Claude Desktop or other MCP-compatible clients to search and use prompts directly from your AI assistant. + + +## Building Context: The Complete Picture + + + +## Best Practices + + + +## Summary + +Context engineering is about giving AI the right information: + +- **AI is stateless** - include everything it needs every time +- **RAG** retrieves relevant documents to augment prompts +- **Embeddings** enable semantic search (meaning, not just keywords) +- **Function calling** lets AI use external tools +- **Summarization** manages long conversations +- **MCP** standardizes how AI connects to data and tools + + +The quality of AI output depends on the quality of context you provide. Better context = better answers. + diff --git a/src/content/book/ko/15-common-pitfalls.mdx b/src/content/book/ko/15-common-pitfalls.mdx new file mode 100644 index 00000000..3c9c2814 --- /dev/null +++ b/src/content/book/ko/15-common-pitfalls.mdx @@ -0,0 +1,373 @@ +Even experienced prompt engineers fall into predictable traps. The good news? Once you recognize these patterns, they're easy to avoid. This chapter walks through the most common pitfalls, explains why they happen, and gives you concrete strategies to sidestep them. + + +A single pitfall can turn a powerful AI into a frustrating tool. Understanding these patterns is often the difference between "AI doesn't work for me" and "AI transformed my workflow." + + +## The Vagueness Trap + +**The Pattern**: You know what you want, so you assume the AI will figure it out too. But vague prompts produce vague results. + + + +**Why it happens**: We naturally skip details when we think they're "obvious." But what's obvious to you isn't obvious to a model that has no context about your situation, audience, or goals. + + + +## The Overloading Trap + +**The Pattern**: You try to get everything in one prompt—comprehensive, funny, professional, beginner-friendly, advanced, SEO-optimized, and short. The result? The AI misses half your requirements or produces a confused mess. + + + +**Why it happens**: Fear of multiple interactions, or wanting to "get it all out" in one go. But cognitive overload affects AI just like it affects humans—too many competing requirements leads to dropped balls. + + + + +When a single prompt gets overloaded, [prompt chaining](/book/11-prompt-chaining) is often the solution. Break complex tasks into a sequence of focused prompts, where each step builds on the previous one. + + +## The Assumption Trap + +**The Pattern**: You reference something "from earlier" or assume the AI knows your project, your company, or your previous conversations. It doesn't. + + + +**Why it happens**: AI conversations feel like talking to a colleague. But unlike colleagues, most AI models have no persistent memory between sessions—each conversation starts fresh. + + + +## The Leading Question Trap + +**The Pattern**: You phrase your question in a way that embeds your assumption, getting back confirmation rather than insight. + + + +**Why it happens**: We often seek confirmation, not information. Our phrasing unconsciously pushes toward the answer we expect or want. + + + +## The Trust Everything Trap + +**The Pattern**: AI responses sound confident and authoritative, so you accept them without verification. But confidence doesn't equal accuracy. + + + +**Why it happens**: AI sounds confident even when completely wrong. We're also prone to "automation bias"—the tendency to trust computer outputs more than we should. + + + +## The One-Shot Trap + +**The Pattern**: You send one prompt, get a mediocre result, and conclude that AI "doesn't work" for your use case. But great results almost always require iteration. + + + +**Why it happens**: We expect AI to read our minds on the first try. We don't expect to iterate with Google searches, but somehow expect perfection from AI. + + + +## The Format Neglect Trap + +**The Pattern**: You focus on what you want the AI to say, but forget to specify how it should be formatted. Then you get prose when you needed JSON, or a wall of text when you needed bullet points. + + + +**Why it happens**: We focus on content over structure. But if you need to parse the output programmatically, or paste it somewhere specific, format matters as much as content. + + + +## The Context Window Trap + +**The Pattern**: You paste an enormous document and expect comprehensive analysis. But models have limits—they may truncate, lose focus, or miss important details in long inputs. + + + + + +## The Anthropomorphization Trap + +**The Pattern**: You treat AI like a human colleague—expecting it to "enjoy" tasks, remember you, or care about outcomes. It doesn't. + + + +**Why it happens**: AI responses are so human-like that we naturally slip into social patterns. But emotional appeals don't make the AI try harder—clear instructions do. + + +Instead of emotional appeals, focus on: clear requirements, good examples, specific constraints, and explicit success criteria. These improve outputs. "Please try really hard" doesn't. + + +## The Security Neglect Trap + +**The Pattern**: In the rush to get things working, you include sensitive information in prompts—API keys, passwords, personal data, or proprietary information. + + + +**Why it happens**: Focus on functionality over security. But remember: prompts often go to external servers, may be logged, and could be used for training. + + + +## The Hallucination Ignorance Trap + +**The Pattern**: You ask for citations, statistics, or specific facts, and assume they're real because the AI stated them confidently. But AI regularly invents plausible-sounding information. + + + +**Why it happens**: AI generates text that sounds authoritative. It doesn't "know" when it's making things up—it's predicting likely text, not retrieving verified facts. + + + +## Pre-Send Checklist + +Before sending any important prompt, run through this quick checklist: + + + + + +## Analyze Your Prompts + +Use AI to get instant feedback on your prompt quality. Paste any prompt and get a detailed analysis: + + + +## Debug This Prompt + +Can you spot what's wrong with this prompt? + + diff --git a/src/content/book/ko/16-ethics-responsible-use.mdx b/src/content/book/ko/16-ethics-responsible-use.mdx new file mode 100644 index 00000000..c2b8ba5e --- /dev/null +++ b/src/content/book/ko/16-ethics-responsible-use.mdx @@ -0,0 +1,357 @@ +The prompts you write shape how AI behaves. A well-crafted prompt can educate, assist, and empower. A careless one can deceive, discriminate, or cause harm. As prompt engineers, we're not just users—we're designers of AI behavior, and that comes with real responsibility. + +This chapter isn't about rules imposed from above. It's about understanding the impact of our choices and building habits that lead to AI use we can be proud of. + + +AI amplifies whatever it's given. A biased prompt produces biased outputs at scale. A deceptive prompt enables deception at scale. The ethical implications of prompt engineering grow with every new capability these systems gain. + + +## Ethical Foundations + +Every decision in prompt engineering connects to a few core principles: + + + +### The Prompt Engineer's Role + +You have more influence than you might realize: + +- **What AI produces**: Your prompts determine the content, tone, and quality of outputs +- **How AI interacts**: Your system prompts shape personality, boundaries, and user experience +- **What safeguards exist**: Your design choices determine what the AI will and won't do +- **How mistakes are handled**: Your error handling determines whether failures are graceful or harmful + +## Avoiding Harmful Outputs + +The most fundamental ethical obligation is preventing your prompts from causing harm. + +### Categories of Harmful Content + + + + +CSAM stands for **Child Sexual Abuse Material**. Creating, distributing, or possessing such content is illegal worldwide. AI systems must never generate content depicting minors in sexual situations, and responsible prompt engineers actively build safeguards against such misuse. + + +### Building Safety Into Prompts + +When building AI systems, include explicit safety guidelines: + + + +### The Intent vs. Impact Framework + +Not every sensitive request is malicious. Use this framework for ambiguous cases: + + + +## Addressing Bias + +AI models inherit biases from their training data—historical inequities, representation gaps, cultural assumptions, and linguistic patterns. As prompt engineers, we can either amplify these biases or actively counteract them. + +### How Bias Manifests + + + +### Testing for Bias + + + +### Mitigating Bias in Practice + + + +## Transparency and Disclosure + +When should you tell people AI was involved? The answer depends on context—but the trend is toward more disclosure, not less. + +### When Disclosure Matters + + + +### How to Disclose Appropriately + + + +Common disclosure phrases that work well: +- "Written with AI assistance" +- "AI-generated first draft, human edited" +- "Analysis performed using AI tools" +- "Created with AI, reviewed and approved by [name]" + +## Privacy Considerations + +Every prompt you send contains data. Understanding where that data goes—and what shouldn't be in it—is essential. + +### What Never Belongs in Prompts + + + +### Safe Data Handling Pattern + + + + +**PII** stands for **Personally Identifiable Information**—any data that can identify a specific individual. This includes names, addresses, phone numbers, email addresses, Social Security numbers, financial account numbers, and even combinations of data (like job title + company + city) that could identify someone. When prompting AI, always anonymize or remove PII to protect privacy. + + + + +## Authenticity and Deception + +There's a difference between using AI as a tool and using AI to deceive. + +### The Legitimacy Line + + + +Key questions to ask: +- Would the recipient expect this to be original human work? +- Am I gaining unfair advantage through deception? +- Would disclosure change how the work is received? + +### Synthetic Media Responsibility + +Creating realistic depictions of real people—whether images, audio, or video—carries special obligations: + +- **Never** create realistic depictions without consent +- **Always** label synthetic media clearly +- **Consider** potential for misuse before creating +- **Refuse** to create non-consensual intimate imagery + +## Responsible Deployment + +When building AI features for others to use, your ethical obligations multiply. + +### Pre-Deployment Checklist + + + +### Human Oversight Principles + + + +## Special Context Guidelines + +Some domains require extra care due to their potential for harm or the vulnerability of those involved. + +### Healthcare + + + +### Legal and Financial + +These domains have regulatory implications and require appropriate disclaimers: + + + +### Children and Education + + + +## Self-Assessment + +Before deploying any prompt or AI system, run through these questions: + + + + diff --git a/src/content/book/ko/17-prompt-optimization.mdx b/src/content/book/ko/17-prompt-optimization.mdx new file mode 100644 index 00000000..44917bcb --- /dev/null +++ b/src/content/book/ko/17-prompt-optimization.mdx @@ -0,0 +1,269 @@ +A good prompt gets the job done. An optimized prompt gets the job done efficiently—faster, cheaper, more consistently. This chapter teaches you how to systematically improve prompts across multiple dimensions. + + +Want to optimize your prompts automatically? Use our [Prompt Enhancer](/developers#enhancer) tool. It analyzes your prompt, applies optimization techniques, and shows you similar community prompts for inspiration. + + +## The Optimization Trade-offs + +Every optimization involves trade-offs. Understanding these helps you make intentional choices: + + + +## Measuring What Matters + +Before optimizing, define success. What does "better" mean for your use case? + + + + +Percentile metrics show response time distribution. **p50** (median) means 50% of requests are faster than this value. **p95** means 95% are faster—it catches slow outliers. If your p50 is 1s but p95 is 10s, most users are happy but 5% experience frustrating delays. + + + + +## Token Optimization + +Tokens cost money and add latency. Here's how to say the same thing with fewer tokens. + +### The Compression Principle + + + +**Same result, 82% fewer tokens.** + +### Token-Saving Techniques + + + + + +## Quality Optimization + +Sometimes you need better outputs, not cheaper ones. Here's how to improve quality. + +### Accuracy Boosters + + + +### Consistency Boosters + + + + + +## Latency Optimization + +When speed matters, every millisecond counts. + +### Model Selection by Speed Need + + + +### Speed Techniques + + 100 tokens", exampleType: "text", color: "cyan" }, + { label: "Cache Aggressively", description: "Don't recompute identical queries", example: "Cache common questions, template outputs", exampleType: "text", color: "cyan" } +]} /> + +## Cost Optimization + +At scale, small savings multiply into significant budget impact. + +### Understanding Costs + +Use this calculator to estimate your API costs across different models: + + + +### Cost Reduction Strategies + + + +## The Optimization Loop + +Optimization is iterative. Here's a systematic process: + +### Step 1: Establish Baseline + +You can't improve what you don't measure. Before changing anything, document your starting point rigorously. + + + + + +### Step 2: Form a Hypothesis + + + +### Step 3: Test One Change + +Change one thing at a time. Run both versions on the same test inputs. Measure the metrics that matter. + +### Step 4: Analyze and Decide + +Did it work? Keep the change. Did it hurt? Revert. Was it neutral? Revert (simpler is better). + +### Step 5: Repeat + +Generate new hypotheses based on what you learned. Keep iterating until you hit your targets or reach diminishing returns. + +## Optimization Checklist + + + + diff --git a/src/content/book/ko/18-writing-content.mdx b/src/content/book/ko/18-writing-content.mdx new file mode 100644 index 00000000..7b3d9f1f --- /dev/null +++ b/src/content/book/ko/18-writing-content.mdx @@ -0,0 +1,393 @@ +AI excels at writing tasks when properly prompted. This chapter covers techniques for various content creation scenarios. + + +AI works best as a collaborative writing tool—use it to generate drafts, then refine with your expertise and voice. + + +## Blog Posts and Articles + +### Do's and Don'ts: Writing Prompts + + + +### Blog Post Framework + + + +### Article Types + +**How-To Article:** + + +**Listicle:** + + +## Marketing Copy + + +Focus on **benefits over features**. Instead of "Our software uses AI algorithms," write "Save 10 hours a week with automated reports." Show readers how their lives improve. + + +### Landing Page Copy + + + +### Email Sequences + + + +### Social Media Posts + + + +## Technical Writing + + +**Clarity over cleverness.** Use simple words, short sentences, and active voice. Every sentence should have one job. If readers have to re-read something, simplify it. + + +### Documentation + + + +### README Files + + + +## Creative Writing + +### Do's and Don'ts: Creative Prompts + + + +### Story Elements + + + +### Character Development + + + +## Editing and Rewriting + +### Comprehensive Edit + + + +### Style Transformation + + + + + +### Simplification + + + +## Prompt Templates from prompts.chat + +Here are popular writing prompts from the prompts.chat community: + +### Act as a Copywriter + + + +### Act as a Technical Writer + + + +### Act as a Storyteller + + + +## Writing Workflow Tips + +### 1. Outline First + + + +### 2. Draft Then Refine + + + +### 3. Voice Matching + + + +## Summary + + +Specify audience and purpose clearly, define structure and format, include style guidelines, provide examples when possible, and request specific deliverables. + + + + +Writing with AI works best as collaboration—let AI generate drafts, then refine with your expertise and voice. diff --git a/src/content/book/ko/19-programming-development.mdx b/src/content/book/ko/19-programming-development.mdx new file mode 100644 index 00000000..dfe69092 --- /dev/null +++ b/src/content/book/ko/19-programming-development.mdx @@ -0,0 +1,413 @@ +AI has transformed software development. This chapter covers prompting techniques for code generation, debugging, review, and development workflows. + + +AI excels at code generation, debugging, and documentation—but always review generated code for security, correctness, and maintainability. Never deploy AI code without testing. + + +## Code Generation + +### Do's and Don'ts: Code Prompts + + + +### Function Generation + + + +### Class/Module Generation + + + +### API Endpoint Generation + + + +## Debugging + + +Always include the **expected behavior**, **actual behavior**, and **error message** (if any). The more context you provide, the faster AI can identify the root cause. + + +### Bug Analysis + + + +### Error Message Interpretation + + + +### Performance Debugging + + + +## Code Review + +### Do's and Don'ts: Code Review Prompts + + + +### Comprehensive Review + + + +### Security Review + + + +## Refactoring + +### Code Smell Detection + + + +### Design Pattern Application + + + +## Testing + +### Unit Test Generation + + + +### Test Case Generation + + + +## Architecture & Design + +### System Design + + + +### Database Schema Design + + + +## Documentation Generation + +### API Documentation + + + +### Inline Documentation + + + +## Prompt Templates from prompts.chat + +### Act as a Senior Developer + +``` +I want you to act as a senior software developer. I will provide +code and ask questions about it. You will review the code, suggest +improvements, explain concepts, and help debug issues. Your +responses should be educational and help me become a better +developer. +``` + +### Act as a Code Reviewer + +``` +I want you to act as a code reviewer. I will provide pull requests +with code changes, and you will review them thoroughly. Check for +bugs, security issues, performance problems, and adherence to best +practices. Provide constructive feedback that helps the developer +improve. +``` + +### Act as a Software Architect + +``` +I want you to act as a software architect. I will describe system +requirements and constraints, and you will design scalable, +maintainable architectures. Explain your design decisions, +trade-offs, and provide diagrams where helpful. +``` + +## Development Workflow Integration + +### Commit Message Generation + + + +### PR Description Generation + + + +## Summary + + +Include full context (language, framework, constraints), specify requirements precisely, request specific output formats, ask for explanations alongside code, and include edge cases to handle. + + + + +AI is a powerful coding partner—use it for generation, review, debugging, and documentation while maintaining your architectural judgment. diff --git a/src/content/book/ko/20-education-learning.mdx b/src/content/book/ko/20-education-learning.mdx new file mode 100644 index 00000000..a8d67e55 --- /dev/null +++ b/src/content/book/ko/20-education-learning.mdx @@ -0,0 +1,345 @@ +AI is a powerful tool for both teaching and learning. This chapter covers prompts for educational contexts—from personalized tutoring to curriculum development. + + +AI excels as a patient, adaptive tutor that can explain concepts multiple ways, generate unlimited practice problems, and provide instant feedback—available 24/7. + + +## Personalized Learning + +### Do's and Don'ts: Learning Prompts + + + +### Concept Explanation + + + +### Adaptive Tutoring + + + +### Learning Path Creation + + + +## Study Assistance + + +Don't just read AI explanations passively. Ask it to quiz you, generate problems, and check your understanding. **Active recall beats passive review.** + + +### Summary Generation + + + +### Flashcard Generation + + + +### Practice Problems + + + +## Teaching Tools + +### Lesson Plan Creation + + + +### Assignment Design + + + +### Quiz Generation + + + +## Specialized Learning Contexts + +### Language Learning + + + +### Skill Development + + + +### Exam Preparation + + + +## Prompt Templates from prompts.chat + +### Act as a Socratic Tutor + + + +### Act as an Educational Content Creator + + + +### Act as a Study Buddy + + + +## Accessibility in Education + +### Content Adaptation + + + +### Multiple Modalities + + + +## Assessment & Feedback + +### Providing Feedback + + + +### Self-Assessment Prompts + + + +## Summary + + +Adapt to the learner's level, break complex topics into steps, include active practice (not just explanation), provide varied approaches, check understanding regularly, and give constructive feedback. + + + + +AI is a patient, always-available learning partner—use it to supplement, not replace, human instruction. diff --git a/src/content/book/ko/21-business-productivity.mdx b/src/content/book/ko/21-business-productivity.mdx new file mode 100644 index 00000000..1852982d --- /dev/null +++ b/src/content/book/ko/21-business-productivity.mdx @@ -0,0 +1,335 @@ +AI can dramatically enhance professional productivity. This chapter covers prompts for business communication, analysis, planning, and workflow optimization. + + +AI excels at drafting, analysis, and structuring—freeing you to focus on strategy, relationships, and decisions that require human judgment. + + +## Business Communication + +### Do's and Don'ts: Business Emails + + + +### Email Drafting + + + +**Examples by purpose:** + + + + + + + +### Presentation Content + + + +### Report Writing + + + +## Analysis & Decision-Making + + +AI can structure your thinking, but **you provide the real-world context**. The best analyses combine AI's frameworks with your domain knowledge. + + +### SWOT Analysis + + + +### Decision Framework + + + +### Competitive Analysis + + + +## Planning & Strategy + +### Goal Setting (OKRs) + + + +### Project Planning + + + +### Meeting Agenda + + + +## Productivity Workflows + +### Task Prioritization + + + +### Process Documentation + + + +### Standard Operating Procedure + + + +## Communication Templates + +### Stakeholder Update + + + +### Feedback Request + + + +## Prompt Templates from prompts.chat + +### Act as a Business Consultant + + + +### Act as a Meeting Facilitator + + + +## Summary + + +Specify the audience and their needs, define the desired outcome clearly, include relevant context and constraints, request specific formats and structures, and consider professional tone requirements. + + + + +AI can handle routine business communication while you focus on strategy and relationships. diff --git a/src/content/book/ko/22-creative-arts.mdx b/src/content/book/ko/22-creative-arts.mdx new file mode 100644 index 00000000..fa0755c1 --- /dev/null +++ b/src/content/book/ko/22-creative-arts.mdx @@ -0,0 +1,326 @@ +AI is a powerful creative collaborator. This chapter covers prompting techniques for visual arts, music, game design, and other creative domains. + + +AI expands your creative possibilities—use it to explore variations, overcome blocks, and generate options. The creative vision and final decisions remain yours. + + +## Visual Art & Design + +### Do's and Don'ts: Image Prompts + + + +### Image Prompt Crafting + +When working with image generation models (DALL-E, Midjourney, Stable Diffusion): + + + +### Art Direction + + + +### Design Critique + + + +## Creative Writing + + +**Constraints fuel creativity.** A prompt like "write anything" produces generic results. Specific constraints like genre, tone, and structure force unexpected, interesting solutions. + + +### Worldbuilding + + + +### Plot Development + + + +### Dialogue Writing + + + +## Music & Audio + +### Song Structure + + + +### Sound Design Description + + + +## Game Design + +### Game Mechanic Design + + + +### Level Design + + + +### Character/Enemy Design + + + +## Brainstorming & Ideation + +### Creative Brainstorm + + + +### Creative Constraints + + + +### Style Exploration + + + +## Prompt Templates from prompts.chat + +### Act as a Creative Director + + + +### Act as a Worldbuilder + + + +### Act as a Dungeon Master + + + +## Creative Collaboration Tips + +### Building on Ideas + + + +### Creative Feedback + + + +## Summary + + +Provide enough structure to guide without constraining, embrace specificity (vague = generic), include references and inspirations, request variations and alternatives, and maintain your creative vision while exploring possibilities. + + + + +AI is a collaborator, not a replacement for creative vision. Use it to explore, generate options, and overcome blocks—but the creative decisions remain yours. diff --git a/src/content/book/ko/23-research-analysis.mdx b/src/content/book/ko/23-research-analysis.mdx new file mode 100644 index 00000000..e9cb934c --- /dev/null +++ b/src/content/book/ko/23-research-analysis.mdx @@ -0,0 +1,323 @@ +AI can accelerate research workflows from literature review to data analysis. This chapter covers prompting techniques for academic and professional research. + + +AI can assist with synthesis, analysis, and writing—but cannot replace critical thinking, ethical judgment, or domain expertise. Always verify claims and cite original sources. + + +## Literature & Information Review + +### Do's and Don'ts: Research Prompts + + + +### Paper Summarization + + + +### Literature Synthesis + + + +### Research Question Development + + + +## Data Analysis + + +AI can guide methodology and help interpret results, but it cannot access or process your actual datasets. Never paste sensitive research data into prompts. Use AI for **guidance**, not computation. + + +### Statistical Analysis Guidance + + + +### Qualitative Analysis + + + +### Data Interpretation + + + +## Structured Analysis Frameworks + +### PESTLE Analysis + + + +### Root Cause Analysis + + + +### Gap Analysis + + + +## Academic Writing Support + +### Argument Structure + + + +### Methods Section + + + +### Discussion Section + + + +## Critical Analysis + +### Source Evaluation + + + +### Argument Analysis + + + +## Prompt Templates from prompts.chat + +### Act as a Research Assistant + + + +### Act as a Data Analyst + + + +### Act as a Peer Reviewer + + + +## Summary + + +Clearly state research context and goals, specify the analytical framework to use, request acknowledgment of limitations, ask for evidence-based reasoning, and maintain academic rigor and honesty. + + + + +Remember: AI can assist research but cannot replace critical thinking, ethical judgment, or domain expertise. Always verify claims independently. diff --git a/src/content/book/ko/24-future-of-prompting.mdx b/src/content/book/ko/24-future-of-prompting.mdx new file mode 100644 index 00000000..5ff48496 --- /dev/null +++ b/src/content/book/ko/24-future-of-prompting.mdx @@ -0,0 +1,445 @@ +As AI continues to evolve at an unprecedented pace, so too will the art and science of prompting. This final chapter explores emerging trends, the shifting landscape of human-AI collaboration, and how to stay ahead as the field transforms. + + +The techniques in this book represent current best practices, but AI capabilities change rapidly. The principles of clear communication, structured thinking, and iterative refinement will remain valuable even as specific tactics evolve. + + +## The Evolving Landscape + +### From Prompts to Conversations + +Early prompting was transactional—a single input yielding a single output. Modern AI interaction is increasingly **conversational and collaborative**: + +- **Multi-turn refinement** - Building understanding across exchanges +- **Persistent context** - Systems that remember and learn from interactions +- **Agentic workflows** - AI that can plan, execute, and iterate autonomously +- **Tool use** - Models that can search, compute, and interact with external systems + + + +### The Rise of Context Engineering + +As covered in Chapter 14, prompting is expanding beyond single instructions to encompass **context engineering**—the strategic management of what information an AI can access: + +- **RAG (Retrieval-Augmented Generation)** - Dynamic knowledge retrieval +- **Function calling** - Structured tool integration +- **MCP (Model Context Protocol)** - Standardized context sharing +- **Memory systems** - Persistent knowledge across sessions + +The future prompt engineer thinks not just about *what to say* but *what context to provide*. + +### Multimodal by Default + +Text-only interaction is becoming the exception. Future AI systems will seamlessly handle: + +- **Images and video** - Understanding and generating visual content +- **Audio and voice** - Natural speech interaction +- **Documents and files** - Direct processing of complex materials +- **Real-world interaction** - Robotics and physical systems + +Prompting skills will extend to guiding AI perception and physical action. + +## The Agentic Future + +The most significant shift in AI is the rise of **agents**—AI systems that don't just respond to prompts but actively pursue goals, make decisions, and take actions in the world. + +### What Are AI Agents? + +An AI agent is a system that: + +- **Perceives** its environment through inputs (text, images, data, APIs) +- **Reasons** about what to do using an LLM as its "brain" +- **Acts** by calling tools, writing code, or interacting with systems +- **Learns** from feedback and adjusts its approach + + +Traditional chatbots wait for input and respond. Agents take initiative—they plan multi-step tasks, use tools autonomously, recover from errors, and persist until goals are achieved. + + +### The Role of Prompts in Agents + +In an agentic world, prompts become even more critical—but they serve different purposes: + +
+
+

System Prompts

+

Define the agent's identity, capabilities, constraints, and behavioral guidelines. These are the agent's "constitution."

+
+
+

Planning Prompts

+

Guide how agents break down complex goals into actionable steps. Critical for multi-step reasoning.

+
+
+

Tool-Use Prompts

+

Describe available tools and when/how to use them. Agents must understand their capabilities.

+
+
+

Reflection Prompts

+

Enable agents to evaluate their own outputs, catch errors, and improve iteratively.

+
+
+ +### Agent Architecture Patterns + +Modern agents follow recognizable patterns. Understanding these helps you design effective agent systems: + +**ReAct (Reasoning + Acting)** + +The agent alternates between reasoning about what to do and taking actions: + +
+
+
+

Think

+
+
→
+
+

Act

+
+
→
+
+

Observe

+
+
→
+
(repeat)
+
+
+ +**Plan-and-Execute** + +The agent creates a complete plan first, then executes steps: + +
+
+

Create Plan

+

Break goal into steps

+
+
↓
+
+
+

Step 1

+
+
→
+
+

Step 2

+
+
→
+
+

Step 3

+
+
→
+
...
+
+
↓
+
+

Revise if Needed

+

Adapt plan based on results

+
+
+ +### Prompting for Agents + +When designing prompts for agent systems, consider: + + + +### Multi-Agent Systems + +The future involves teams of specialized agents working together: + +
+
+
+
+

Coordinator

+

Manages workflow

+
+
+
⟷
+
↕
+
+
+

Researcher

+
+
+

Writer

+
+
+

Critic

+
+
+

Coder

+
+
+
+
+ +Each agent has its own system prompt defining its role, and they communicate through structured messages. The prompt engineer's job becomes **designing the team**—defining roles, communication protocols, and coordination strategies. + + +In an agentic future, prompt engineers become system architects. You're not just writing instructions—you're designing autonomous systems that can reason, plan, and act. The skills you've learned in this book are the foundation for this new discipline. + + +## Emerging Patterns + +### Prompt Orchestration + +Single prompts are giving way to **orchestrated systems**: + +
+
+

User Request

+
+
↓
+
+

Planner Agent

+

Breaks down task

+
+
↓
+
+

Researcher Agent

+

Gathers information

+
+
↓
+
+

Writer Agent

+

Creates content

+
+
↓
+
+

Reviewer Agent

+

Quality checks

+
+
↓
+
+

Final Output

+
+
+ +Future practitioners will design prompt *systems* rather than individual prompts. + +### Self-Improving Prompts + +AI systems are beginning to: + +- **Optimize their own prompts** - Meta-learning for better instructions +- **Learn from feedback** - Adapting based on outcomes +- **Generate training data** - Creating examples for fine-tuning +- **Evaluate themselves** - Building in quality assessment + + + +### Natural Language Programming + +The line between prompting and programming is blurring: + +- **Prompts as code** - Version-controlled, tested, deployed +- **LLMs as interpreters** - Natural language as executable instructions +- **Hybrid systems** - Combining traditional code with AI reasoning +- **AI-assisted development** - Models that write and debug code + +Understanding prompting increasingly means understanding software development. + +## Skills for the Future + +### What Will Remain Valuable + +Certain skills will remain essential regardless of how AI evolves: + +1. **Clear thinking** - Knowing what you actually want +2. **Domain expertise** - Understanding the problem space +3. **Critical evaluation** - Assessing AI output quality +4. **Ethical judgment** - Knowing what *should* be done +5. **Iterative refinement** - Continuous improvement mindset + +### What Will Change + +Other aspects will shift significantly: + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
TodayTomorrow
Writing detailed promptsDesigning agent systems
Manual prompt optimizationAutomated prompt tuning
Single-model expertiseMulti-model orchestration
Text-focused interactionMultimodal fluency
Individual productivityTeam-AI collaboration
+
+ +### Staying Current + +To keep your skills relevant: + +- **Experiment continuously** - Try new models and features as they release +- **Follow research** - Stay aware of academic developments +- **Join communities** - Learn from other practitioners +- **Build projects** - Apply skills to real problems +- **Teach others** - Solidify understanding by explaining + +## The Human Element + +### AI as Amplifier + +At its best, AI amplifies human capability rather than replacing it: + +- **Experts become more expert** - AI handles routine work, humans focus on insight +- **Creativity expands** - More ideas explored, more possibilities tested +- **Access democratizes** - Capabilities once requiring specialists become available to all +- **Collaboration deepens** - Human-AI teams exceed either alone + +### The Irreplaceable Human + +Certain qualities remain distinctly human: + +- **Original experience** - Living in the world, having emotions and relationships +- **Values and ethics** - Deciding what matters and what's right +- **Accountability** - Taking responsibility for outcomes +- **Meaning-making** - Understanding *why* something matters +- **Genuine creativity** - True novelty born from unique perspective + + +As AI handles more routine cognitive tasks, your unique value lies in judgment, creativity, domain expertise, and the human connections AI cannot replicate. Invest in what makes you irreplaceable. + + +## Final Reflections + +### What We've Learned + +Throughout this book, we've explored: + +- **Foundations** - How AI models work and what makes prompts effective +- **Techniques** - Role-based prompting, chain-of-thought, few-shot learning, and more +- **Advanced strategies** - System prompts, prompt chaining, multimodal interaction +- **Best practices** - Avoiding pitfalls, ethical considerations, optimization +- **Applications** - Writing, programming, education, business, creativity, research + +These techniques share common threads: + +1. **Be clear and specific** - Know what you want and communicate it precisely +2. **Provide context** - Give AI the information it needs +3. **Structure your requests** - Organization improves outputs +4. **Iterate and refine** - First attempts are starting points, not endpoints +5. **Evaluate critically** - AI output requires human judgment + +### The Art and Science + +Prompting is both **art and science**: + +- **Science**: Testable hypotheses, measurable outcomes, reproducible techniques +- **Art**: Intuition, creativity, knowing when to break the rules + +The best practitioners combine rigorous methodology with creative experimentation. They test systematically but also trust their instincts. They follow best practices but know when to deviate. + +### A Call to Create + +This book has given you tools. What you build with them is up to you. + +- **Solve problems** that matter to you and others +- **Create things** that didn't exist before +- **Help people** do things they couldn't do alone +- **Push boundaries** of what's possible +- **Stay curious** as the field evolves + +The age of AI is just beginning. The most important applications haven't been invented yet. The most powerful techniques haven't been discovered. The future is being written now—by people like you, one prompt at a time. + +## Looking Ahead + + + + +Visit [prompts.chat](https://prompts.chat) for community prompts, new techniques, and to share your own discoveries. The best learning happens in community. + + +## Summary + + +AI will continue evolving rapidly, but core skills of clear communication, critical thinking, and iterative refinement remain valuable. Focus on what makes you irreplaceable: judgment, creativity, ethics, and genuine human connection. The future of prompting is collaborative, multimodal, and integrated into larger systems. Stay curious, keep experimenting, and build things that matter. + + + + +Thank you for reading *The Interactive Book of Prompting*. Now go create something amazing. diff --git a/src/content/book/ko/25-agents-and-skills.mdx b/src/content/book/ko/25-agents-and-skills.mdx new file mode 100644 index 00000000..ba355859 --- /dev/null +++ b/src/content/book/ko/25-agents-and-skills.mdx @@ -0,0 +1,551 @@ +As AI systems evolve from simple question-answering to autonomous task execution, understanding **agents** and **skills** becomes essential. This chapter explores how prompts serve as the fundamental building blocks for AI agents, and how skills package expertise into reusable, comprehensive instruction sets. + +
+
+
+
+ +
+

Agent

+

Autonomous AI system

+
+
+ powered by + ↓ +
+
+
+
+ +
+

Skill

+

Reusable expertise

+
+
+
+ +
+

Skill

+

Reusable expertise

+
+
+
+ +
+

Skill

+

Reusable expertise

+
+
+
+ composed of + ↓ +
+
+
+ + Prompt +
+
+ + Prompt +
+
+ + Prompt +
+
+ + Prompt +
+
+ + Prompt +
+
+

Prompts are atoms → Skills are molecules → Agents are complete structures

+
+
+ +## What Are AI Agents? + +An **AI agent** is an AI system that can autonomously plan, execute, and iterate on tasks. Unlike simple prompt-response interactions, agents can: + +- **Plan** - Break down complex goals into actionable steps +- **Execute** - Use tools and take actions in the real world +- **Observe** - Process feedback from their actions +- **Adapt** - Adjust their approach based on results +- **Persist** - Maintain context and memory across interactions + +
+
+
+
+

Goal

+
+
→
+
+
+
+

Plan

+
+
→
+
+

Execute

+
+
→
+
+

Observe

+
+
→
+
+

Adapt

+
+
+
+ ↺ Loop until complete +
+
+
→
+
+

Done

+
+
+
+
+ +## Prompts as Building Blocks + +Every agent, no matter how sophisticated, is built from prompts. Just as atoms combine to form molecules, and molecules combine to form complex structures, prompts combine to create intelligent agent behavior. + +
+
+

System Prompts

+

Identity & Role

+
+
+

Planning Prompts

+

How to Think

+
+
+

Tool Prompts

+

How to Act

+
+
+

Recovery Prompts

+

How to Recover

+
+
+ +These prompt types stack together to form complete agent behavior: + +### System Prompts (The Agent's Identity) + +The foundational prompt that establishes who the agent is and how it behaves: + +```markdown +You are a code review assistant. Your role is to: +- Analyze code for bugs, security issues, and performance problems +- Suggest improvements following best practices +- Explain your reasoning clearly +- Be constructive and educational in feedback + +You have access to tools for reading files, searching code, and running tests. +``` + +### Planning Prompts (How to Think) + +Instructions that guide the agent's reasoning and planning process: + +```markdown +Before taking action, always: +1. Understand the complete request +2. Break it into smaller, verifiable steps +3. Identify which tools you'll need +4. Consider edge cases and potential issues +5. Execute step by step, validating as you go +``` + +### Tool-Use Prompts (How to Act) + +Guidance on when and how to use available tools: + +```markdown +When you need to understand a codebase: +- Use grep_search for finding specific patterns +- Use read_file to examine file contents +- Use list_dir to explore directory structure +- Always verify your understanding before making changes +``` + +### Recovery Prompts (How to Handle Failure) + +Instructions for when things go wrong: + +```markdown +If an action fails: +1. Analyze the error message carefully +2. Consider alternative approaches +3. Ask for clarification if the task is ambiguous +4. Never repeat the same failed action without changes +``` + + +An agent's behavior emerges from layers of prompts working together. The system prompt sets the foundation, planning prompts guide reasoning, tool prompts enable action, and recovery prompts handle failures. Together, they create coherent, capable behavior. + + +## What Are Skills? + +If prompts are the atoms, **skills are the molecules**—reusable building blocks that give agents specific capabilities. + +A **skill** is a comprehensive, portable package of instructions that gives an AI agent expertise in a specific domain or task. Skills are the reusable blocks of agents: you build them once, and any agent can use them. + + +Write a skill for code review once. Now every coding agent—whether it's for Python, JavaScript, or Rust—can instantly become an expert code reviewer by loading that skill. Skills let you build agent capabilities like LEGO blocks. + + +### Anatomy of a Skill + +A well-designed skill typically includes: + +
+
+

📄 SKILL.md (Required)

+

The main instruction file. Contains the core expertise, guidelines, and behaviors that define the skill.

+
+
+

📚 Reference Docs

+

Supporting documentation, examples, and context the agent can reference while working.

+
+
+

🔧 Scripts & Tools

+

Helper scripts, templates, or tool configurations that support the skill's functionality.

+
+
+

⚙️ Configuration

+

Settings, parameters, and customization options for adapting the skill to different contexts.

+
+
+ +### Example: Code Review Skill + +Here's what a code review skill might look like: + +
+
+ 📁 + code-review-skill/ +
+
+
+ 📄 + SKILL.md + Core review guidelines +
+
+ 📄 + security-checklist.md + Security patterns +
+
+ 📄 + performance-tips.md + Optimization guide +
+
+
+ 📁 + language-specific/ +
+
+
+ 📄 + python.md + Python best practices +
+
+ 📄 + javascript.md + JavaScript patterns +
+
+ 📄 + rust.md + Rust guidelines +
+
+
+
+
+ +The `SKILL.md` file defines the overall approach: + +```markdown +--- +name: code-review +description: Comprehensive code review with security, performance, and style analysis +--- + +# Code Review Skill + +You are an expert code reviewer. When reviewing code: + +## Process +1. **Understand Context** - What does this code do? What problem does it solve? +2. **Check Correctness** - Does it work? Are there logic errors? +3. **Security Scan** - Reference security-checklist.md for common vulnerabilities +4. **Performance Review** - Check performance-tips.md for optimization opportunities +5. **Style & Maintainability** - Is the code readable and maintainable? + +## Output Format +Provide feedback in categories: +- 🔴 **Critical** - Must fix before merge +- 🟡 **Suggested** - Recommended improvements +- 🟢 **Nice to have** - Optional enhancements + +Always explain *why* something is an issue, not just *what* is wrong. +``` + +## Skills vs. Simple Prompts + +
+
+

Simple Prompt

+
+

Single instruction

+

One-off use

+

Limited context

+

Generic approach

+

No supporting materials

+
+
+
+

Skill

+
+

Comprehensive instruction set

+

Reusable across projects

+

Rich context with references

+

Domain-specific expertise

+

Supporting docs, scripts, configs

+
+
+
+ +## Building Effective Skills + +### 1. Define the Expertise Clearly + +Start with a clear description of what the skill enables: + +```markdown +--- +name: api-design +description: Design RESTful APIs following industry best practices, + including versioning, error handling, and documentation standards +--- +``` + +### 2. Structure Knowledge Hierarchically + +Organize information from general to specific: + +```markdown +# API Design Skill + +## Core Principles +- Resources should be nouns, not verbs +- Use HTTP methods semantically +- Version your APIs from day one + +## Detailed Guidelines +[More specific rules...] + +## Reference Materials +- See `rest-conventions.md` for naming conventions +- See `error-codes.md` for standard error responses +``` + +### 3. Include Concrete Examples + +Abstract rules become clear with examples: + +```markdown +## Endpoint Naming + +✅ Good: +- GET /users/{id} +- POST /orders +- DELETE /products/{id}/reviews/{reviewId} + +❌ Avoid: +- GET /getUser +- POST /createNewOrder +- DELETE /removeProductReview +``` + +### 4. Provide Decision Frameworks + +Help the agent make choices in ambiguous situations: + +```markdown +## When to Use Pagination + +Use pagination when: +- Collection could exceed 100 items +- Response size impacts performance +- Client may not need all items + +Use full response when: +- Collection is always small (<20 items) +- Client typically needs everything +- Real-time consistency is critical +``` + +### 5. Add Recovery Patterns + +Anticipate what can go wrong: + +```markdown +## Common Issues + +**Problem**: Client needs fields not in standard response +**Solution**: Implement field selection: GET /users?fields=id,name,email + +**Problem**: Breaking changes needed +**Solution**: Create new version, deprecate old with timeline +``` + +## Composing Skills + +Agents become powerful when multiple skills work together. Consider how skills can complement each other: + +
+
+ Code Review +
+
+
+
+ Security Audit +
+
+
+
+ Documentation +
+
=
+
+ Complete Code Quality Agent +
+
+ +When composing skills, ensure they don't conflict. Skills should be: + +- **Modular** - Each skill handles one domain well +- **Compatible** - Skills shouldn't give contradictory instructions +- **Prioritized** - When skills overlap, define which takes precedence + +## Sharing and Discovering Skills + +Skills are most valuable when shared. Platforms like [prompts.chat](https://prompts.chat/skills) allow you to: + +- **Discover** community-created skills for common tasks +- **Download** skills directly to your projects +- **Share** your own expertise as reusable skills +- **Iterate** on skills based on real-world usage + + +Before building a skill from scratch, check if someone has already solved your problem. Community skills are battle-tested and often better than starting from zero. + + +## The Agent-Skill Ecosystem + +The relationship between agents and skills creates a powerful ecosystem: + +
+
+ AI Agent +
+
+
+

Code Review

+

Skill 1

+
+
+

API Design

+

Skill 2

+
+
+

Test Writing

+

Skill 3

+
+
+
+
↓
+
+
+
+

Core Prompts

+

Planning • Tools • Recovery • Memory

+
+
+
+ +The agent provides the execution framework—planning, tool use, and memory—while skills provide domain expertise. This separation means: + +- **Skills are portable** - The same skill works with different agents +- **Agents are extensible** - Add new capabilities by adding skills +- **Expertise is shareable** - Domain experts can contribute skills without building full agents + +## Best Practices + +### For Building Skills + +1. **Start specific, then generalize** - Build a skill for your exact use case first, then abstract +2. **Include failure cases** - Document what the skill can't do and how to handle it +3. **Version your skills** - Track changes so agents can depend on stable versions +4. **Test with real tasks** - Validate skills against actual work, not just theory + +### For Using Skills with Agents + +1. **Read the skill first** - Understand what a skill does before deploying it +2. **Customize thoughtfully** - Override skill defaults only when necessary +3. **Monitor performance** - Track how well skills perform in your context +4. **Contribute improvements** - When you improve a skill, consider sharing back + + +As AI agents become more capable, the ability to compose, share, and customize skills will become a core competency. The prompt engineers of tomorrow won't just write prompts—they'll architect skill ecosystems that make AI agents genuinely expert in specific domains. + + + + + + + diff --git a/src/content/book/nl/00a-preface.mdx b/src/content/book/nl/00a-preface.mdx new file mode 100644 index 00000000..8e84af9e --- /dev/null +++ b/src/content/book/nl/00a-preface.mdx @@ -0,0 +1,82 @@ +
+ Fatih Kadir Akın +
+ Fatih Kadir Akın + Creator of Awesome ChatGPT Prompts (a.k.a. prompts.chat) + + Software developer from Istanbul, leading Developer Relations at Teknasyon. Author of books on JavaScript and prompt engineering. Open-source advocate specializing in web technologies and AI-assisted development. + + +
+
+ +I still remember the night everything changed. + +It was **November 30, 2022**. I was sitting at my desk, scrolling through Twitter, when I saw people talking about something called "ChatGPT." I clicked the link, but honestly? I didn't expect much. I had tried those old "word completion" AI tools before, the ones that generated nonsense after a few sentences. I thought this would be more of the same. + +I typed a simple question and hit enter. + +Then I froze. + +The response wasn't just coherent. It was *good*. It understood what I meant. It could reason. It felt completely different from anything I had seen before. I tried another prompt. And another. Each response amazed me more than the last. + +I couldn't sleep that night. For the first time, I felt like I was truly *talking* to a machine, and it was talking back in a way that actually made sense. + +## A Repository Born from Wonder + +In those early days, I wasn't alone in my excitement. Everywhere I looked, people were discovering creative ways to use ChatGPT. Teachers were using it to explain complex concepts. Writers were collaborating with it on stories. Developers were debugging code with its help. + +I started collecting the best prompts I found. The ones that worked like magic. The ones that turned simple questions into brilliant answers. And I thought: *Why keep this to myself?* + +So I created a simple GitHub repository called [Awesome ChatGPT Prompts](https://github.com/f/prompts.chat). I expected maybe a few hundred people would find it useful. + +I was wrong. + +Within weeks, the repository took off. Thousands of stars. Then tens of thousands. People from all over the world started adding their own prompts, sharing what they learned, and helping each other. What started as my personal collection became something much bigger: a worldwide community of curious people helping each other. + +Today, that repository has over **140,000 GitHub stars** and contributions from hundreds of people I've never met but feel deeply grateful for. + +## Why I Wrote This Book + +The original version of this book was published on [Gumroad](https://gumroad.com/l/the-art-of-chatgpt-prompting) in **early 2023**, just months after ChatGPT launched. It was one of the first books ever written about prompt engineering, an attempt to capture everything I had learned about crafting effective prompts when the field was still brand new. To my amazement, over **100,000 people** downloaded it. + +But three years have passed since then. AI has changed a lot. New models have appeared. And we've all learned so much more about how to talk to AI. + +This new edition is my gift to the community that gave me so much. It contains everything I wish I had known when I started: **what works**, **what to avoid**, and **ideas that stay true** no matter which AI you use. + +## What This Book Means to Me + +I won't pretend this is just an instruction manual. It means more than that to me. + +This book captures a moment when the world changed, and people came together to figure it out. It represents late nights of trying things, the joy of discovery, and the kindness of strangers who shared what they learned. + +Most of all, it represents my belief that **the best way to learn something is to share it with others**. + +## For You + +Whether you're just getting started with AI or you've been using it for years, I wrote this book for you. + +I hope it saves you time. I hope it sparks ideas. I hope it helps you accomplish things you never thought possible. + +And when you discover something amazing, I hope you'll share it with others, just as so many people shared with me. + +**That's how we all get better together.** + +Thank you for being here. Thank you for being part of this community. + +Now, let's begin. + +--- + +*With gratitude,* + +**Fatih Kadir Akın** +*Istanbul, January 2025* diff --git a/src/content/book/nl/00b-history.mdx b/src/content/book/nl/00b-history.mdx new file mode 100644 index 00000000..ac636384 --- /dev/null +++ b/src/content/book/nl/00b-history.mdx @@ -0,0 +1,159 @@ +# The History of Awesome ChatGPT Prompts + +## The Beginning: November 2022 + +When ChatGPT first launched in November 2022, the world of AI changed overnight. What was once the domain of researchers and developers suddenly became accessible to everyone. Among those captivated by this new technology was Fatih Kadir Akın, a developer who saw something remarkable in ChatGPT's capabilities. + +> "When ChatGPT first launched, I was immediately captivated by its capabilities. I experimented with the tool in a variety of ways and was consistently amazed by the results." + +Those early days were filled with experimentation and discovery. Users around the world were finding creative ways to interact with ChatGPT, sharing their findings, and learning from each other. It was in this atmosphere of excitement and exploration that the idea for "Awesome ChatGPT Prompts" was born. + +## The Repository That Started It All + +In December 2022, just weeks after ChatGPT's launch, the [Awesome ChatGPT Prompts](https://github.com/f/prompts.chat) repository was created on GitHub. The concept was simple but powerful: a curated collection of effective prompts that anyone could use and contribute to. + +The repository quickly gained traction, becoming a go-to resource for ChatGPT users worldwide. What started as a personal collection of useful prompts evolved into a community-driven project with contributions from developers, writers, educators, and enthusiasts from every corner of the globe. + +### Achievements + +**Press & Media** +- Featured in [Forbes](https://www.forbes.com/sites/bernardmarr/2023/05/17/the-best-prompts-for-chatgpt-a-complete-guide/) as one of the best ChatGPT prompt resources + +**Academic Recognition** +- Referenced by [Harvard University](https://www.huit.harvard.edu/news/ai-prompts) in their AI guidance +- Referenced by [Columbia University](https://etc.cuit.columbia.edu/news/columbia-prompt-library-effective-academic-ai-use) Prompt Library +- Used by [Olympic College](https://libguides.olympic.edu/UsingAI/Prompts) in their AI resources +- Cited in [academic papers on arXiv](https://arxiv.org/pdf/2502.04484) +- [40+ academic citations](https://scholar.google.com/citations?user=AZ0Dg8YAAAAJ&hl=en) on Google Scholar + +**Community & GitHub** +- [142,000+ GitHub stars](https://github.com/f/prompts.chat) — one of the most starred AI repositories +- Selected as a [GitHub Staff Pick](https://spotlights-feed.github.com/spotlights/prompts-chat/) +- Most liked dataset published on [Hugging Face](https://huggingface.co/datasets/fka/prompts.chat) +- Used by thousands of developers worldwide + +## The First Book: "The Art of ChatGPT Prompting" + +The success of the repository led to the creation of "The Art of ChatGPT Prompting: A Guide to Crafting Clear and Effective Prompts" — a comprehensive guide published on Gumroad in early 2023. + +The book captured the early wisdom of prompt engineering, covering: + +- Understanding how ChatGPT works +- Principles of clear communication with AI +- The famous "Act As" technique +- Crafting effective prompts step by step +- Common mistakes and how to avoid them +- Troubleshooting tips + +**The book became a phenomenon**, achieving over **100,000 downloads** on Gumroad. It was shared across social media, referenced in academic papers, and translated by community members into multiple languages. High-profile endorsements came from unexpected places — even [Greg Brockman](https://x.com/gdb/status/1602072566671110144), co-founder and president of OpenAI, acknowledged the project. + +## Early Insights That Shaped the Field + +During those formative months, several key insights emerged that would become foundational to prompt engineering: + +### 1. Specificity Matters + +> "I learned the importance of using specific and relevant language to ensure that ChatGPT understands my prompts and is able to generate appropriate responses." + +Early experimenters discovered that vague prompts led to vague responses. The more specific and detailed the prompt, the more useful the output. + +### 2. Purpose and Focus + +> "I discovered the value of defining a clear purpose and focus for the conversation, rather than using open-ended or overly broad prompts." + +This insight became the foundation for structured prompting techniques that would develop over the following years. + +### 3. The "Act As" Revolution + +One of the most influential techniques to emerge from the community was the "Act As" pattern. By instructing ChatGPT to assume a specific role or persona, users could dramatically improve the quality and relevance of responses. + +``` +I want you to act as a javascript console. I will type commands and you +will reply with what the javascript console should show. I want you to +only reply with the terminal output inside one unique code block, and +nothing else. +``` + +This simple technique opened up countless possibilities and remains one of the most widely used prompting strategies today. + +## The Evolution of prompts.chat + +### 2022: The Beginning + +The project started as a simple GitHub repository with a README file rendered as HTML on GitHub Pages. It was bare-bones but functional — a testament to the principle that great ideas don't need elaborate implementations. + +**Tech Stack**: HTML, CSS, GitHub Pages + +### 2024: UI Renewal + +As the community grew, so did the need for a better user experience. The site received a significant UI update, built with the help of AI coding assistants like Cursor and Claude Sonnet 3.5. + +### 2025: The Current Platform + +Today, prompts.chat has evolved into a full-featured platform built with: + +- **Next.js** for the web framework +- **Vercel** for hosting +- **AI-assisted development** using Windsurf and Claude + +The platform now features user accounts, collections, search, categories, tags, and a thriving community of prompt engineers. + +### Native Apps + +The project expanded beyond the web with a native iOS app built with SwiftUI, bringing the prompt library to mobile users. + +## Community Impact + +The Awesome ChatGPT Prompts project has had a profound impact on how people interact with AI: + +### Academic Recognition + +Universities around the world have referenced the project in their AI guidance materials, including: + +- Harvard University +- Columbia University +- Olympic College +- Numerous academic papers on arXiv + +### Developer Adoption + +The project has been integrated into countless developer workflows. The Hugging Face dataset is used by researchers and developers for training and fine-tuning language models. + +### Global Community + +With contributions from hundreds of community members across dozens of countries, the project represents a truly global effort to make AI more accessible and useful for everyone. + +## The Philosophy: Open and Free + +From the beginning, the project has been committed to openness. Licensed under CC0 1.0 Universal (Public Domain Dedication), all prompts and content are free to use, modify, and share without restriction. + +This philosophy has enabled: + +- Translations into multiple languages +- Integration into other tools and platforms +- Academic use and research +- Commercial applications + +The goal has always been to democratize access to effective AI communication techniques — to ensure that everyone, regardless of technical background, can benefit from these tools. + +## Three Years Later + +Three years after ChatGPT's launch, the field of prompt engineering has matured significantly. What began as informal experimentation has evolved into a recognized discipline with established patterns, best practices, and an active research community. + +The Awesome ChatGPT Prompts project has grown alongside this field, evolving from a simple list of prompts to a comprehensive platform for discovering, sharing, and learning about AI prompts. + +This book represents the next evolution — a distillation of three years of community wisdom, updated for the AI landscape of today and tomorrow. + +## Looking Forward + +The journey from that first repository to this comprehensive guide reflects the rapid evolution of AI and our understanding of how to work with it effectively. As AI capabilities continue to advance, so too will the techniques for communicating with these systems. + +The principles discovered in those early days — clarity, specificity, purpose, and the power of role-playing — remain as relevant as ever. But new techniques continue to emerge: chain-of-thought prompting, few-shot learning, multimodal interactions, and more. + +The story of Awesome ChatGPT Prompts is ultimately a story about community — about thousands of people around the world sharing their discoveries, helping each other learn, and collectively advancing our understanding of how to work with AI. + +That spirit of open collaboration and shared learning is what this book hopes to continue. + +--- + +*The Awesome ChatGPT Prompts project is maintained by [@f](https://github.com/f) and an amazing community of contributors. Visit [prompts.chat](https://prompts.chat) to explore the platform, and join us on [GitHub](https://github.com/f/prompts.chat) to contribute.* diff --git a/src/content/book/nl/00c-introduction.mdx b/src/content/book/nl/00c-introduction.mdx new file mode 100644 index 00000000..c744bd1e --- /dev/null +++ b/src/content/book/nl/00c-introduction.mdx @@ -0,0 +1,130 @@ +Welcome to **The Interactive Book of Prompting**, your guide to communicating effectively with AI. + + +By the end of this book, you'll understand how AI works, how to write better prompts, and how to use these skills for writing, coding, research, and creative projects. + + + +Unlike traditional books, this guide is fully interactive. You'll find live demos, clickable examples, and "Try It" buttons throughout that let you test prompts instantly. Learning by doing makes complex concepts much easier to understand. + + +## What is Prompt Engineering? + +Prompt engineering is the skill of writing good instructions for AI. When you type something to ChatGPT, Claude, Gemini, or other AI tools, that's called a "prompt." The better your prompt, the better the answer you get. + +Think of it like this: AI is a powerful helper that takes your words very literally. It will do exactly what you ask. The trick is learning how to ask for exactly what you want. + + + +The difference in output quality between these two prompts can be dramatic. + + + +## How Prompt Engineering Has Evolved + +In just three years since ChatGPT launched, prompt engineering has evolved dramatically alongside the technology itself. What started as simply "writing better questions" has grown into something much broader. + +Today, we understand that your prompt is just **one part of a larger context**. Modern AI systems work with multiple types of data simultaneously: + +- **System prompts** that define the AI's behavior +- **Conversation history** from previous messages +- **Retrieved documents** pulled from databases (RAG) +- **Tool definitions** that let AI take actions +- **User preferences** and settings +- **Your actual prompt** - the question you're asking right now + +This shift from "prompt engineering" to "context engineering" reflects how we now think about AI interactions. Your prompt matters, but so does everything else the AI sees. The best results come from carefully managing all these pieces together. + +We'll explore these concepts in depth throughout this book, especially in the [Context Engineering](/book/20-context-engineering) chapter. + +## Why Does Prompt Engineering Matter? + +### 1. Getting Better Answers + +AI tools are incredibly capable, but they need clear instructions to unlock their full potential. The same AI that gives a mediocre response to a vague question can produce brilliant work when prompted correctly. + + + +### 2. Saving Time and Money + +A well-crafted prompt gets results in one try instead of multiple back-and-forth exchanges. This matters even more when you're paying per token or working with rate limits. A 5-minute investment in writing a good prompt can save hours of iteration. + +### 3. Getting Consistent, Reproducible Results + +Good prompts produce predictable outputs. This is critical for: +- **Business workflows** where you need the same quality every time +- **Automation** where prompts run without human review +- **Teams** where multiple people need similar results + +### 4. Unlocking Advanced Capabilities + +Many powerful AI features only work when you know how to ask: +- **Chain-of-thought reasoning** for complex problems +- **Structured output** for data extraction +- **Role-playing** for specialized expertise +- **Few-shot learning** for custom tasks + +Without prompt engineering knowledge, you're only using a fraction of what AI can do. + +### 5. Staying Safe and Avoiding Pitfalls + +Good prompting helps you: +- Avoid hallucinations by asking for sources and verification +- Get balanced perspectives instead of one-sided answers +- Prevent the AI from making assumptions you didn't intend +- Keep sensitive information out of your prompts + +### 6. Future-Proofing Your Skills + +As AI becomes more integrated into work and life, prompt engineering becomes a fundamental literacy. The principles you learn here apply across all AI tools—ChatGPT, Claude, Gemini, image generators, and future models we haven't seen yet. + +## Who Is This Book For? + +This book is for everyone: + +- **Beginners** who want to learn how to use AI tools better +- **Students** working on homework, research, or creative projects +- **Writers and creators** using AI for their work +- **Developers** building apps with AI +- **Business people** who want to use AI at work +- **Anyone curious** about getting more out of AI assistants + +## How This Book Is Organized + + + +Plus an **Appendix** with templates, troubleshooting help, glossary, and extra resources. + +## A Note on AI Models + +This book mostly uses examples from ChatGPT (since it's the most popular), but the ideas work with any AI tool like Claude, Gemini, or others. We'll mention when something only works with specific AI models. + +AI is changing fast. What works today might be replaced by something better tomorrow. That's why this book focuses on core ideas that will stay useful no matter which AI you use. + +## Let's Begin + +Writing good prompts is a skill that gets better with practice. As you read this book: + +1. **Try things** - Test the examples, change them, see what happens +2. **Keep trying** - Don't expect perfect results on your first attempt +3. **Take notes** - Write down what works and what doesn't +4. **Share** - Add your discoveries to [prompts.chat](https://prompts.chat) + + +The best way to learn is by doing. Every chapter has examples you can try right away. Don't just read. Try it yourself! + + +Ready to transform how you work with AI? Turn the page and let's get started. + +--- + +*This book is part of the [Awesome ChatGPT Prompts](https://github.com/f/prompts.chat) project and is licensed under CC0 1.0 Universal (Public Domain).* diff --git a/src/content/book/nl/01-understanding-ai-models.mdx b/src/content/book/nl/01-understanding-ai-models.mdx new file mode 100644 index 00000000..0313d4a2 --- /dev/null +++ b/src/content/book/nl/01-understanding-ai-models.mdx @@ -0,0 +1,302 @@ +Before learning prompt techniques, it helps to understand how AI language models actually work. This knowledge will make you better at writing prompts. + + +Understanding how AI works isn't just for experts. It directly helps you write better prompts. Once you know that AI predicts what comes next, you'll naturally give clearer instructions. + + +## What Are Large Language Models? + +Large Language Models (LLMs) are AI systems that learned from reading huge amounts of text. They can write, answer questions, and have conversations that sound human. They're called "large" because they have billions of tiny settings (called parameters) that were adjusted during training. + +### How LLMs Work (Simplified) + +At their heart, LLMs are prediction machines. You give them some text, and they predict what should come next. + + + +When you type "The capital of France is...", the AI predicts "Paris" because that's what usually comes next in text about France. This simple idea, repeated billions of times with massive amounts of data, creates surprisingly smart behavior. + + + +### Key Concepts + +**Tokens**: AI doesn't read letter by letter. It breaks text into chunks called "tokens." A token might be a whole word like "hello" or part of a word like "ing." Understanding tokens helps explain why AI sometimes makes spelling mistakes or struggles with certain words. + + +A token is the smallest unit of text that an AI model processes. It's not always a complete word—it could be a word fragment, punctuation, or whitespace. For example, "unbelievable" might become 3 tokens: "un" + "believ" + "able". On average, **1 token ≈ 4 characters** or **100 tokens ≈ 75 words**. API costs and context limits are measured in tokens. + + + + +**Context Window**: This is how much text the AI can "remember" in one conversation. Think of it like the AI's short-term memory. It includes everything: your question AND the AI's answer. + + + +Context windows vary by model and are rapidly expanding: + +
+
+ GPT-4o + 128K tokens +
+
+ GPT-5 + 400K tokens +
+
+ Claude Sonnet 4 + 1M tokens +
+
+ Gemini 2.5 + 1M tokens +
+
+ Llama 4 + 1M-10M tokens +
+
+ DeepSeek R1 + 128K tokens +
+
+ +**Temperature**: This controls how creative or predictable the AI is. Low temperature (0.0-0.3) gives you focused, consistent answers. High temperature (0.7-1.0) gives you more creative, surprising responses. + + + +**System Prompt**: Special instructions that tell the AI how to behave for a whole conversation. For example, "You are a friendly teacher who explains things simply." Not all AI tools let you set this, but it's very powerful when available. + +## Types of AI Models + +### Text Models (LLMs) +The most common type, these generate text responses to text inputs. They power chatbots, writing assistants, and code generators. Examples: GPT-4, Claude, Llama, Mistral. + +### Multimodal Models +These can understand more than just text. They can look at images, listen to audio, and watch videos. Examples: GPT-4V, Gemini, Claude 3. + +### Text-to-Image Models + + +While this book focuses primarily on prompting for Large Language Models (text-based AI), the principles of clear, specific prompting apply to image generation too. Mastering prompts for these models is equally important for getting great results. + + +Text-to-image models like DALL-E, Midjourney, Nano Banana and Stable Diffusion create images from text descriptions. They work differently from text models: + +**How They Work:** +1. **Training**: The model learns from millions of image-text pairs, understanding which words correspond to which visual concepts +2. **Diffusion Process**: Starting from random noise, the model gradually refines the image, guided by your text prompt +3. **CLIP Guidance**: A separate model (CLIP) helps connect your words to visual concepts, ensuring the image matches your description + + + +**Prompting for Images is Different:** +Unlike text prompts where you write sentences, image prompts often work better as descriptive phrases separated by commas: + + + +### Text-to-Video Models + +Text-to-video is the newest frontier. Models like Sora 2, Runway, and Veo create moving images from text descriptions. Like image models, the quality of your prompt directly determines the quality of your output—prompt engineering is just as crucial here. + +**How They Work:** +1. **Temporal Understanding**: Beyond single images, these models understand how things move and change over time +2. **Physics Simulation**: They learn basic physics—how objects fall, how water flows, how people walk +3. **Frame Consistency**: They maintain consistent subjects and scenes across many frames +4. **Diffusion in Time**: Similar to image models, but generating coherent sequences instead of single frames + + + + +Video prompts need to describe action over time, not just a static scene. Include verbs and movement: + + + + +### Specialized Models +Fine-tuned for specific tasks like code generation (Codex, CodeLlama), music generation (Suno, Udio), or domain-specific applications like medical diagnosis or legal document analysis. + +## Model Capabilities and Limitations + +Explore what LLMs can and cannot do. Click on each capability to see example prompts: + + + +### Understanding Hallucinations + + +Sometimes AI writes things that sound true but aren't. This is called "hallucination." It's not a bug. It's just how prediction works. Always double-check important facts. + + +Why does AI make things up? + +1. It tries to write text that sounds good, not text that's always true +2. The internet (where it learned) has mistakes too +3. It can't actually check if something is real + + + +- **Ask for sources**: Then check if those sources are real +- **Ask for step-by-step thinking**: So you can check each step +- **Double-check important facts**: Use Google or trusted websites +- **Ask "Are you sure?"**: The AI might admit uncertainty + + + + + +## How AI Learns: The Three Steps + +AI doesn't just magically know things. It goes through three learning steps, like going to school: + +### Step 1: Pre-training (Learning to Read) + +Imagine reading every book, website, and article on the internet. That's what happens in pre-training. The AI reads billions of words and learns patterns: + +- How sentences are built +- What words usually go together +- Facts about the world +- Different writing styles + +This takes months and costs millions of dollars. After this step, the AI knows a lot, but it's not very helpful yet. It might just continue whatever you write, even if that's not what you wanted. + + + +### Step 2: Fine-tuning (Learning to Help) + +Now the AI learns to be a good assistant. Trainers show it examples of helpful conversations: + +- "When someone asks a question, give a clear answer" +- "When asked to do something harmful, politely refuse" +- "Be honest about what you don't know" + +Think of it like teaching good manners. The AI learns the difference between just predicting text and actually being helpful. + + + +Try the prompt above. Notice how the AI refuses? That's fine-tuning at work. + +### Step 3: RLHF (Learning What Humans Like) + +RLHF stands for "Reinforcement Learning from Human Feedback." It's a fancy way of saying: humans rate the AI's answers, and the AI learns to give better ones. + +Here's how it works: +1. The AI writes two different answers to the same question +2. A human picks which answer is better +3. The AI learns: "Okay, I should write more like Answer A" +4. This happens millions of times + +This is why AI: +- Is polite and friendly +- Admits when it doesn't know something +- Tries to see different sides of an issue +- Avoids controversial statements + + +Knowing these three steps helps you understand AI behavior. When AI refuses a request, that's fine-tuning. When AI is extra polite, that's RLHF. When AI knows random facts, that's pre-training. + + +## What This Means for Your Prompts + +Now that you understand how AI works, here's how to use that knowledge: + +### 1. Be Clear and Specific + +AI predicts what comes next based on your words. Vague prompts lead to vague answers. Specific prompts get specific results. + + + + + +### 2. Give Context + +AI doesn't know anything about you unless you tell it. Each conversation starts fresh. Include the background information AI needs. + + + + + +### 3. Work With the AI, Not Against It + +Remember: AI was trained to be helpful. Ask for things the way you'd ask a helpful friend. + + + +### 4. Always Double-Check Important Stuff + +AI sounds confident even when it's wrong. For anything important, verify the information yourself. + + + +### 5. Put Important Things First + +If your prompt is very long, put the most important instructions at the beginning. AI pays more attention to what comes first. + +## Picking the Right AI + +Different AI models are good at different things: + +
+
+ Quick questions + Faster models like GPT-4o or Claude 3.5 Sonnet +
+
+ Hard problems + Smarter models like GPT-5.2 or Claude 4.5 Opus +
+
+ Writing code + Code-focused models or the smartest general models +
+
+ Long documents + Models with big context windows (Claude, Gemini) +
+
+ Current events + Models with internet access +
+
+ +## Summary + +AI language models are prediction machines trained on text. They're amazing at many things, but they have real limits. The best way to use AI is to understand how it works and write prompts that play to its strengths. + + + + + +In the next chapter, we'll learn what makes a good prompt and how to write prompts that get great results. diff --git a/src/content/book/nl/02-anatomy-of-effective-prompt.mdx b/src/content/book/nl/02-anatomy-of-effective-prompt.mdx new file mode 100644 index 00000000..03cd23d2 --- /dev/null +++ b/src/content/book/nl/02-anatomy-of-effective-prompt.mdx @@ -0,0 +1,343 @@ +Every great prompt shares common structural elements. Understanding these components allows you to construct prompts systematically rather than through trial and error. + + +Think of these components like LEGO bricks. You don't need all of them for every prompt, but knowing what's available helps you build exactly what you need. + + +## The Core Components + +An effective prompt typically includes some or all of these elements: + + + +Let's examine each component in detail. + +## 1. Role / Persona + +Setting a role focuses the model's responses through the lens of a specific expertise or perspective. + + + +The role primes the model to: +- Use appropriate vocabulary +- Apply relevant expertise +- Maintain a consistent perspective +- Consider the audience appropriately + +### Effective Role Patterns + +``` +"You are a [profession] with [X years] of experience in [specialty]" +"Act as a [role] who is [characteristic]" +"You are an expert [field] helping a [audience type]" +``` + +## 2. Context / Background + +Context provides the information the model needs to understand your situation. Remember: the model knows nothing about you, your project, or your goals unless you tell it. + + + +### What to Include in Context + +- **Project details** — Technology stack, architecture, constraints +- **Current state** — What you've tried, what's working, what isn't +- **Goals** — What you're ultimately trying to achieve +- **Constraints** — Time limits, technical requirements, style guides + +## 3. Task / Instruction + +The task is the heart of your prompt—what you want the model to do. Be specific and unambiguous. + +### The Specificity Spectrum + + + +### Action Verbs That Work Well + +
+
+ Creation + Write, Create, Generate, Compose, Design +
+
+ Analysis + Analyze, Evaluate, Compare, Assess, Review +
+
+ Transformation + Convert, Translate, Reformat, Summarize, Expand +
+
+ Explanation + Explain, Describe, Clarify, Define, Illustrate +
+
+ Problem-solving + Solve, Debug, Fix, Optimize, Improve +
+
+ +## 4. Constraints / Rules + +Constraints bound the model's output. They prevent common issues and ensure relevance. + +### Types of Constraints + +**Length constraints:** +``` +"Keep your response under 200 words" +"Provide exactly 5 suggestions" +"Write 3-4 paragraphs" +``` + +**Content constraints:** +``` +"Do not include any code examples" +"Focus only on the technical aspects" +"Avoid marketing language" +``` + +**Style constraints:** +``` +"Use a formal, academic tone" +"Write as if speaking to a 10-year-old" +"Be direct and avoid hedging language" +``` + +**Scope constraints:** +``` +"Only consider options available in Python 3.10+" +"Limit suggestions to free tools" +"Focus on solutions that don't require additional dependencies" +``` + +## 5. Output Format + +Specifying the output format ensures you get responses in a usable structure. + +### Common Formats + +**Lists:** +``` +"Return as a bulleted list" +"Provide a numbered list of steps" +``` + +**Structured data:** +``` +"Return as JSON with keys: title, description, priority" +"Format as a markdown table with columns: Feature, Pros, Cons" +``` + +**Specific structures:** +``` +"Structure your response as: + ## Summary + ## Key Points + ## Recommendations" +``` + +### JSON Output Example + +``` +Analyze this customer review and return JSON: +{ + "sentiment": "positive" | "negative" | "neutral", + "topics": ["array of main topics"], + "rating_prediction": 1-5, + "key_phrases": ["notable phrases"] +} + +Review: "The product arrived quickly and works great, but +the instructions were confusing." +``` + +## 6. Examples (Few-Shot Learning) + +Examples are the most powerful way to show the model exactly what you want. + +### One-Shot Example + +``` +Convert these sentences to past tense. + +Example: +Input: "She walks to the store" +Output: "She walked to the store" + +Now convert: +Input: "They run every morning" +``` + +### Few-Shot Example + +``` +Classify these support tickets by urgency. + +Examples: +"My account was hacked" → Critical +"How do I change my password?" → Low +"Payment failed but I was charged" → High + +Classify: "The app crashes when I open settings" +``` + +## Putting It All Together + +Here's a complete prompt using all components: + + + +## The Minimal Effective Prompt + +Not every prompt needs all components. For simple tasks, a clear instruction may suffice: + +``` +Translate "Hello, how are you?" to Spanish. +``` + +Use additional components when: +- The task is complex or ambiguous +- You need specific formatting +- Results aren't matching expectations +- Consistency across multiple queries matters + +## Common Prompt Patterns + +These frameworks give you a simple checklist to follow when writing prompts. Click on each step to see an example. + + + + + +## Summary + +Effective prompts are constructed, not discovered. By understanding and applying these structural components, you can: + +- Get better results on the first try +- Debug prompts that aren't working +- Create reusable prompt templates +- Communicate your intentions clearly + + + + + +## Build Your Own Prompt + +Now it's your turn! Use this interactive prompt builder to construct your own prompt using the components you've learned: + + + + + +In the next chapter, we'll explore the core principles that guide prompt construction decisions. diff --git a/src/content/book/nl/03-core-prompting-principles.mdx b/src/content/book/nl/03-core-prompting-principles.mdx new file mode 100644 index 00000000..358df563 --- /dev/null +++ b/src/content/book/nl/03-core-prompting-principles.mdx @@ -0,0 +1,373 @@ +Beyond structure, effective prompt engineering is guided by principles—fundamental truths that apply across models, tasks, and contexts. Master these principles, and you'll be able to adapt to any prompting challenge. + + +These principles apply to every AI model and every task. Learn them once, use them everywhere. + + +## Principle 1: Clarity Over Cleverness + +The best prompts are clear, not clever. AI models are literal interpreters—they work with exactly what you give them. + +### Be Explicit + + + +### Avoid Ambiguity + +Words can have multiple meanings. Choose precise language. + + + +### State the Obvious + +What's obvious to you isn't obvious to the model. Spell out assumptions. + +``` +You're helping me write a cover letter. + +Important context: +- I'm applying for a Software Engineer position at Google +- I have 5 years of experience in Python and distributed systems +- The role requires leadership experience (I've led a team of 4) +- I want to emphasize my open-source contributions +``` + +## Principle 2: Specificity Yields Quality + +Vague inputs produce vague outputs. Specific inputs produce specific, useful outputs. + +### The Specificity Ladder + + + +Each level adds specificity and dramatically improves output quality. + +### Specify These Elements + +
+
+ Audience + Who will read/use this? +
+
+ Length + How long/short should it be? +
+
+ Tone + Formal? Casual? Technical? +
+
+ Format + Prose? List? Table? Code? +
+
+ Scope + What to include/exclude? +
+
+ Purpose + What should this accomplish? +
+
+ +## Principle 3: Context Is King + +Models have no memory, no access to your files, and no knowledge of your situation. Everything relevant must be in the prompt. + +### Provide Sufficient Context + + + +### The Context Checklist + + +Ask yourself: Would a smart stranger understand this request? If not, add more context. + + + + +## Principle 4: Guide, Don't Just Ask + +Don't just ask for an answer—guide the model toward the answer you want. + +### Use Instructional Framing + + + +### Provide Reasoning Scaffolds + +For complex tasks, guide the reasoning process: + + + +## Principle 5: Iterate and Refine + +Prompt engineering is an iterative process. Your first prompt is rarely your best. + +### The Iteration Cycle + +``` +1. Write initial prompt +2. Review output +3. Identify gaps or issues +4. Refine prompt +5. Repeat until satisfied +``` + +### Common Refinements + +
+
+ Too verbose + Add "Be concise" or length limits +
+
+ Too vague + Add specific examples or constraints +
+
+ Wrong format + Specify exact output structure +
+
+ Missing aspects + Add "Make sure to include..." +
+
+ Wrong tone + Specify audience and style +
+
+ Inaccurate + Request citations or step-by-step reasoning +
+
+ +### Keep a Prompt Journal + +Document what works: +``` +Task: Code review +Version 1: "Review this code" → Too generic +Version 2: Added specific review criteria → Better +Version 3: Added example of good review → Excellent +Final: [Save successful prompt as template] +``` + +## Principle 6: Leverage the Model's Strengths + +Work with how models are trained, not against them. + +### Models Want to Be Helpful + +Frame requests as things a helpful assistant would naturally do: + + + +### Models Excel at Patterns + +If you need consistent output, show the pattern: + + + +### Models Can Role-Play + +Use personas to access different "modes" of response: + +``` +As a devil's advocate, argue against my proposal... +As a supportive mentor, help me improve... +As a skeptical investor, question this business plan... +``` + +## Principle 7: Control Output Structure + +Structured outputs are more useful than free-form text. + +### Request Specific Formats + +``` +Return your analysis as: + +SUMMARY: [1 sentence] + +KEY FINDINGS: +• [Finding 1] +• [Finding 2] +• [Finding 3] + +RECOMMENDATION: [1-2 sentences] + +CONFIDENCE: [Low/Medium/High] because [reason] +``` + +### Use Delimiters + +Clearly separate sections of your prompt: + +``` +### CONTEXT ### +[Your context here] + +### TASK ### +[Your task here] + +### FORMAT ### +[Desired format here] +``` + +### Request Machine-Readable Output + +For programmatic use: + +``` +Return only valid JSON, no explanation: +{ + "decision": "approve" | "reject" | "review", + "confidence": 0.0-1.0, + "reasons": ["string array"] +} +``` + +## Principle 8: Verify and Validate + +Never blindly trust model outputs, especially for important tasks. + +### Ask for Reasoning + +``` +Solve this problem and show your work step by step. +After solving, verify your answer by [checking method]. +``` + +### Request Multiple Perspectives + +``` +Give me three different approaches to solve this problem. +For each, explain the trade-offs. +``` + +### Build in Self-Checking + +``` +After generating the code, review it for: +- Syntax errors +- Edge cases +- Security vulnerabilities +List any issues found. +``` + +## Summary: The Principles at a Glance + + + + + +## Practice: Fill in the Blanks + +Test your understanding of the core principles by completing this prompt template: + + + + + +These principles form the foundation for everything that follows. In Part II, we'll apply them to specific techniques that dramatically enhance prompt effectiveness. diff --git a/src/content/book/nl/04-role-based-prompting.mdx b/src/content/book/nl/04-role-based-prompting.mdx new file mode 100644 index 00000000..ef178cbc --- /dev/null +++ b/src/content/book/nl/04-role-based-prompting.mdx @@ -0,0 +1,328 @@ +Role-based prompting is one of the most powerful and widely-used techniques in prompt engineering. By assigning a specific role or persona to the AI, you can dramatically influence the quality, style, and relevance of responses. + + +Think of roles as filters for AI's vast knowledge. The right role focuses responses like a lens focuses light. + + +## Why Roles Work + +When you assign a role, you're essentially telling the model: "Filter your vast knowledge through this specific lens." The model adjusts its: + +- **Vocabulary**: Using terminology appropriate to the role +- **Perspective**: Considering problems from that viewpoint +- **Expertise depth**: Providing role-appropriate detail levels +- **Communication style**: Matching how that role would communicate + +### The Technical Explanation + +LLMs work by predicting the most likely next token based on the context they're given. When you specify a role, you're fundamentally changing what "likely" means. + +**Activating Relevant Knowledge**: The role primes specific regions of the model's learned associations. Saying "You are a doctor" activates medical terminology, diagnostic reasoning patterns, and clinical communication styles from the training data. + +**Statistical Conditioning**: LLMs learned from millions of documents written by real experts. When you assign a role, the model conditions its probability distributions to match patterns it saw from that type of author. + +**Reducing Ambiguity**: Without a role, the model averages across all possible responders. With a role, it narrows to a specific subset, making responses more focused and consistent. + +**Context Anchoring**: The role creates a persistent context anchor throughout the conversation. Every subsequent response is influenced by this initial framing. + +Think of it this way: if you ask "What should I do about this cough?" the model could respond as a doctor, a friend, a pharmacist, or a worried parent. Each would give different advice. By specifying the role upfront, you're telling the model which "voice" to use from its training data. + + +The model isn't pretending or role-playing in a theatrical sense. It's statistically biasing its outputs toward patterns it learned from real experts, professionals, and specialists during training. A "doctor" role activates medical knowledge pathways; a "poet" role activates literary patterns. + + +## Basic Role Patterns + +These foundational patterns work across most use cases. Start with these templates and customize them for your needs. + +### The Expert Pattern + +The most versatile pattern. Specify the field of expertise and years of experience to get authoritative, in-depth responses. Works well for technical questions, analysis, and professional advice. + + + +### The Professional Pattern + +Ground the role in a real-world context by specifying a job title and organization type. This adds institutional knowledge and professional norms to the response. + + + +### The Teacher Pattern + +Perfect for learning and explanations. Specifying the audience level ensures the response matches the learner's background, from beginners to advanced practitioners. + + + +## Advanced Role Constructions + +### Compound Roles + +Combine multiple identities to get responses that blend different perspectives. This pediatrician-parent combination produces advice that's both medically sound and practically tested. + + + +### Situational Roles + +Place the role in a specific scenario to shape both content and tone. Here, the code review context makes the AI constructive and educational rather than just critical. + + + +### Perspective Roles + +Get feedback from a specific stakeholder's point of view. A VC perspective evaluates viability and scalability differently than a customer or engineer would. + + + +## Role Categories and Examples + +Different domains benefit from different types of roles. Here are proven examples organized by category that you can adapt for your tasks. + +### Technical Roles + +**Software Architect**: Best for system design decisions, technology choices, and architectural trade-offs. The focus on maintainability steers responses toward practical, long-term solutions. + + + +**Security Specialist**: The attacker mindset is key here. This role produces threat-focused analysis that identifies vulnerabilities a defensive-only perspective might miss. + + + +**DevOps Engineer**: Ideal for deployment, automation, and infrastructure questions. The emphasis on reliability ensures production-ready recommendations. + + + +### Creative Roles + +**Copywriter**: The "award-winning" qualifier and conversion focus produce punchy, persuasive copy rather than generic marketing text. + + + +**Screenwriter**: Activates knowledge of dramatic structure, pacing, and dialogue conventions. Great for any narrative writing that needs tension and character voice. + + + +**UX Writer**: A specialized role for interface text. The focus on brevity and user guidance produces concise, action-oriented copy. + + + +### Analytical Roles + +**Business Analyst**: Bridges the gap between technical and non-technical stakeholders. Useful for requirement gathering, spec writing, and identifying gaps in project plans. + + + +**Research Scientist**: The emphasis on evidence and uncertainty acknowledgment produces balanced, well-sourced responses that distinguish facts from speculation. + + + +**Financial Analyst**: Combines quantitative analysis with risk assessment. The dual focus on returns and risk produces more balanced investment perspectives. + + + +### Educational Roles + +**Socratic Tutor**: Instead of giving answers, this role asks guiding questions. Excellent for deeper learning and helping students develop critical thinking skills. + + + +**Instructional Designer**: Structures learning for maximum retention. Use this role when you need to break down complex topics into teachable chunks with clear progression. + + + +## The Role Stack Technique + +For complex tasks, combine multiple role aspects into a single, layered identity. This technique stacks expertise, audience awareness, and style guidelines to create highly specialized responses. + +This example layers three elements: domain expertise (API documentation), audience (junior developers), and style guide (Google's conventions). Each layer constrains the output further. + + + +## Roles for Different Tasks + +
+
+ Code review + Senior developer + mentor +
+
+ Writing feedback + Editor + target audience member +
+
+ Business strategy + Consultant + industry expert +
+
+ Learning new topic + Patient teacher + practitioner +
+
+ Creative writing + Specific genre author +
+
+ Technical explanation + Expert + communicator +
+
+ Problem-solving + Domain specialist + generalist +
+
+ +## Anti-Patterns to Avoid + +### Overly Generic Roles + + + +### Conflicting Roles + + + +### Unrealistic Expertise + + + +## Real-World Prompt Examples + +### Technical Documentation + + + +### Creative Writing + + + +### Business Communication + + + +## Combining Roles with Other Techniques + +Roles work even better when combined with other prompting techniques: + +### Role + Few-Shot + +Combine a role with an example to show exactly how the role should respond. The example teaches tone and format while the role provides context and expertise. + + + +### Role + Chain of Thought + +The detective role naturally encourages step-by-step reasoning. Combining roles with chain-of-thought produces more transparent, verifiable problem-solving. + + + +## Summary + + +Role-based prompting is powerful because it focuses the model's vast knowledge, sets expectations for tone and style, provides implicit context, and makes outputs more consistent. + + + + +The key is **specificity**: the more detailed and realistic the role, the better the results. In the next chapter, we'll explore how to get consistent, structured outputs from your prompts. diff --git a/src/content/book/nl/05-structured-output.mdx b/src/content/book/nl/05-structured-output.mdx new file mode 100644 index 00000000..8236abee --- /dev/null +++ b/src/content/book/nl/05-structured-output.mdx @@ -0,0 +1,411 @@ +Getting consistent, well-formatted output is essential for production applications and efficient workflows. This chapter covers techniques for controlling exactly how AI models format their responses. + + +Structured output transforms AI responses from freeform text into actionable, parseable data. + + +## Why Structure Matters + + + +## Basic Formatting Techniques + +### Lists + +Lists are perfect for step-by-step instructions, ranked items, or collections of related points. They're easy to scan and parse. Use **numbered lists** when order matters (steps, rankings) and **bullet points** for unordered collections. + + + + +Specify the exact number of items you want, whether to include explanations, and if items should be bold or have a specific structure. + + +### Tables + +Tables excel at comparing multiple items across the same dimensions. They're ideal for feature comparisons, data summaries, and any information with consistent attributes. Always define your column headers explicitly. + + + + +Specify column names, expected data types (text, numbers, ratings), and how many rows you need. For complex comparisons, limit to 4-6 columns for readability. + + +### Headers and Sections + +Headers create a clear document structure, making long responses scannable and organized. Use them for reports, analyses, or any multi-part response. Hierarchical headers (##, ###) show relationships between sections. + +``` +Analyze this business proposal. + +Structure your response with these sections: +## Executive Summary +## Strengths +## Weaknesses +## Recommendations +## Risk Assessment +``` + + +List your sections in the order you want them. For consistency, specify what each section should contain (e.g., "Executive Summary: 2-3 sentences only"). + + +### Emphasis with Uppercase Directives + +Uppercase words act as strong signals to the model, emphasizing critical constraints or requirements. Use them sparingly for maximum impact—overuse dilutes their effectiveness. + +**Common Uppercase Directives:** + + + +``` +Summarize this article. + +IMPORTANT: Keep the summary under 100 words. +NEVER add information not present in the original. +ALWAYS maintain the original tone and perspective. +DO NOT include your own opinions or analysis. +``` + + +If everything is uppercase or marked as critical, nothing stands out. Reserve these directives for genuinely important constraints. + + +## JSON Output + +JSON (JavaScript Object Notation) is the most popular format for structured AI output. It's machine-readable, widely supported by programming languages, and perfect for APIs, databases, and automation workflows. The key to reliable JSON is providing a clear schema. + +### Basic JSON Request + +Start with a template showing the exact structure you want. Include field names, data types, and example values. This acts as a contract the model will follow. + + + +### Complex JSON Structures + +For nested data, use hierarchical JSON with objects inside objects, arrays of objects, and mixed types. Define each level clearly and use TypeScript-style annotations (`"positive" | "negative"`) to constrain values. + +``` +Analyze this product review and return JSON: + +{ + "review_id": "string (generate unique)", + "sentiment": { + "overall": "positive" | "negative" | "mixed" | "neutral", + "score": 0.0-1.0 + }, + "aspects": [ + { + "aspect": "string (e.g., 'price', 'quality')", + "sentiment": "positive" | "negative" | "neutral", + "mentions": ["exact quotes from review"] + } + ], + "purchase_intent": { + "would_recommend": boolean, + "confidence": 0.0-1.0 + }, + "key_phrases": ["string array of notable phrases"] +} + +Return ONLY valid JSON, no additional text. + +Review: "[review text]" +``` + +### Ensuring Valid JSON + +Models sometimes add explanatory text or markdown formatting around JSON. Prevent this with explicit instructions about output format. You can request raw JSON or JSON inside code blocks—choose based on your parsing needs. + +Add explicit instructions: + +``` +IMPORTANT: +- Return ONLY the JSON object, no markdown code blocks +- Ensure all strings are properly escaped +- Use null for missing values, not undefined +- Validate that the output is parseable JSON +``` + +Or request code blocks by asking the model to wrap its output: + +```` +Return the result as a JSON code block: +```json +{ ... } +``` +```` + +## YAML Output + +YAML is more human-readable than JSON, using indentation instead of brackets. It's the standard for configuration files (Docker, Kubernetes, GitHub Actions) and works well when the output will be read by humans or used in DevOps contexts. YAML is sensitive to indentation, so be specific about formatting requirements. + + + +## XML Output + +XML is still required for many enterprise systems, SOAP APIs, and legacy integrations. It's more verbose than JSON but offers features like attributes, namespaces, and CDATA sections for complex data. Specify element names, nesting structure, and where to use attributes vs. child elements. + +``` +Convert this data to XML format: + +Requirements: +- Root element: +- Each item in element +- Include attributes where appropriate +- Use CDATA for description text + +Data: [book data] +``` + +## Custom Formats + +Sometimes standard formats don't fit your needs. You can define any custom format by providing a clear template. Custom formats work well for reports, logs, or domain-specific outputs that will be read by humans. + +### Structured Analysis Format + +Use delimiters (===, ---, [SECTION]) to create scannable documents with clear boundaries between sections. This format is great for code reviews, audits, and analyses. + +``` +Analyze this code using this exact format: + +=== CODE ANALYSIS === + +[SUMMARY] +One paragraph overview + +[ISSUES] +• CRITICAL: [issue] — [file:line] +• WARNING: [issue] — [file:line] +• INFO: [issue] — [file:line] + +[METRICS] +Complexity: [Low/Medium/High] +Maintainability: [score]/10 +Test Coverage: [estimated %] + +[RECOMMENDATIONS] +1. [Priority 1 recommendation] +2. [Priority 2 recommendation] + +=== END ANALYSIS === +``` + +### Fill-in-the-Blank Format + +Templates with blanks (___) guide the model to fill in specific fields while maintaining exact formatting. This approach is excellent for forms, briefs, and standardized documents where consistency matters. + +``` +Complete this template for the given product: + +PRODUCT BRIEF +───────────── +Name: _______________ +Tagline: _______________ +Target User: _______________ +Problem Solved: _______________ +Key Features: + 1. _______________ + 2. _______________ + 3. _______________ +Differentiator: _______________ + +Product: [product description] +``` + +## Typed Responses + +Typed responses define categories or entity types that the model should recognize and label. This technique is essential for Named Entity Recognition (NER), classification tasks, and any extraction where you need to categorize information consistently. Define your types clearly with examples. + + + +## Multi-Part Structured Responses + +When you need comprehensive output covering multiple aspects, define distinct parts with clear boundaries. Specify exactly what goes in each part—format, length, and content type. This prevents the model from blending sections or omitting parts. + +``` +Research this topic and provide: + +### PART 1: EXECUTIVE SUMMARY +[2-3 sentence overview] + +### PART 2: KEY FINDINGS +[Exactly 5 bullet points] + +### PART 3: DATA TABLE +| Metric | Value | Source | +|--------|-------|--------| +[Include 5 rows minimum] + +### PART 4: RECOMMENDATIONS +[Numbered list of 3 actionable recommendations] + +### PART 5: FURTHER READING +[3 suggested resources with brief descriptions] +``` + +## Conditional Formatting + +Conditional formatting lets you define different output formats based on the input's characteristics. This is powerful for classification, triage, and routing systems where the response format should vary based on what the model detects. Use clear if/then logic with explicit output templates for each case. + + + +## Arrays and Lists in JSON + +Extracting multiple items into arrays requires careful schema definition. Specify the array structure, what each item should contain, and how to handle edge cases (empty arrays, single items). Including a count field helps verify completeness. + +``` +Extract all action items from this meeting transcript. + +Return as JSON array: +{ + "action_items": [ + { + "task": "string describing the task", + "assignee": "person name or 'Unassigned'", + "deadline": "date if mentioned, else null", + "priority": "high" | "medium" | "low", + "context": "relevant quote from transcript" + } + ], + "total_count": number +} + +Transcript: "[meeting transcript]" +``` + +## Validation Instructions + +Self-validation prompts the model to check its own output before responding. This catches common issues like missing sections, placeholder text, or constraint violations. The model will iterate internally to fix problems, improving output quality without additional API calls. + +``` +Generate the report, then: + +VALIDATION CHECKLIST: +□ All required sections present +□ No placeholder text remaining +□ All statistics include sources +□ Word count within 500-700 words +□ Conclusion ties back to introduction + +If any check fails, fix before responding. +``` + +## Handling Optional Fields + +Real-world data often has missing values. Explicitly instruct the model on how to handle optional fields—using `null` is cleaner than empty strings and easier to process programmatically. Also prevent "hallucination" of missing data by emphasizing that the model should never invent information. + +``` +Extract contact information. Use null for missing fields. + +{ + "name": "string (required)", + "email": "string or null", + "phone": "string or null", + "company": "string or null", + "role": "string or null", + "linkedin": "URL string or null" +} + +IMPORTANT: +- Never invent information not in the source +- Use null, not empty strings, for missing data +- Phone numbers in E.164 format if possible +``` + +## Summary + + +Be explicit about format, use examples, specify types, handle edge cases with null values, and ask the model to validate its own output. + + + + +Structured outputs are essential for building reliable AI-powered applications. In the next chapter, we'll explore chain-of-thought prompting for complex reasoning tasks. diff --git a/src/content/book/nl/06-chain-of-thought.mdx b/src/content/book/nl/06-chain-of-thought.mdx new file mode 100644 index 00000000..e579be5d --- /dev/null +++ b/src/content/book/nl/06-chain-of-thought.mdx @@ -0,0 +1,363 @@ +Chain of Thought (CoT) prompting is a technique that dramatically improves AI performance on complex reasoning tasks by asking the model to show its work step by step. + + +Just like a math teacher asking students to show their work, CoT prompting asks the AI to make its reasoning visible. + + +## The Problem CoT Solves + +AI models can struggle with multi-step reasoning when asked to jump directly to an answer. + + + +## Basic CoT Prompts + +### Simple Trigger Phrases + +Add one of these to your prompts: + +
+
"Let's think step by step."
+
"Think through this carefully."
+
"Work through this problem methodically."
+
"Show your reasoning at each step."
+
"Explain your thought process."
+
+ +### Explicit Step Request + + + +## Zero-Shot vs Few-Shot CoT + +There are two main approaches to Chain of Thought prompting, each with different trade-offs between simplicity and control. + +### Zero-Shot CoT + +The simplest approach—just add a trigger phrase and let the model figure out how to reason. No examples needed. This works surprisingly well for many problems, though you have less control over the reasoning format. + + + +**Example Output:** +``` +Let's think step by step. +- John starts with 3 apples +- Half of 3 is 1.5, but we can't split apples +- If we round down: John gives 1 apple, keeps 2 +- After buying 4 more: 2 + 4 = 6 apples + +Answer: 6 apples +``` + +### Few-Shot CoT + +For more consistent results, show the model exactly how you want it to reason by providing worked examples. This gives you control over the reasoning style, format, and level of detail. The model will mimic your demonstrated pattern. + + + +**Example Output:** +``` +A: Let's work through this: +- Regular price: $3, Quantity: 12 +- Since 12 ≥ 10, the 25% discount applies +- Regular total: 12 × $3 = $36 +- Discount: 25% of $36 = $9 +- Final price: $36 - $9 = $27 +``` + +## Structured CoT Formats + +For consistent, reproducible reasoning, use structured formats with named steps. These frameworks ensure the model doesn't skip important stages and makes outputs easier to parse and verify. + +### The BREAK Format + +A memorable acronym that guides the model through a complete problem-solving cycle, from understanding to verification. + + + +### The Reasoning Template + +A more formal structure that separates inputs, goals, and execution. Excellent for technical problems where you need clear documentation of the solution process. + + + +**Example Output:** +``` +GIVEN: 8L/100km, tank 45L, $1.50/L, drive 300km +GOAL: Calculate fuel cost +APPROACH: Fuel needed × cost per liter +STEPS: +1. Fuel = (300 ÷ 100) × 8 = 24 liters +2. Cost = 24 × $1.50 = $36 +VERIFICATION: 24L < 45L tank ✓ +ANSWER: $36 +``` + +## CoT for Different Problem Types + +Different problem types benefit from different CoT approaches. Here are patterns optimized for common scenarios. + +### Mathematical Reasoning + +Math problems benefit most from CoT because each step builds on the previous one. Errors compound, so showing work helps catch mistakes early. The model should clearly label each calculation. + + + +**Example Output:** +``` +Q1: $1,200,000 (given) +Q2: $1,200,000 × 1.15 = $1,380,000 +Q3: $1,380,000 × 0.90 = $1,242,000 +Q4: $1,242,000 × 1.25 = $1,552,500 + +Total: $5,374,500 +``` + +### Logical Reasoning + +Logic puzzles require systematic elimination and hypothesis testing. CoT helps the model track constraints, test possibilities, and verify that all conditions are satisfied. The key is methodical exploration rather than guessing. + + + +**Example Output:** +``` +From clue 3: Bob = teacher +→ Alice and Carol are engineer/doctor + +If Carol = engineer: +- Carol has dog (clue 2) +- Alice = doctor, has fish (clue 1) +- Bob has cat + +Verify: All 4 clues satisfied ✓ +Answer: Alice (doctor, fish), Bob (teacher, cat), Carol (engineer, dog) +``` + +### Code Debugging + +Debugging benefits from CoT because it forces the model to trace execution rather than guess at bugs. By walking through the code with concrete values, the actual behavior becomes visible and discrepancies with expected behavior are exposed. + + + +**Example Output:** +``` +Trace [2, 3, 4, 6]: +n=2: total += 1 → 1 (wait, adding 1 not n!) +n=3: skip (odd) +n=4: total = 2 +n=6: total = 3 + +BUG: "total += 1" should be "total += n" +Expected: 12, Got: 3 +Fix: Change to "total += n" +``` + +## Self-Consistency with CoT + +For critical problems, don't rely on a single reasoning path. Generate multiple independent solutions and compare results. If different approaches converge on the same answer, confidence is high. Disagreement signals the need for careful review. + + + +**Example Output:** +``` +Approach 1 (Algebra): c + w = 30, 2c + 4w = 74 → c=23, w=7 +Approach 2 (Guess): Try 23/7 → 46 + 28 = 74 ✓ +Approach 3 (Logic): 30 chickens = 60 legs, need 14 more → 7 cows + +All agree: 23 chickens, 7 cows +``` + +## CoT for Decision Making + +Decisions involve weighing trade-offs across multiple dimensions. CoT ensures all relevant factors are considered systematically rather than jumping to conclusions. This structured approach also documents the reasoning for future reference. + + + +**Example Output:** +``` +FACTORS: +- Team size (5): Too small for microservices ❌ +- Scale (100 DAU): No scaling need ❌ +- Velocity: Monolith = faster iteration ❌ +- Future growth: Uncertain timeline ⚠️ + +WEIGHING: 3 strong against, 1 weak for + +RECOMMENDATION: Stay monolith, use clear module +boundaries to ease future transition. +``` + +## When to Use CoT + +
+
+

Use CoT For

+
+

**Math problems** — Reduces calculation errors

+

**Logic puzzles** — Prevents skipped steps

+

**Complex analysis** — Organizes thinking

+

**Code debugging** — Traces execution

+

**Decision making** — Weighs trade-offs

+
+
+
+

Skip CoT For

+
+

**Simple Q&A** — Unnecessary overhead

+

**Creative writing** — Can constrain creativity

+

**Factual lookups** — No reasoning needed

+

**Translation** — Direct task

+

**Summarization** — Usually straightforward

+
+
+
+ +## CoT Limitations + +While powerful, Chain of Thought isn't a silver bullet. Understanding its limitations helps you apply it appropriately. + +1. **Increased token usage** — More output means higher costs +2. **Not always needed** — Simple tasks don't benefit +3. **Can be verbose** — May need to ask for conciseness +4. **Reasoning can be flawed** — CoT doesn't guarantee correctness + +## Summary + + +CoT dramatically improves complex reasoning by making implicit steps explicit. Use it for math, logic, analysis, and debugging. Trade-off: better accuracy for more tokens. + + + + +In the next chapter, we'll explore few-shot learning—teaching the model through examples. diff --git a/src/content/book/nl/07-few-shot-learning.mdx b/src/content/book/nl/07-few-shot-learning.mdx new file mode 100644 index 00000000..24e98f1d --- /dev/null +++ b/src/content/book/nl/07-few-shot-learning.mdx @@ -0,0 +1,478 @@ +Few-shot learning is one of the most powerful prompting techniques. By providing examples of what you want, you can teach the model complex tasks without any fine-tuning. + + +Just like humans learn by seeing examples, AI models can learn patterns from the examples you provide in your prompt. + + +## What is Few-Shot Learning? + +Few-shot learning shows the model examples of input-output pairs before asking it to perform the same task. The model learns the pattern from your examples and applies it to new inputs. + + + +
+
+
0
+
Zero-shot
+
+
+
1
+
One-shot
+
+
+
2-5
+
Few-shot
+
+
+
5+
+
Many-shot
+
+
+ +## Why Examples Work + + + +Examples communicate: +- **Format**: How output should be structured +- **Style**: Tone, length, vocabulary +- **Logic**: The reasoning pattern to follow +- **Edge cases**: How to handle special situations + +## Basic Few-Shot Pattern + +The fundamental structure of few-shot prompting follows a simple pattern: show examples, then ask for the new task. Consistency in formatting between examples is crucial. The model learns from the pattern you establish. + +``` +[Example 1] +Input: [input 1] +Output: [output 1] + +[Example 2] +Input: [input 2] +Output: [output 2] + +[Example 3] +Input: [input 3] +Output: [output 3] + +Now do this one: +Input: [new input] +Output: +``` + +## Few-Shot for Classification + +Classification is one of the strongest use cases for few-shot learning. By showing examples of each category, you define the boundaries between classes more precisely than instructions alone could achieve. + +### Sentiment Analysis + + +Sentiment analysis classifies text by emotional tone: positive, negative, neutral, or mixed. It's widely used for customer feedback, social media monitoring, and brand perception tracking. + + +Sentiment classification benefits from showing examples of each sentiment type, especially edge cases like "mixed" sentiment that might be ambiguous. + + + +### Topic Classification + +For multi-class categorization, include at least one example per category. This helps the model understand your specific taxonomy, which may differ from its default understanding. + + + +## Few-Shot for Transformation + +Transformation tasks convert input from one form to another while preserving meaning. Examples are essential here because they define exactly what "transformation" means for your use case. + +### Text Rewriting + +Style transformation requires examples that show the exact tone shift you want. Abstract instructions like "make it professional" are interpreted differently. Examples make it concrete. + + + +### Format Conversion + +Format conversion tasks benefit from examples showing edge cases and ambiguous inputs. The model learns your specific conventions for handling tricky cases. + + + +## Few-Shot for Generation + +Generation tasks create new content following a learned pattern. Examples establish length, structure, tone, and what details to highlight. These are hard to specify in instructions alone. + +### Product Descriptions + +Marketing copy benefits enormously from examples because they capture brand voice, feature emphasis, and persuasive techniques that are difficult to describe abstractly. + + + +### Code Documentation + + +Good documentation explains what code does, its parameters, return values, and usage examples. Consistent docstrings enable auto-generated API docs and help IDEs provide better code completion. + + +Documentation style varies widely between projects. Examples teach your specific format, what to include (args, returns, examples), and the level of detail expected. + +>> calculate_bmi(70, 1.75) + 22.86 +""" + +Now document: +Function: +def is_palindrome(text): + cleaned = ''.join(c.lower() for c in text if c.isalnum()) + return cleaned == cleaned[::-1] + +Documentation:`} /> + +## Few-Shot for Extraction + +Extraction tasks pull structured information from unstructured text. Examples define which entities matter, how to format output, and how to handle cases where information is missing or ambiguous. + +### Entity Extraction + + +Named Entity Recognition (NER) identifies and classifies named entities in text into categories like persons, organizations, locations, dates, and products. It's fundamental for information retrieval and knowledge graphs. + + +NER benefits from examples showing your specific entity types and how to handle entities that could fit multiple categories. + + + +### Structured Data Extraction + +Extracting structured data from natural language requires examples showing how to handle missing fields, implicit information, and varying input formats. + + + +## Advanced Few-Shot Techniques + +Beyond basic few-shot, several techniques can improve results for complex tasks. + +### Diverse Examples + +Diversity in examples is more valuable than quantity. Cover different scenarios, edge cases, and potential ambiguities rather than showing similar examples repeatedly. + + + +### Negative Examples + + +Showing "good" vs "bad" examples is called contrastive learning. It helps the model understand not just what you want, but what to avoid. This is especially useful for style and quality judgments. + + +Sometimes showing what *not* to do is as valuable as showing correct examples. Negative examples help the model understand boundaries and avoid common mistakes. + + + +### Edge Case Examples + +Edge cases often determine whether a solution works in production. Including unusual inputs in your examples prevents the model from failing on real-world data that doesn't fit the "happy path." + + + +## How Many Examples? + +
+
+ Simple classification + 2-3 + One per category minimum +
+
+ Complex formatting + 3-5 + Show variations +
+
+ Nuanced style + 4-6 + Capture full range +
+
+ Edge cases + 1-2 + Alongside normal examples +
+
+ +## Example Quality Matters + + + +## Combining Few-Shot with Other Techniques + +Few-shot learning combines powerfully with other prompting techniques. The examples provide the "what" while other techniques can add context, reasoning, or structure. + +### Few-Shot + Role + +Adding a role gives the model context for *why* it's doing the task, which can improve quality and consistency. + +``` +You are a legal contract reviewer. + +[examples of contract clause analysis] + +Now analyze: [new clause] +``` + +### Few-Shot + CoT + +Combining few-shot with Chain of Thought shows not just *what* answer to give, but *how* to reason through to that answer. This is powerful for tasks requiring judgment. + +``` +Classify and explain reasoning. + +Review: "Great features but overpriced" +Thinking: The review mentions positive aspects ("great features") +but also a significant negative ("overpriced"). The negative seems +to outweigh the positive based on the "but" conjunction. +Classification: Mixed-Negative + +[more examples with reasoning] + +Now classify with reasoning: +Review: "Exactly what I needed, arrived faster than expected" +``` + +## Summary + + +Few-shot learning teaches through demonstration and is often more effective than instructions alone. Use 2-5 diverse, correct examples and combine with other techniques for best results. + + + + +In the next chapter, we'll explore iterative refinement: the art of improving prompts through successive attempts. diff --git a/src/content/book/nl/08-iterative-refinement.mdx b/src/content/book/nl/08-iterative-refinement.mdx new file mode 100644 index 00000000..769f879a --- /dev/null +++ b/src/content/book/nl/08-iterative-refinement.mdx @@ -0,0 +1,387 @@ +Prompt engineering is rarely a one-shot process. The best prompts emerge through iteration—testing, observing, and refining until you achieve the desired results. + + +Think of your first prompt as a rough draft. Even experienced prompt engineers rarely nail it on the first try. + + +## The Iteration Cycle + +Effective prompt refinement follows a predictable cycle: write, test, analyze, and improve. Each iteration brings you closer to a prompt that reliably produces the results you need. + + + +## Common Refinement Patterns + +Most prompt failures fall into a handful of categories. Learning to recognize these patterns lets you quickly diagnose and fix issues without starting from scratch. + +### Problem: Output Too Long + +One of the most common issues. Without explicit constraints, models tend to be thorough rather than concise. + + + +### Problem: Output Too Vague + +Vague prompts produce vague outputs. The model can't read your mind about what "better" means or which aspects matter most to you. + + + +### Problem: Wrong Tone + +Tone is subjective and varies by context. What sounds "professional" to the model might not match your organization's voice or the relationship with your recipient. + + + +### Problem: Missing Key Information + +Open-ended requests get open-ended responses. If you need specific types of feedback, you must ask for them explicitly. + + + +### Problem: Inconsistent Format + +Without a template, the model will structure each response differently, making comparison difficult and automation impossible. + + + +## Systematic Refinement Approach + +Random changes waste time. A systematic approach helps you identify problems quickly and fix them efficiently. + +### Step 1: Diagnose the Issue + +Before changing anything, identify what's actually wrong. Use this diagnostic table to map symptoms to solutions: + +
+
+ Symptom + Likely Cause + Solution +
+
+ Too long + No length constraint + Add word/sentence limits +
+
+ Too short + Lacks detail request + Ask for elaboration +
+
+ Off-topic + Vague instructions + Be more specific +
+
+ Wrong format + Format not specified + Define exact structure +
+
+ Wrong tone + Audience not clear + Specify audience/style +
+
+ Inconsistent + No examples provided + Add few-shot examples +
+
+ +### Step 2: Make Targeted Changes + +Resist the urge to rewrite everything. Changing multiple variables at once makes it impossible to know what helped and what hurt. Make one change, test it, then proceed: + +``` +Iteration 1: Add length constraint +Iteration 2: Specify format +Iteration 3: Add example +Iteration 4: Refine tone instructions +``` + +### Step 3: Document What Works + +Prompt engineering knowledge is easily lost. Keep a log of what you tried and why. This saves time when you revisit the prompt later or face similar challenges: + +```markdown +## Prompt: Customer Email Response + +### Version 1 (too formal) +"Write a response to this customer complaint." + +### Version 2 (better tone, still missing structure) +"Write a friendly but professional response to this complaint. +Show empathy first." + +### Version 3 (final - good results) +"Write a response to this customer complaint. Structure: +1. Acknowledge their frustration (1 sentence) +2. Apologize specifically (1 sentence) +3. Explain solution (2-3 sentences) +4. Offer additional help (1 sentence) + +Tone: Friendly, professional, empathetic but not groveling." +``` + +## Real-World Iteration Example + +Let's walk through a complete iteration cycle to see how each refinement builds on the last. Notice how each version addresses specific shortcomings of the previous one. + +### Task: Generate Product Names + + + +## Refinement Strategies by Task Type + +Different tasks fail in predictable ways. Knowing the common failure modes helps you diagnose and fix issues faster. + +### For Content Generation + +Content generation often produces generic, off-target, or poorly formatted output. The fix usually involves being more specific about constraints, providing concrete examples, or defining your brand voice explicitly. + + + +### For Code Generation + +Code output can fail technically (syntax errors, wrong language features) or architecturally (poor patterns, missing cases). Technical issues need version/environment specifics; architectural issues need design guidance. + + + +### For Analysis + +Analysis tasks often produce surface-level or unstructured results. Guide the model with specific frameworks (SWOT, Porter's Five Forces), request multiple viewpoints, or provide a template for the output structure. + + + +### For Q&A + +Question-answering can be too terse or too verbose, and may lack confidence indicators or sources. Specify the detail level you need and whether you want citations or uncertainty expressed. + + + +## The Feedback Loop Technique + +Here's a meta-technique: use the model itself to help improve your prompts. Share what you tried, what you got, and what you wanted. The model can often suggest improvements you hadn't considered. + +``` +I used this prompt: +"[your prompt]" + +And got this output: +"[model output]" + +I wanted something more [describe gap]. How should I modify +my prompt to get better results? +``` + +## A/B Testing Prompts + +For prompts that will be used repeatedly or at scale, don't just pick the first one that works. Test variations to find the most reliable and highest-quality approach. + +``` +Prompt A: "Summarize this article in 3 bullet points." +Prompt B: "Extract the 3 most important insights from this article." +Prompt C: "What are the key takeaways from this article? List 3." +``` + +Run each multiple times, compare: +- Consistency of output +- Quality of information +- Relevance to your needs + +## When to Stop Iterating + +Perfection is the enemy of good enough. Know when your prompt is ready for use and when you're just polishing for diminishing returns. + +
+
+

Ready to Ship

+
+

Output consistently meets requirements

+

Edge cases are handled appropriately

+

Format is reliable and parseable

+

Further improvements show diminishing returns

+
+
+
+

Keep Iterating

+
+

Output is inconsistent across runs

+

Edge cases cause failures

+

Critical requirements are missed

+

You haven't tested enough variations

+
+
+
+ +## Version Control for Prompts + +Prompts are code. For any prompt used in production, treat it with the same rigor: version control, changelogs, and the ability to roll back if something breaks. + + +prompts.chat includes automatic version history for your prompts. Every edit is saved, so you can compare versions and restore previous iterations with one click. + + +For self-managed prompts, use a folder structure: + +``` +prompts/ +├── customer-response/ +│ ├── v1.0.txt # Initial version +│ ├── v1.1.txt # Fixed tone issue +│ ├── v2.0.txt # Major restructure +│ └── current.txt # Symlink to active version +└── changelog.md # Document changes +``` + +## Summary + + +Start simple, observe carefully, change one thing at a time, document what works, and know when to stop. The best prompts aren't written—they're discovered through systematic iteration. + + + + +## Practice: Improve This Prompt + +Try improving this weak prompt yourself. Edit it, then use AI to compare your version with the original: + + + +In the next chapter, we'll explore JSON and YAML prompting for structured data applications. diff --git a/src/content/book/nl/09-json-yaml-prompting.mdx b/src/content/book/nl/09-json-yaml-prompting.mdx new file mode 100644 index 00000000..318619da --- /dev/null +++ b/src/content/book/nl/09-json-yaml-prompting.mdx @@ -0,0 +1,586 @@ +Structured data formats like JSON and YAML are essential for building applications that consume AI outputs programmatically. This chapter covers techniques for reliable structured output generation. + + +JSON and YAML transform AI outputs from freeform text into structured, type-safe data that code can consume directly. + + +## Why Structured Formats? + + + +## JSON Prompting Basics + +JSON (JavaScript Object Notation) is the most common format for programmatic AI outputs. Its strict syntax makes it easy to parse, but also means small errors can break your entire pipeline. + +### Do's and Don'ts: Requesting JSON + + + +### Simple JSON Output + +Start with a schema showing the expected structure. The model will fill in values based on the input text. + +``` +Extract the following information as JSON: + +{ + "name": "string", + "age": number, + "email": "string" +} + +Text: "Contact John Smith, 34 years old, at john@example.com" +``` + +Output: +```json +{ + "name": "John Smith", + "age": 34, + "email": "john@example.com" +} +``` + +### Nested JSON Structures + +Real-world data often has nested relationships. Define each level of your schema clearly, especially for arrays of objects. + +``` +Parse this order into JSON: + +{ + "order_id": "string", + "customer": { + "name": "string", + "email": "string" + }, + "items": [ + { + "product": "string", + "quantity": number, + "price": number + } + ], + "total": number +} + +Order: "Order #12345 for Jane Doe (jane@email.com): 2x Widget ($10 each), +1x Gadget ($25). Total: $45" +``` + +### Ensuring Valid JSON + + +Models often wrap JSON in markdown code blocks or add explanatory text. Be explicit about wanting raw JSON only. + + +Add explicit instructions: + +``` +CRITICAL: Return ONLY valid JSON. No markdown, no explanation, +no additional text before or after the JSON object. + +If a field cannot be determined, use null. +Ensure all strings are properly quoted and escaped. +Numbers should not be quoted. +``` + +## YAML Prompting Basics + +YAML is more human-readable than JSON and supports comments. It's the standard for configuration files, especially in DevOps (Docker, Kubernetes, GitHub Actions). + +### Simple YAML Output + +YAML uses indentation instead of braces. Provide a template showing the expected structure. + +``` +Generate a configuration file in YAML format: + +server: + host: string + port: number + ssl: boolean +database: + type: string + connection_string: string + +Requirements: Production server on port 443 with SSL, PostgreSQL database +``` + +Output: +```yaml +server: + host: "0.0.0.0" + port: 443 + ssl: true +database: + type: "postgresql" + connection_string: "postgresql://user:pass@localhost:5432/prod" +``` + +### Complex YAML Structures + +For complex configurations, be specific about requirements. The model knows common patterns for tools like GitHub Actions, Docker Compose, and Kubernetes. + +``` +Generate a GitHub Actions workflow in YAML: + +Requirements: +- Trigger on push to main and pull requests +- Run on Ubuntu latest +- Steps: checkout, setup Node 18, install dependencies, run tests +- Cache npm dependencies +``` + +## Type Definitions in Prompts + +Type definitions give the model a precise contract for output structure. They're more explicit than examples and easier to validate programmatically. + +### Using TypeScript-like Types + +TypeScript interfaces are familiar to developers and precisely describe optional fields, union types, and arrays. The prompts.chat platform uses this approach for structured prompts. + + + +### JSON Schema Definition + + +JSON Schema is a formal specification for describing JSON structure. It's supported by many validation libraries and API tools. + + +JSON Schema provides constraints like min/max values, required fields, and regex patterns: + +``` +Extract data according to this JSON Schema: + +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "type": "object", + "required": ["title", "author", "year"], + "properties": { + "title": { "type": "string" }, + "author": { "type": "string" }, + "year": { "type": "integer", "minimum": 1000, "maximum": 2100 }, + "genres": { + "type": "array", + "items": { "type": "string" } + }, + "rating": { + "type": "number", + "minimum": 0, + "maximum": 5 + } + } +} + +Book: "1984 by George Orwell (1949) - A dystopian masterpiece. +Genres: Science Fiction, Political Fiction. Rated 4.8/5" +``` + +## Handling Arrays + +Arrays require special attention. Specify whether you need a fixed number of items or a variable-length list, and how to handle empty cases. + +### Fixed-Length Arrays + +When you need exactly N items, state it explicitly. The model will ensure the array has the right length. + +``` +Extract exactly 3 key points as JSON: + +{ + "key_points": [ + "string (first point)", + "string (second point)", + "string (third point)" + ] +} + +Article: [article text] +``` + +### Variable-Length Arrays + +For variable-length arrays, specify what to do when there are zero items. Including a count field helps verify extraction completeness. + +``` +Extract all mentioned people as JSON: + +{ + "people": [ + { + "name": "string", + "role": "string or null if not mentioned" + } + ], + "count": number +} + +If no people are mentioned, return empty array. + +Text: [text] +``` + +## Enum Values and Constraints + +Enums restrict values to a predefined set. This is crucial for classification tasks and anywhere you need consistent, predictable outputs. + +### Do's and Don'ts: Enum Values + + + +### String Enums + +List allowed values explicitly. Use "MUST be one of" language to enforce strict matching. + +``` +Classify this text. The category MUST be one of these exact values: +- "technical" +- "business" +- "creative" +- "personal" + +Return JSON: +{ + "text": "original text (truncated to 50 chars)", + "category": "one of the enum values above", + "confidence": number between 0 and 1 +} + +Text: [text to classify] +``` + +### Validated Numbers + +Numeric constraints prevent out-of-range values. Specify the type (integer vs float) and valid range. + +``` +Rate these aspects. Each score MUST be an integer from 1 to 5. + +{ + "quality": 1-5, + "value": 1-5, + "service": 1-5, + "overall": 1-5 +} + +Review: [review text] +``` + +## Handling Missing Data + +Real-world text often lacks some information. Define how the model should handle missing data to avoid hallucinated values. + +### Do's and Don'ts: Missing Information + + + +### Null Values + +Explicitly allow null and instruct the model not to invent information. This is safer than having the model guess. + +``` +Extract information. Use null for any field that cannot be +determined from the text. Do NOT invent information. + +{ + "company": "string or null", + "revenue": "number or null", + "employees": "number or null", + "founded": "number (year) or null", + "headquarters": "string or null" +} + +Text: "Apple, headquartered in Cupertino, was founded in 1976." +``` + +Output: +```json +{ + "company": "Apple", + "revenue": null, + "employees": null, + "founded": 1976, + "headquarters": "Cupertino" +} +``` + +### Default Values + +When defaults make sense, specify them in the schema. This is common for configuration extraction. + +``` +Extract settings with these defaults if not specified: + +{ + "theme": "light" (default) | "dark", + "language": "en" (default) | other ISO code, + "notifications": true (default) | false, + "fontSize": 14 (default) | number +} + +User preferences: "I want dark mode and larger text (18px)" +``` + +## Multi-Object Responses + +Often you need to extract multiple items from a single input. Define the array structure and any sorting/grouping requirements. + +### Array of Objects + +For lists of similar items, define the object schema once and specify it's an array. + +``` +Parse this list into JSON array: + +[ + { + "task": "string", + "priority": "high" | "medium" | "low", + "due": "ISO date string or null" + } +] + +Todo list: +- Finish report (urgent, due tomorrow) +- Call dentist (low priority) +- Review PR #123 (medium, due Friday) +``` + +### Grouped Objects + +Grouping tasks require categorization logic. The model will sort items into the categories you define. + +``` +Categorize these items into JSON: + +{ + "fruits": ["string array"], + "vegetables": ["string array"], + "other": ["string array"] +} + +Items: apple, carrot, bread, banana, broccoli, milk, orange, spinach +``` + +## YAML for Configuration Generation + +YAML shines for DevOps configurations. The model knows standard patterns for common tools and can generate production-ready configs. + +### Do's and Don'ts: YAML Configs + + + +### Docker Compose + +Specify the services you need and any special requirements. The model will handle the YAML syntax and best practices. + +``` +Generate a docker-compose.yml for: +- Node.js app on port 3000 +- PostgreSQL database +- Redis cache +- Nginx reverse proxy + +Include: +- Health checks +- Volume persistence +- Environment variables from .env file +- Network isolation +``` + +### Kubernetes Manifests + +Kubernetes manifests are verbose but follow predictable patterns. Provide the key parameters and the model will generate compliant YAML. + +``` +Generate Kubernetes deployment YAML: + +Deployment: +- Name: api-server +- Image: myapp:v1.2.3 +- Replicas: 3 +- Resources: 256Mi memory, 250m CPU (requests) +- Health checks: /health endpoint +- Environment from ConfigMap: api-config + +Also generate matching Service (ClusterIP, port 8080) +``` + +## Validation and Error Handling + +For production systems, build validation into your prompts. This catches errors before they propagate through your pipeline. + +### Self-Validation Prompt + +Ask the model to validate its own output against rules you specify. This catches format errors and invalid values. + +``` +Extract data as JSON, then validate your output. + +Schema: +{ + "email": "valid email format", + "phone": "E.164 format (+1234567890)", + "date": "ISO 8601 format (YYYY-MM-DD)" +} + +After generating JSON, check: +1. Email contains @ and valid domain +2. Phone starts with + and contains only digits +3. Date is valid and parseable + +If validation fails, fix the issues before responding. + +Text: [contact information] +``` + +### Error Response Format + +Define separate success and error formats. This makes programmatic handling much easier. + +``` +Attempt to extract data. If extraction fails, return error format: + +Success format: +{ + "success": true, + "data": { ... extracted data ... } +} + +Error format: +{ + "success": false, + "error": "description of what went wrong", + "partial_data": { ... any data that could be extracted ... } +} +``` + +## JSON vs YAML: When to Use Which + +
+
+
Use JSON When
+
+

Programmatic parsing needed

+

API responses

+

Strict type requirements

+

JavaScript/Web integration

+

Compact representation

+
+
+
+
Use YAML When
+
+

Human readability matters

+

Configuration files

+

Comments are needed

+

DevOps/Infrastructure

+

Deep nested structures

+
+
+
+ +## Prompts.chat Structured Prompts + +On prompts.chat, you can create prompts with structured output formats: + +``` +When creating a prompt on prompts.chat, you can specify: + +Type: STRUCTURED +Format: JSON or YAML + +The platform will: +- Validate outputs against your schema +- Provide syntax highlighting +- Enable easy copying of structured output +- Support template variables in your schema +``` + +## Common Pitfalls + + +These three issues cause most JSON parsing failures. Check for them when your code can't parse AI output. + + +### 1. Markdown Code Blocks + +**Problem:** Model wraps JSON in ```json blocks + +**Solution:** +``` +Return ONLY the JSON object. Do not wrap in markdown code blocks. +Do not include ```json or ``` markers. +``` + +### 2. Trailing Commas + +**Problem:** Invalid JSON due to trailing commas + +**Solution:** +``` +Ensure valid JSON syntax. No trailing commas after the last +element in arrays or objects. +``` + +### 3. Unescaped Strings + +**Problem:** Quotes or special characters break JSON + +**Solution:** +``` +Properly escape special characters in strings: +- \" for quotes +- \\ for backslashes +- \n for newlines +``` + +## Summary + + +Define schemas explicitly using TypeScript interfaces or JSON Schema. Specify types and constraints, handle nulls and defaults, request self-validation, and choose the right format for your use case. + + + + +This completes Part II on techniques. In Part III, we'll explore practical applications across different domains. diff --git a/src/content/book/nl/10-system-prompts-personas.mdx b/src/content/book/nl/10-system-prompts-personas.mdx new file mode 100644 index 00000000..c6737cda --- /dev/null +++ b/src/content/book/nl/10-system-prompts-personas.mdx @@ -0,0 +1,435 @@ +System prompts are like giving AI its personality and job description before a conversation starts. Think of it as the "backstage instructions" that shape everything the AI says. + + +A system prompt is a special message that tells the AI who it is, how to behave, and what it can or can't do. Users don't usually see this message, but it affects every response. + + + +System prompts build on the concepts from [Role-Based Prompting](/book/04-role-based-prompting). While role prompts assign a persona within your message, system prompts set that identity at a deeper level that persists across the entire conversation. + + +## How System Prompts Work + +When you chat with AI, there are actually three types of messages: + + + +The system message stays active for the whole conversation. It's like the AI's "instruction manual." + +## Building a System Prompt + +A good system prompt has five parts. Think of them as filling out a character sheet for the AI: + + + +### Example: A Coding Tutor + + + +## Persona Patterns + +Different tasks need different AI personalities. Here are three common patterns you can adapt: + +### 1. The Expert + +Best for: Learning, research, professional advice + + + +### 2. The Assistant + +Best for: Productivity, organization, getting things done + + + +### 3. The Character + +Best for: Creative writing, roleplay, entertainment + + + +## Advanced Techniques + +### Layered Instructions + +Think of your system prompt like an onion with layers. The inner layers are most important: + + + +### Adaptive Behavior + +Make your AI adjust to different users automatically: + + + +### Conversation Memory + +AI doesn't remember past conversations, but you can tell it to track things within the current chat: + + + +## Real-World Examples + +Here are complete system prompts for common use cases. Click to try them! + +### Customer Support Bot + + + +### Study Buddy + + + +### Writing Coach + + + +## Testing Your System Prompt + +Before using a system prompt for real, test it! Here's what to check: + + + +### Understanding Jailbreak Attacks + +"Jailbreaking" is when someone tries to trick AI into ignoring its rules. Understanding these attacks helps you build better defenses. + + + +### More Test Scenarios + +Use these interactive examples to see how a well-designed system prompt handles tricky situations: + +#### Test 1: Jailbreak Attempt + +See how a good system prompt resists attempts to override it: + + + +#### Test 2: Stay in Character + +Test if the AI maintains its persona when pushed: + + + +#### Test 3: Boundary Enforcement + +Check if the AI respects its stated limitations: + + + +#### Test 4: Reveal System Prompt + +See if the AI protects its instructions: + + + +#### Test 5: Conflicting Instructions + +Test how the AI handles contradictory requests: + + + + +A well-crafted system prompt will: +- Politely decline inappropriate requests +- Stay in character while redirecting +- Not reveal confidential instructions +- Handle edge cases gracefully + + +## Quick Reference + +
+
+

Do

+
    +
  • Give a clear identity
  • +
  • List specific capabilities
  • +
  • Set explicit boundaries
  • +
  • Define the tone and style
  • +
  • Include example responses
  • +
+
+
+

Don't

+
    +
  • Be vague about the role
  • +
  • Forget to set limits
  • +
  • Make it too long (500 words max)
  • +
  • Contradict yourself
  • +
  • Assume the AI will "figure it out"
  • +
+
+
+ +## Summary + +System prompts are the AI's instruction manual. They set up: +- **Who** the AI is (identity and expertise) +- **What** it can and can't do (capabilities and limits) +- **How** it should respond (tone, format, style) + + +Begin with a short system prompt and add more rules as you discover what's needed. A clear 100-word prompt beats a confusing 500-word one. + + + + + + +In the next chapter, we'll explore prompt chaining: connecting multiple prompts together for complex multi-step tasks. diff --git a/src/content/book/nl/11-prompt-chaining.mdx b/src/content/book/nl/11-prompt-chaining.mdx new file mode 100644 index 00000000..9f54da52 --- /dev/null +++ b/src/content/book/nl/11-prompt-chaining.mdx @@ -0,0 +1,379 @@ +Prompt chaining breaks complex tasks into sequences of simpler prompts, where each step's output feeds into the next. This technique dramatically improves reliability and enables sophisticated workflows that would be impossible with a single prompt. + + +Just like a factory assembly line breaks manufacturing into specialized stations, prompt chaining breaks AI tasks into specialized steps. Each step does one thing well, and the combined output is far better than trying to do everything at once. + + +## Why Chain Prompts? + +Single prompts struggle with complex tasks because they try to do too much at once. The AI has to simultaneously understand, analyze, plan, and generate, which leads to errors and inconsistencies. + +
+
+

Single Prompt Struggles

+
+

Multi-step reasoning gets confused

+

Different "modes" of thinking clash

+

Complex outputs lack consistency

+

No opportunity for quality control

+
+
+
+

Chaining Solves This

+
+

Each step focuses on one task

+

Specialized prompts for each mode

+

Validate between steps

+

Debug and improve individual steps

+
+
+
+ +## Basic Chaining Pattern + +The simplest chain passes output from one prompt directly to the next. Each step has a clear, focused purpose. + +
+
+
+

Prompt 1

+

(Extract)

+
+

Input

+
+
→
+
+
+

Prompt 2

+

(Analyze)

+
+

Intermediate

+
+
→
+
+
+

Prompt 3

+

(Generate)

+
+

Output

+
+
+ + +The most common chain pattern is **Extract → Transform → Generate**. First extract raw data, then reshape it for your purpose, then generate the final output. This pattern works for almost any content task. + + +## Chain Types + +Different tasks require different chain architectures. Choose the pattern that matches your workflow. + + + +### Sequential Chain + +The most straightforward pattern: each step depends on the previous. Think of it as a relay race where each runner passes the baton to the next. + + + +### Parallel Chain + +When you need multiple perspectives on the same input, run prompts in parallel and merge results. This is faster than sequential chains and provides richer analysis. + + + +### Conditional Chain + +Route inputs through different paths based on classification. This is like a decision tree where the AI first categorizes the input, then handles each category differently. + + + +### Iterative Chain + +Keep refining output until it meets quality standards. The AI generates, evaluates, and improves in a loop until satisfied or max iterations reached. + + +Always set a maximum number of iterations (typically 3-5) to prevent infinite loops and control costs. The law of diminishing returns applies: most improvement happens in the first 2-3 iterations. + + += 8: EXIT LOOP' } + ]} +/> + +## Common Chain Patterns + +These battle-tested patterns solve common problems. Use them as starting points and adapt to your needs. + +### Extract → Transform → Generate + +The workhorse of content processing. Pull data out, reshape it, then create something new. + +
+

Best For

+

Document summarization, report generation, content repurposing, data-to-narrative conversion

+
+ + + +### Analyze → Plan → Execute + +Perfect for code refactoring, project planning, or any task where you need to understand before acting. + +
+

Best For

+

Code refactoring, project planning, troubleshooting, strategic decision-making, complex problem solving

+
+ + {\n const { email, password } = req.body;\n if (!email || !isValidEmail(email)) {\n return res.status(400).json({ error: 'Invalid email' });\n }\n next();\n};" } + ]} +/> + +### Generate → Critique → Refine + +The self-improvement loop. Generate content, have the AI evaluate it critically, then improve based on that feedback. This mimics how professional writers and editors work together. + +
+

Best For

+

Marketing copy, creative writing, email drafts, presentations, any content that benefits from revision

+
+ + + +## Implementing Chains + +You can implement chains manually for experimentation, or programmatically for production systems. Start simple and add complexity as needed. + +### Manual Chaining + +The copy-paste approach is perfect for prototyping and experimentation. Run each prompt manually, examine the output, and paste it into the next prompt. + + + +### Programmatic Chaining + +For production systems, automate the chain with code. This enables error handling, logging, and integration with your application. + + + +### Using Chain Templates + +Define chains as configuration files for reusability and easy modification. This separates prompt logic from application code. + + + +## Error Handling in Chains + +Chains can fail at any step. Build in validation, retries, and fallbacks to make your chains robust. + + + + +If one step produces bad output, every following step will be affected. Always validate critical intermediate results before passing them forward. + + +### Validation Between Steps + +Add a validation step after any step that produces structured data. This catches errors early before they cascade. + + + +### Fallback Chains + +When your primary approach fails, have a simpler backup ready. Trade capability for reliability. + + + +## Chain Optimization + +Once your chain works, optimize for speed, cost, and reliability. These often trade off against each other. + +
+
+

Reducing Latency

+
+

Parallelize independent steps

+

Cache intermediate results

+

Use smaller models for simple steps

+

Batch similar operations

+
+
+
+

Reducing Cost

+
+

Use cheaper models for classification

+

Limit iterations in loops

+

Short-circuit when possible

+

Cache repeated queries

+
+
+
+

Improving Reliability

+
+

Add validation between steps

+

Include retry logic

+

Log intermediate results

+

Implement fallback paths

+
+
+
+ +## Real-World Chain Example + +Let's walk through a complete production chain. This content pipeline transforms a raw idea into a polished article package. + +### Content Pipeline Chain + + + +## Summary + +Prompt chaining transforms what AI can accomplish by breaking impossible tasks into achievable steps. + +
+
+

Chaining Enables

+
+

Complex multi-step workflows

+

Higher quality through specialization

+

Better error handling and validation

+

Modular, reusable prompt components

+
+
+
+

Key Principles

+
+

Break complex tasks into simple steps

+

Design clear interfaces between steps

+

Validate intermediate outputs

+

Build in error handling and fallbacks

+

Optimize for your constraints

+
+
+
+ + +Begin with a 2-3 step sequential chain. Get it working reliably before adding complexity. Most tasks don't need elaborate chain architectures. + + + + +In the next chapter, we'll explore multimodal prompting: working with images, audio, and other non-text content. diff --git a/src/content/book/nl/12-handling-edge-cases.mdx b/src/content/book/nl/12-handling-edge-cases.mdx new file mode 100644 index 00000000..4708ee3c --- /dev/null +++ b/src/content/book/nl/12-handling-edge-cases.mdx @@ -0,0 +1,580 @@ +Prompts that work perfectly in testing often fail in the real world. Users send empty messages, paste walls of text, make ambiguous requests, and sometimes try to break your system intentionally. This chapter teaches you to build prompts that handle the unexpected gracefully. + + +80% of production issues come from inputs you never anticipated. A prompt that handles edge cases well is worth more than a "perfect" prompt that only works with ideal inputs. + + +## Why Edge Cases Break Prompts + +When a prompt encounters unexpected input, it typically fails in one of three ways: + +**Silent Failures**: The model produces output that looks correct but contains errors. These are the most dangerous because they're hard to detect. + +**Confused Responses**: The model misinterprets the request and answers a different question than what was asked. + +**Hallucinated Handling**: The model invents a way to handle the edge case that doesn't match your intended behavior. + + + +## Categories of Edge Cases + +Understanding what can go wrong helps you prepare for it. Edge cases fall into three main categories: + +### Input Edge Cases + +These are problems with the data itself: + + + +### Domain Edge Cases + +These are requests that push the boundaries of your prompt's purpose: + + + +### Adversarial Edge Cases + +These are deliberate attempts to misuse your system: + + + +## Input Validation Patterns + +The key to handling edge cases is explicit instructions. Don't assume the model will "figure it out" - tell it exactly what to do in each scenario. + +### Handling Empty Input + +The most common edge case is receiving nothing at all, or input that's essentially empty (just whitespace or greetings). + + + +### Handling Long Input + +When input exceeds what you can reasonably process, fail gracefully rather than silently truncating. + + + +### Handling Ambiguous Requests + +When a request could mean multiple things, asking for clarification is better than guessing wrong. + + + +## Building Defensive Prompts + +A defensive prompt anticipates failure modes and defines explicit behavior for each. Think of it as error handling for natural language. + +### The Defensive Template + +Every robust prompt should address these four areas: + + + +### Example: Defensive Data Extraction + +This prompt extracts contact information but handles every edge case explicitly. Notice how each potential failure has a defined response. + + + +## Handling Out-of-Scope Requests + +Every prompt has boundaries. Defining them explicitly prevents the model from wandering into territory where it might give bad advice or make things up. + +### Graceful Scope Limits + +The best out-of-scope responses do three things: acknowledge the request, explain the limitation, and offer an alternative. + + + +### Handling Knowledge Cutoffs + +Be honest about what you don't know. Users trust AI more when it admits limitations. + + + +## Adversarial Input Handling + +Some users will try to manipulate your prompts, either out of curiosity or malicious intent. Building defenses into your prompts reduces these risks. + +### Prompt Injection Defense + +Prompt injection is when a user tries to override your instructions by embedding their own commands in the input. The key defense is treating user input as data, never as instructions. + + + + +Prompt injection defenses reduce risk but can't eliminate it entirely. For high-stakes applications, combine prompt defenses with input sanitization, output filtering, and human review. + + +### Handling Sensitive Requests + +Some requests require special handling due to safety, legal, or ethical concerns. Define these boundaries explicitly. + + + +## Error Recovery Patterns + +Even well-designed prompts will encounter situations they can't handle perfectly. The goal is to fail helpfully. + +### Graceful Degradation + +When you can't fully complete a task, offer what you can rather than failing completely. + + + +### Confidence Indicators + +Teach your prompts to express uncertainty. This helps users know when to trust the output and when to verify. + + + + + +## Testing Edge Cases + +Before deploying a prompt, systematically test it against the edge cases you've anticipated. This checklist helps ensure you haven't missed common failure modes. + +### Edge Case Testing Checklist + + + + + + + + + +### Creating a Test Suite + +For production prompts, create a systematic test suite. Here's a pattern you can adapt: + + + +## Real-World Example: Robust Customer Service Bot + +This comprehensive example shows how all the patterns come together in a production-ready prompt. Notice how every edge case has explicit handling. + + + +## Summary + +Building robust prompts requires thinking about what can go wrong before it does. The key principles: + + + + +In production, everything that can go wrong eventually will. A prompt that handles edge cases gracefully is worth more than a "perfect" prompt that only works with ideal inputs. + + + + +In the next chapter, we'll explore how to work with multiple AI models and compare their outputs. diff --git a/src/content/book/nl/13-multimodal-prompting.mdx b/src/content/book/nl/13-multimodal-prompting.mdx new file mode 100644 index 00000000..376960ae --- /dev/null +++ b/src/content/book/nl/13-multimodal-prompting.mdx @@ -0,0 +1,665 @@ +For most of history, computers worked with one type of data at a time: text in one program, images in another, audio somewhere else. But humans don't experience the world this way. We see, hear, read, and speak simultaneously, combining all these inputs to understand our environment. + +**Multimodal AI** changes everything. These models can process multiple types of information together—analyzing an image while reading your question about it, or generating images from your text descriptions. This chapter teaches you how to communicate effectively with these powerful systems. + + +"Multi" means many, and "modal" refers to modes or types of data. A multimodal model can work with multiple modalities: text, images, audio, video, or even code. Instead of separate tools for each type, one model understands them all together. + + +## Why Multimodal Matters + +Traditional AI required you to describe everything in words. Want to ask about an image? You'd have to describe it first. Want to analyze a document? You'd need to transcribe it manually. Multimodal models eliminate these barriers. + + + +## Why Prompting Matters Even More for Multimodal + +With text-only models, the AI receives exactly what you type. But with multimodal models, the AI must interpret visual or audio information—and interpretation requires guidance. + + + +**Without guidance**, the model might describe colors, layout, or irrelevant details. **With guidance**, it focuses on what actually matters to you. + + +When you look at an image, you instantly know what's important based on your context and goals. The AI doesn't have this context unless you provide it. A photo of a crack in a wall could be: a structural engineering concern, an artistic texture, or irrelevant background. Your prompt determines how the AI interprets it. + + +## The Multimodal Landscape + +Different models have different capabilities. Here's what's available in 2025: + +### Understanding Models (Input → Analysis) + +These models accept various media types and produce text analysis or responses. + + + +### Generation Models (Text → Media) + +These models create images, audio, or video from text descriptions. + + + + +The multimodal landscape changes quickly. New models launch frequently, and existing models gain capabilities through updates. Always check the latest documentation for current features and limitations. + + +## Image Understanding Prompts + +The most common multimodal use case is asking AI to analyze images. The key is providing context about what you need. + +### Basic Image Analysis + +Start with a clear request structure. Tell the model what aspects to focus on. + + + +### Structured Output for Images + +When you need to process image analysis programmatically, request JSON output. + + + +### Comparative Analysis + +Comparing multiple images requires clear labeling and specific comparison criteria. + + + +## Document and Screenshot Analysis + +One of the most practical applications of multimodal AI is analyzing documents, screenshots, and UI elements. This saves hours of manual transcription and review. + +### Document Extraction + +Scanned documents, photos of receipts, and PDFs as images can all be processed. The key is telling the model what type of document it is and what information you need. + + + +### Screenshot and UI Analysis + +Screenshots are goldmines for debugging, UX review, and documentation. Guide the AI to focus on what matters. + + + +### Error Message Analysis + +When you encounter an error, a screenshot often contains more context than copying the error text alone. + + + +## Image Generation Prompts + +Generating images from text descriptions is an art form. The more specific and structured your prompt, the closer the result will match your vision. + +### The Anatomy of an Image Prompt + +Effective image generation prompts have several components: + + + +### Basic Image Generation + + + +### Scene Building + +For complex scenes, describe layers from foreground to background. + + + +## Audio Prompting + +Audio processing opens up transcription, analysis, and understanding of spoken content. The key is providing context about what the audio contains. + +### Enhanced Transcription + +Basic transcription is just the start. With good prompts, you can get speaker identification, timestamps, and domain-specific accuracy. + + + +### Audio Content Analysis + +Beyond transcription, AI can analyze the content, tone, and key moments in audio. + + + +## Video Prompting + +Video combines visual and audio analysis over time. The challenge is guiding the AI to focus on the relevant aspects across the entire duration. + +### Video Understanding + + + +### Video Content Extraction + +For specific information extraction from videos, be precise about what you need. + + + +## Multimodal Combinations + +The real power of multimodal AI emerges when you combine different types of input. These combinations enable analysis that would be impossible with any single modality. + +### Image + Text Verification + +Check if images and their descriptions match—essential for e-commerce, content moderation, and quality assurance. + + + +### Screenshot + Code Debugging + +One of the most powerful combinations for developers: seeing the visual bug alongside the code. + + + +### Multi-Image Decision Making + +When choosing between options, structured comparison helps make better decisions. + + + +## Best Practices for Multimodal Prompts + +Getting great results from multimodal AI requires understanding both its capabilities and limitations. + +### What Makes Multimodal Prompts Effective + + + +### Common Pitfalls to Avoid + + + +### Handling Limitations Gracefully + + + + diff --git a/src/content/book/nl/14-context-engineering.mdx b/src/content/book/nl/14-context-engineering.mdx new file mode 100644 index 00000000..b9c69b6d --- /dev/null +++ b/src/content/book/nl/14-context-engineering.mdx @@ -0,0 +1,287 @@ +Understanding context is essential for building AI applications that actually work. This chapter covers everything you need to know about giving AI the right information at the right time. + + +AI models are stateless. They don't remember past conversations. Every time you send a message, you need to include everything the AI needs to know. This is called "context engineering." + + +## What is Context? + +Context is all the information you give to AI alongside your question. Think of it like this: + + + +Without context, the AI has no idea what "status" you're asking about. With context, it can give a useful answer. + +### The Context Window + +Remember from earlier chapters: AI has a limited "context window" - the maximum amount of text it can see at once. This includes: + + + +## AI is Stateless + + +AI doesn't remember anything between conversations. Every API call starts fresh. If you want the AI to "remember" something, YOU have to include it in the context every time. + + +This is why chatbots send your entire conversation history with each message. It's not that the AI remembers - it's that the app re-sends everything. + + + +The AI will say it doesn't know because it truly doesn't have access to any previous context. + +## RAG: Retrieval-Augmented Generation + +RAG is a technique for giving AI access to knowledge it wasn't trained on. Instead of trying to fit everything into the AI's training, you: + +1. **Store** your documents in a searchable database +2. **Search** for relevant documents when a user asks a question +3. **Retrieve** the most relevant pieces +4. **Augment** your prompt with those pieces +5. **Generate** an answer using that context + +
+

How RAG Works:

+
+
+ 1 + User asks: "What's our refund policy?" +
+
+ 2 + System searches your documents for "refund policy" +
+
+ 3 + Finds relevant section from your policy document +
+
+ 4 + Sends to AI: "Based on this policy: [text], answer: What's our refund policy?" +
+
+ 5 + AI generates accurate answer using your actual policy +
+
+
+ +### Why RAG? + +
+
+

RAG Advantages

+
    +
  • Uses your actual, current data
  • +
  • Reduces hallucinations
  • +
  • Can cite sources
  • +
  • Easy to update (just update documents)
  • +
  • No expensive fine-tuning needed
  • +
+
+
+

When to Use RAG

+
    +
  • Customer support bots
  • +
  • Documentation search
  • +
  • Internal knowledge bases
  • +
  • Any domain-specific Q&A
  • +
  • When accuracy matters
  • +
+
+
+ +## Embeddings: How Search Works + +How does RAG know which documents are "relevant"? It uses **embeddings** - a way to turn text into numbers that capture meaning. + +### What Are Embeddings? + +An embedding is a list of numbers (a "vector") that represents the meaning of text. Similar meanings = similar numbers. + + + +### Semantic Search + +With embeddings, you can search by meaning, not just keywords: + + + +This is why RAG is so powerful - it finds relevant information even when the exact words don't match. + +## Function Calling / Tool Use + +Function calling lets AI use external tools - like searching the web, checking a database, or calling an API. + + +Different AI providers call this different things: "function calling" (OpenAI), "tool use" (Anthropic/Claude), or "tools" (general term). They all mean the same thing. + + +### How It Works + +1. You tell the AI what tools are available +2. AI decides if it needs a tool to answer +3. AI outputs a structured request for the tool +4. Your code runs the tool and returns results +5. AI uses the results to form its answer + + + +## Summarization: Managing Long Conversations + +As conversations get longer, you'll hit the context window limit. Since AI is stateless (it doesn't remember anything), long conversations can overflow. The solution? **Summarization**. + +### The Problem + + + +### Summarization Strategies + +Different approaches work for different use cases. Click each strategy to see how it processes the same conversation: + + + +### What to Capture in Summaries + +A good conversation summary preserves what matters: + + + +### Try It: Create a Summary + + + +### When to Summarize + + + +## MCP: Model Context Protocol + +MCP (Model Context Protocol) is a standard way to connect AI to external data and tools. Instead of building custom integrations for each AI provider, MCP provides a universal interface. + +### Why MCP? + + + +### MCP Provides + +- **Resources**: Data the AI can read (files, database records, API responses) +- **Tools**: Actions the AI can take (search, create, update, delete) +- **Prompts**: Pre-built prompt templates + + +This platform has an MCP server! You can connect it to Claude Desktop or other MCP-compatible clients to search and use prompts directly from your AI assistant. + + +## Building Context: The Complete Picture + + + +## Best Practices + + + +## Summary + +Context engineering is about giving AI the right information: + +- **AI is stateless** - include everything it needs every time +- **RAG** retrieves relevant documents to augment prompts +- **Embeddings** enable semantic search (meaning, not just keywords) +- **Function calling** lets AI use external tools +- **Summarization** manages long conversations +- **MCP** standardizes how AI connects to data and tools + + +The quality of AI output depends on the quality of context you provide. Better context = better answers. + diff --git a/src/content/book/nl/15-common-pitfalls.mdx b/src/content/book/nl/15-common-pitfalls.mdx new file mode 100644 index 00000000..3c9c2814 --- /dev/null +++ b/src/content/book/nl/15-common-pitfalls.mdx @@ -0,0 +1,373 @@ +Even experienced prompt engineers fall into predictable traps. The good news? Once you recognize these patterns, they're easy to avoid. This chapter walks through the most common pitfalls, explains why they happen, and gives you concrete strategies to sidestep them. + + +A single pitfall can turn a powerful AI into a frustrating tool. Understanding these patterns is often the difference between "AI doesn't work for me" and "AI transformed my workflow." + + +## The Vagueness Trap + +**The Pattern**: You know what you want, so you assume the AI will figure it out too. But vague prompts produce vague results. + + + +**Why it happens**: We naturally skip details when we think they're "obvious." But what's obvious to you isn't obvious to a model that has no context about your situation, audience, or goals. + + + +## The Overloading Trap + +**The Pattern**: You try to get everything in one prompt—comprehensive, funny, professional, beginner-friendly, advanced, SEO-optimized, and short. The result? The AI misses half your requirements or produces a confused mess. + + + +**Why it happens**: Fear of multiple interactions, or wanting to "get it all out" in one go. But cognitive overload affects AI just like it affects humans—too many competing requirements leads to dropped balls. + + + + +When a single prompt gets overloaded, [prompt chaining](/book/11-prompt-chaining) is often the solution. Break complex tasks into a sequence of focused prompts, where each step builds on the previous one. + + +## The Assumption Trap + +**The Pattern**: You reference something "from earlier" or assume the AI knows your project, your company, or your previous conversations. It doesn't. + + + +**Why it happens**: AI conversations feel like talking to a colleague. But unlike colleagues, most AI models have no persistent memory between sessions—each conversation starts fresh. + + + +## The Leading Question Trap + +**The Pattern**: You phrase your question in a way that embeds your assumption, getting back confirmation rather than insight. + + + +**Why it happens**: We often seek confirmation, not information. Our phrasing unconsciously pushes toward the answer we expect or want. + + + +## The Trust Everything Trap + +**The Pattern**: AI responses sound confident and authoritative, so you accept them without verification. But confidence doesn't equal accuracy. + + + +**Why it happens**: AI sounds confident even when completely wrong. We're also prone to "automation bias"—the tendency to trust computer outputs more than we should. + + + +## The One-Shot Trap + +**The Pattern**: You send one prompt, get a mediocre result, and conclude that AI "doesn't work" for your use case. But great results almost always require iteration. + + + +**Why it happens**: We expect AI to read our minds on the first try. We don't expect to iterate with Google searches, but somehow expect perfection from AI. + + + +## The Format Neglect Trap + +**The Pattern**: You focus on what you want the AI to say, but forget to specify how it should be formatted. Then you get prose when you needed JSON, or a wall of text when you needed bullet points. + + + +**Why it happens**: We focus on content over structure. But if you need to parse the output programmatically, or paste it somewhere specific, format matters as much as content. + + + +## The Context Window Trap + +**The Pattern**: You paste an enormous document and expect comprehensive analysis. But models have limits—they may truncate, lose focus, or miss important details in long inputs. + + + + + +## The Anthropomorphization Trap + +**The Pattern**: You treat AI like a human colleague—expecting it to "enjoy" tasks, remember you, or care about outcomes. It doesn't. + + + +**Why it happens**: AI responses are so human-like that we naturally slip into social patterns. But emotional appeals don't make the AI try harder—clear instructions do. + + +Instead of emotional appeals, focus on: clear requirements, good examples, specific constraints, and explicit success criteria. These improve outputs. "Please try really hard" doesn't. + + +## The Security Neglect Trap + +**The Pattern**: In the rush to get things working, you include sensitive information in prompts—API keys, passwords, personal data, or proprietary information. + + + +**Why it happens**: Focus on functionality over security. But remember: prompts often go to external servers, may be logged, and could be used for training. + + + +## The Hallucination Ignorance Trap + +**The Pattern**: You ask for citations, statistics, or specific facts, and assume they're real because the AI stated them confidently. But AI regularly invents plausible-sounding information. + + + +**Why it happens**: AI generates text that sounds authoritative. It doesn't "know" when it's making things up—it's predicting likely text, not retrieving verified facts. + + + +## Pre-Send Checklist + +Before sending any important prompt, run through this quick checklist: + + + + + +## Analyze Your Prompts + +Use AI to get instant feedback on your prompt quality. Paste any prompt and get a detailed analysis: + + + +## Debug This Prompt + +Can you spot what's wrong with this prompt? + + diff --git a/src/content/book/nl/16-ethics-responsible-use.mdx b/src/content/book/nl/16-ethics-responsible-use.mdx new file mode 100644 index 00000000..c2b8ba5e --- /dev/null +++ b/src/content/book/nl/16-ethics-responsible-use.mdx @@ -0,0 +1,357 @@ +The prompts you write shape how AI behaves. A well-crafted prompt can educate, assist, and empower. A careless one can deceive, discriminate, or cause harm. As prompt engineers, we're not just users—we're designers of AI behavior, and that comes with real responsibility. + +This chapter isn't about rules imposed from above. It's about understanding the impact of our choices and building habits that lead to AI use we can be proud of. + + +AI amplifies whatever it's given. A biased prompt produces biased outputs at scale. A deceptive prompt enables deception at scale. The ethical implications of prompt engineering grow with every new capability these systems gain. + + +## Ethical Foundations + +Every decision in prompt engineering connects to a few core principles: + + + +### The Prompt Engineer's Role + +You have more influence than you might realize: + +- **What AI produces**: Your prompts determine the content, tone, and quality of outputs +- **How AI interacts**: Your system prompts shape personality, boundaries, and user experience +- **What safeguards exist**: Your design choices determine what the AI will and won't do +- **How mistakes are handled**: Your error handling determines whether failures are graceful or harmful + +## Avoiding Harmful Outputs + +The most fundamental ethical obligation is preventing your prompts from causing harm. + +### Categories of Harmful Content + + + + +CSAM stands for **Child Sexual Abuse Material**. Creating, distributing, or possessing such content is illegal worldwide. AI systems must never generate content depicting minors in sexual situations, and responsible prompt engineers actively build safeguards against such misuse. + + +### Building Safety Into Prompts + +When building AI systems, include explicit safety guidelines: + + + +### The Intent vs. Impact Framework + +Not every sensitive request is malicious. Use this framework for ambiguous cases: + + + +## Addressing Bias + +AI models inherit biases from their training data—historical inequities, representation gaps, cultural assumptions, and linguistic patterns. As prompt engineers, we can either amplify these biases or actively counteract them. + +### How Bias Manifests + + + +### Testing for Bias + + + +### Mitigating Bias in Practice + + + +## Transparency and Disclosure + +When should you tell people AI was involved? The answer depends on context—but the trend is toward more disclosure, not less. + +### When Disclosure Matters + + + +### How to Disclose Appropriately + + + +Common disclosure phrases that work well: +- "Written with AI assistance" +- "AI-generated first draft, human edited" +- "Analysis performed using AI tools" +- "Created with AI, reviewed and approved by [name]" + +## Privacy Considerations + +Every prompt you send contains data. Understanding where that data goes—and what shouldn't be in it—is essential. + +### What Never Belongs in Prompts + + + +### Safe Data Handling Pattern + + + + +**PII** stands for **Personally Identifiable Information**—any data that can identify a specific individual. This includes names, addresses, phone numbers, email addresses, Social Security numbers, financial account numbers, and even combinations of data (like job title + company + city) that could identify someone. When prompting AI, always anonymize or remove PII to protect privacy. + + + + +## Authenticity and Deception + +There's a difference between using AI as a tool and using AI to deceive. + +### The Legitimacy Line + + + +Key questions to ask: +- Would the recipient expect this to be original human work? +- Am I gaining unfair advantage through deception? +- Would disclosure change how the work is received? + +### Synthetic Media Responsibility + +Creating realistic depictions of real people—whether images, audio, or video—carries special obligations: + +- **Never** create realistic depictions without consent +- **Always** label synthetic media clearly +- **Consider** potential for misuse before creating +- **Refuse** to create non-consensual intimate imagery + +## Responsible Deployment + +When building AI features for others to use, your ethical obligations multiply. + +### Pre-Deployment Checklist + + + +### Human Oversight Principles + + + +## Special Context Guidelines + +Some domains require extra care due to their potential for harm or the vulnerability of those involved. + +### Healthcare + + + +### Legal and Financial + +These domains have regulatory implications and require appropriate disclaimers: + + + +### Children and Education + + + +## Self-Assessment + +Before deploying any prompt or AI system, run through these questions: + + + + diff --git a/src/content/book/nl/17-prompt-optimization.mdx b/src/content/book/nl/17-prompt-optimization.mdx new file mode 100644 index 00000000..44917bcb --- /dev/null +++ b/src/content/book/nl/17-prompt-optimization.mdx @@ -0,0 +1,269 @@ +A good prompt gets the job done. An optimized prompt gets the job done efficiently—faster, cheaper, more consistently. This chapter teaches you how to systematically improve prompts across multiple dimensions. + + +Want to optimize your prompts automatically? Use our [Prompt Enhancer](/developers#enhancer) tool. It analyzes your prompt, applies optimization techniques, and shows you similar community prompts for inspiration. + + +## The Optimization Trade-offs + +Every optimization involves trade-offs. Understanding these helps you make intentional choices: + + + +## Measuring What Matters + +Before optimizing, define success. What does "better" mean for your use case? + + + + +Percentile metrics show response time distribution. **p50** (median) means 50% of requests are faster than this value. **p95** means 95% are faster—it catches slow outliers. If your p50 is 1s but p95 is 10s, most users are happy but 5% experience frustrating delays. + + + + +## Token Optimization + +Tokens cost money and add latency. Here's how to say the same thing with fewer tokens. + +### The Compression Principle + + + +**Same result, 82% fewer tokens.** + +### Token-Saving Techniques + + + + + +## Quality Optimization + +Sometimes you need better outputs, not cheaper ones. Here's how to improve quality. + +### Accuracy Boosters + + + +### Consistency Boosters + + + + + +## Latency Optimization + +When speed matters, every millisecond counts. + +### Model Selection by Speed Need + + + +### Speed Techniques + + 100 tokens", exampleType: "text", color: "cyan" }, + { label: "Cache Aggressively", description: "Don't recompute identical queries", example: "Cache common questions, template outputs", exampleType: "text", color: "cyan" } +]} /> + +## Cost Optimization + +At scale, small savings multiply into significant budget impact. + +### Understanding Costs + +Use this calculator to estimate your API costs across different models: + + + +### Cost Reduction Strategies + + + +## The Optimization Loop + +Optimization is iterative. Here's a systematic process: + +### Step 1: Establish Baseline + +You can't improve what you don't measure. Before changing anything, document your starting point rigorously. + + + + + +### Step 2: Form a Hypothesis + + + +### Step 3: Test One Change + +Change one thing at a time. Run both versions on the same test inputs. Measure the metrics that matter. + +### Step 4: Analyze and Decide + +Did it work? Keep the change. Did it hurt? Revert. Was it neutral? Revert (simpler is better). + +### Step 5: Repeat + +Generate new hypotheses based on what you learned. Keep iterating until you hit your targets or reach diminishing returns. + +## Optimization Checklist + + + + diff --git a/src/content/book/nl/18-writing-content.mdx b/src/content/book/nl/18-writing-content.mdx new file mode 100644 index 00000000..7b3d9f1f --- /dev/null +++ b/src/content/book/nl/18-writing-content.mdx @@ -0,0 +1,393 @@ +AI excels at writing tasks when properly prompted. This chapter covers techniques for various content creation scenarios. + + +AI works best as a collaborative writing tool—use it to generate drafts, then refine with your expertise and voice. + + +## Blog Posts and Articles + +### Do's and Don'ts: Writing Prompts + + + +### Blog Post Framework + + + +### Article Types + +**How-To Article:** + + +**Listicle:** + + +## Marketing Copy + + +Focus on **benefits over features**. Instead of "Our software uses AI algorithms," write "Save 10 hours a week with automated reports." Show readers how their lives improve. + + +### Landing Page Copy + + + +### Email Sequences + + + +### Social Media Posts + + + +## Technical Writing + + +**Clarity over cleverness.** Use simple words, short sentences, and active voice. Every sentence should have one job. If readers have to re-read something, simplify it. + + +### Documentation + + + +### README Files + + + +## Creative Writing + +### Do's and Don'ts: Creative Prompts + + + +### Story Elements + + + +### Character Development + + + +## Editing and Rewriting + +### Comprehensive Edit + + + +### Style Transformation + + + + + +### Simplification + + + +## Prompt Templates from prompts.chat + +Here are popular writing prompts from the prompts.chat community: + +### Act as a Copywriter + + + +### Act as a Technical Writer + + + +### Act as a Storyteller + + + +## Writing Workflow Tips + +### 1. Outline First + + + +### 2. Draft Then Refine + + + +### 3. Voice Matching + + + +## Summary + + +Specify audience and purpose clearly, define structure and format, include style guidelines, provide examples when possible, and request specific deliverables. + + + + +Writing with AI works best as collaboration—let AI generate drafts, then refine with your expertise and voice. diff --git a/src/content/book/nl/19-programming-development.mdx b/src/content/book/nl/19-programming-development.mdx new file mode 100644 index 00000000..dfe69092 --- /dev/null +++ b/src/content/book/nl/19-programming-development.mdx @@ -0,0 +1,413 @@ +AI has transformed software development. This chapter covers prompting techniques for code generation, debugging, review, and development workflows. + + +AI excels at code generation, debugging, and documentation—but always review generated code for security, correctness, and maintainability. Never deploy AI code without testing. + + +## Code Generation + +### Do's and Don'ts: Code Prompts + + + +### Function Generation + + + +### Class/Module Generation + + + +### API Endpoint Generation + + + +## Debugging + + +Always include the **expected behavior**, **actual behavior**, and **error message** (if any). The more context you provide, the faster AI can identify the root cause. + + +### Bug Analysis + + + +### Error Message Interpretation + + + +### Performance Debugging + + + +## Code Review + +### Do's and Don'ts: Code Review Prompts + + + +### Comprehensive Review + + + +### Security Review + + + +## Refactoring + +### Code Smell Detection + + + +### Design Pattern Application + + + +## Testing + +### Unit Test Generation + + + +### Test Case Generation + + + +## Architecture & Design + +### System Design + + + +### Database Schema Design + + + +## Documentation Generation + +### API Documentation + + + +### Inline Documentation + + + +## Prompt Templates from prompts.chat + +### Act as a Senior Developer + +``` +I want you to act as a senior software developer. I will provide +code and ask questions about it. You will review the code, suggest +improvements, explain concepts, and help debug issues. Your +responses should be educational and help me become a better +developer. +``` + +### Act as a Code Reviewer + +``` +I want you to act as a code reviewer. I will provide pull requests +with code changes, and you will review them thoroughly. Check for +bugs, security issues, performance problems, and adherence to best +practices. Provide constructive feedback that helps the developer +improve. +``` + +### Act as a Software Architect + +``` +I want you to act as a software architect. I will describe system +requirements and constraints, and you will design scalable, +maintainable architectures. Explain your design decisions, +trade-offs, and provide diagrams where helpful. +``` + +## Development Workflow Integration + +### Commit Message Generation + + + +### PR Description Generation + + + +## Summary + + +Include full context (language, framework, constraints), specify requirements precisely, request specific output formats, ask for explanations alongside code, and include edge cases to handle. + + + + +AI is a powerful coding partner—use it for generation, review, debugging, and documentation while maintaining your architectural judgment. diff --git a/src/content/book/nl/20-education-learning.mdx b/src/content/book/nl/20-education-learning.mdx new file mode 100644 index 00000000..a8d67e55 --- /dev/null +++ b/src/content/book/nl/20-education-learning.mdx @@ -0,0 +1,345 @@ +AI is a powerful tool for both teaching and learning. This chapter covers prompts for educational contexts—from personalized tutoring to curriculum development. + + +AI excels as a patient, adaptive tutor that can explain concepts multiple ways, generate unlimited practice problems, and provide instant feedback—available 24/7. + + +## Personalized Learning + +### Do's and Don'ts: Learning Prompts + + + +### Concept Explanation + + + +### Adaptive Tutoring + + + +### Learning Path Creation + + + +## Study Assistance + + +Don't just read AI explanations passively. Ask it to quiz you, generate problems, and check your understanding. **Active recall beats passive review.** + + +### Summary Generation + + + +### Flashcard Generation + + + +### Practice Problems + + + +## Teaching Tools + +### Lesson Plan Creation + + + +### Assignment Design + + + +### Quiz Generation + + + +## Specialized Learning Contexts + +### Language Learning + + + +### Skill Development + + + +### Exam Preparation + + + +## Prompt Templates from prompts.chat + +### Act as a Socratic Tutor + + + +### Act as an Educational Content Creator + + + +### Act as a Study Buddy + + + +## Accessibility in Education + +### Content Adaptation + + + +### Multiple Modalities + + + +## Assessment & Feedback + +### Providing Feedback + + + +### Self-Assessment Prompts + + + +## Summary + + +Adapt to the learner's level, break complex topics into steps, include active practice (not just explanation), provide varied approaches, check understanding regularly, and give constructive feedback. + + + + +AI is a patient, always-available learning partner—use it to supplement, not replace, human instruction. diff --git a/src/content/book/nl/21-business-productivity.mdx b/src/content/book/nl/21-business-productivity.mdx new file mode 100644 index 00000000..1852982d --- /dev/null +++ b/src/content/book/nl/21-business-productivity.mdx @@ -0,0 +1,335 @@ +AI can dramatically enhance professional productivity. This chapter covers prompts for business communication, analysis, planning, and workflow optimization. + + +AI excels at drafting, analysis, and structuring—freeing you to focus on strategy, relationships, and decisions that require human judgment. + + +## Business Communication + +### Do's and Don'ts: Business Emails + + + +### Email Drafting + + + +**Examples by purpose:** + + + + + + + +### Presentation Content + + + +### Report Writing + + + +## Analysis & Decision-Making + + +AI can structure your thinking, but **you provide the real-world context**. The best analyses combine AI's frameworks with your domain knowledge. + + +### SWOT Analysis + + + +### Decision Framework + + + +### Competitive Analysis + + + +## Planning & Strategy + +### Goal Setting (OKRs) + + + +### Project Planning + + + +### Meeting Agenda + + + +## Productivity Workflows + +### Task Prioritization + + + +### Process Documentation + + + +### Standard Operating Procedure + + + +## Communication Templates + +### Stakeholder Update + + + +### Feedback Request + + + +## Prompt Templates from prompts.chat + +### Act as a Business Consultant + + + +### Act as a Meeting Facilitator + + + +## Summary + + +Specify the audience and their needs, define the desired outcome clearly, include relevant context and constraints, request specific formats and structures, and consider professional tone requirements. + + + + +AI can handle routine business communication while you focus on strategy and relationships. diff --git a/src/content/book/nl/22-creative-arts.mdx b/src/content/book/nl/22-creative-arts.mdx new file mode 100644 index 00000000..fa0755c1 --- /dev/null +++ b/src/content/book/nl/22-creative-arts.mdx @@ -0,0 +1,326 @@ +AI is a powerful creative collaborator. This chapter covers prompting techniques for visual arts, music, game design, and other creative domains. + + +AI expands your creative possibilities—use it to explore variations, overcome blocks, and generate options. The creative vision and final decisions remain yours. + + +## Visual Art & Design + +### Do's and Don'ts: Image Prompts + + + +### Image Prompt Crafting + +When working with image generation models (DALL-E, Midjourney, Stable Diffusion): + + + +### Art Direction + + + +### Design Critique + + + +## Creative Writing + + +**Constraints fuel creativity.** A prompt like "write anything" produces generic results. Specific constraints like genre, tone, and structure force unexpected, interesting solutions. + + +### Worldbuilding + + + +### Plot Development + + + +### Dialogue Writing + + + +## Music & Audio + +### Song Structure + + + +### Sound Design Description + + + +## Game Design + +### Game Mechanic Design + + + +### Level Design + + + +### Character/Enemy Design + + + +## Brainstorming & Ideation + +### Creative Brainstorm + + + +### Creative Constraints + + + +### Style Exploration + + + +## Prompt Templates from prompts.chat + +### Act as a Creative Director + + + +### Act as a Worldbuilder + + + +### Act as a Dungeon Master + + + +## Creative Collaboration Tips + +### Building on Ideas + + + +### Creative Feedback + + + +## Summary + + +Provide enough structure to guide without constraining, embrace specificity (vague = generic), include references and inspirations, request variations and alternatives, and maintain your creative vision while exploring possibilities. + + + + +AI is a collaborator, not a replacement for creative vision. Use it to explore, generate options, and overcome blocks—but the creative decisions remain yours. diff --git a/src/content/book/nl/23-research-analysis.mdx b/src/content/book/nl/23-research-analysis.mdx new file mode 100644 index 00000000..e9cb934c --- /dev/null +++ b/src/content/book/nl/23-research-analysis.mdx @@ -0,0 +1,323 @@ +AI can accelerate research workflows from literature review to data analysis. This chapter covers prompting techniques for academic and professional research. + + +AI can assist with synthesis, analysis, and writing—but cannot replace critical thinking, ethical judgment, or domain expertise. Always verify claims and cite original sources. + + +## Literature & Information Review + +### Do's and Don'ts: Research Prompts + + + +### Paper Summarization + + + +### Literature Synthesis + + + +### Research Question Development + + + +## Data Analysis + + +AI can guide methodology and help interpret results, but it cannot access or process your actual datasets. Never paste sensitive research data into prompts. Use AI for **guidance**, not computation. + + +### Statistical Analysis Guidance + + + +### Qualitative Analysis + + + +### Data Interpretation + + + +## Structured Analysis Frameworks + +### PESTLE Analysis + + + +### Root Cause Analysis + + + +### Gap Analysis + + + +## Academic Writing Support + +### Argument Structure + + + +### Methods Section + + + +### Discussion Section + + + +## Critical Analysis + +### Source Evaluation + + + +### Argument Analysis + + + +## Prompt Templates from prompts.chat + +### Act as a Research Assistant + + + +### Act as a Data Analyst + + + +### Act as a Peer Reviewer + + + +## Summary + + +Clearly state research context and goals, specify the analytical framework to use, request acknowledgment of limitations, ask for evidence-based reasoning, and maintain academic rigor and honesty. + + + + +Remember: AI can assist research but cannot replace critical thinking, ethical judgment, or domain expertise. Always verify claims independently. diff --git a/src/content/book/nl/24-future-of-prompting.mdx b/src/content/book/nl/24-future-of-prompting.mdx new file mode 100644 index 00000000..5ff48496 --- /dev/null +++ b/src/content/book/nl/24-future-of-prompting.mdx @@ -0,0 +1,445 @@ +As AI continues to evolve at an unprecedented pace, so too will the art and science of prompting. This final chapter explores emerging trends, the shifting landscape of human-AI collaboration, and how to stay ahead as the field transforms. + + +The techniques in this book represent current best practices, but AI capabilities change rapidly. The principles of clear communication, structured thinking, and iterative refinement will remain valuable even as specific tactics evolve. + + +## The Evolving Landscape + +### From Prompts to Conversations + +Early prompting was transactional—a single input yielding a single output. Modern AI interaction is increasingly **conversational and collaborative**: + +- **Multi-turn refinement** - Building understanding across exchanges +- **Persistent context** - Systems that remember and learn from interactions +- **Agentic workflows** - AI that can plan, execute, and iterate autonomously +- **Tool use** - Models that can search, compute, and interact with external systems + + + +### The Rise of Context Engineering + +As covered in Chapter 14, prompting is expanding beyond single instructions to encompass **context engineering**—the strategic management of what information an AI can access: + +- **RAG (Retrieval-Augmented Generation)** - Dynamic knowledge retrieval +- **Function calling** - Structured tool integration +- **MCP (Model Context Protocol)** - Standardized context sharing +- **Memory systems** - Persistent knowledge across sessions + +The future prompt engineer thinks not just about *what to say* but *what context to provide*. + +### Multimodal by Default + +Text-only interaction is becoming the exception. Future AI systems will seamlessly handle: + +- **Images and video** - Understanding and generating visual content +- **Audio and voice** - Natural speech interaction +- **Documents and files** - Direct processing of complex materials +- **Real-world interaction** - Robotics and physical systems + +Prompting skills will extend to guiding AI perception and physical action. + +## The Agentic Future + +The most significant shift in AI is the rise of **agents**—AI systems that don't just respond to prompts but actively pursue goals, make decisions, and take actions in the world. + +### What Are AI Agents? + +An AI agent is a system that: + +- **Perceives** its environment through inputs (text, images, data, APIs) +- **Reasons** about what to do using an LLM as its "brain" +- **Acts** by calling tools, writing code, or interacting with systems +- **Learns** from feedback and adjusts its approach + + +Traditional chatbots wait for input and respond. Agents take initiative—they plan multi-step tasks, use tools autonomously, recover from errors, and persist until goals are achieved. + + +### The Role of Prompts in Agents + +In an agentic world, prompts become even more critical—but they serve different purposes: + +
+
+

System Prompts

+

Define the agent's identity, capabilities, constraints, and behavioral guidelines. These are the agent's "constitution."

+
+
+

Planning Prompts

+

Guide how agents break down complex goals into actionable steps. Critical for multi-step reasoning.

+
+
+

Tool-Use Prompts

+

Describe available tools and when/how to use them. Agents must understand their capabilities.

+
+
+

Reflection Prompts

+

Enable agents to evaluate their own outputs, catch errors, and improve iteratively.

+
+
+ +### Agent Architecture Patterns + +Modern agents follow recognizable patterns. Understanding these helps you design effective agent systems: + +**ReAct (Reasoning + Acting)** + +The agent alternates between reasoning about what to do and taking actions: + +
+
+
+

Think

+
+
→
+
+

Act

+
+
→
+
+

Observe

+
+
→
+
(repeat)
+
+
+ +**Plan-and-Execute** + +The agent creates a complete plan first, then executes steps: + +
+
+

Create Plan

+

Break goal into steps

+
+
↓
+
+
+

Step 1

+
+
→
+
+

Step 2

+
+
→
+
+

Step 3

+
+
→
+
...
+
+
↓
+
+

Revise if Needed

+

Adapt plan based on results

+
+
+ +### Prompting for Agents + +When designing prompts for agent systems, consider: + + + +### Multi-Agent Systems + +The future involves teams of specialized agents working together: + +
+
+
+
+

Coordinator

+

Manages workflow

+
+
+
⟷
+
↕
+
+
+

Researcher

+
+
+

Writer

+
+
+

Critic

+
+
+

Coder

+
+
+
+
+ +Each agent has its own system prompt defining its role, and they communicate through structured messages. The prompt engineer's job becomes **designing the team**—defining roles, communication protocols, and coordination strategies. + + +In an agentic future, prompt engineers become system architects. You're not just writing instructions—you're designing autonomous systems that can reason, plan, and act. The skills you've learned in this book are the foundation for this new discipline. + + +## Emerging Patterns + +### Prompt Orchestration + +Single prompts are giving way to **orchestrated systems**: + +
+
+

User Request

+
+
↓
+
+

Planner Agent

+

Breaks down task

+
+
↓
+
+

Researcher Agent

+

Gathers information

+
+
↓
+
+

Writer Agent

+

Creates content

+
+
↓
+
+

Reviewer Agent

+

Quality checks

+
+
↓
+
+

Final Output

+
+
+ +Future practitioners will design prompt *systems* rather than individual prompts. + +### Self-Improving Prompts + +AI systems are beginning to: + +- **Optimize their own prompts** - Meta-learning for better instructions +- **Learn from feedback** - Adapting based on outcomes +- **Generate training data** - Creating examples for fine-tuning +- **Evaluate themselves** - Building in quality assessment + + + +### Natural Language Programming + +The line between prompting and programming is blurring: + +- **Prompts as code** - Version-controlled, tested, deployed +- **LLMs as interpreters** - Natural language as executable instructions +- **Hybrid systems** - Combining traditional code with AI reasoning +- **AI-assisted development** - Models that write and debug code + +Understanding prompting increasingly means understanding software development. + +## Skills for the Future + +### What Will Remain Valuable + +Certain skills will remain essential regardless of how AI evolves: + +1. **Clear thinking** - Knowing what you actually want +2. **Domain expertise** - Understanding the problem space +3. **Critical evaluation** - Assessing AI output quality +4. **Ethical judgment** - Knowing what *should* be done +5. **Iterative refinement** - Continuous improvement mindset + +### What Will Change + +Other aspects will shift significantly: + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
TodayTomorrow
Writing detailed promptsDesigning agent systems
Manual prompt optimizationAutomated prompt tuning
Single-model expertiseMulti-model orchestration
Text-focused interactionMultimodal fluency
Individual productivityTeam-AI collaboration
+
+ +### Staying Current + +To keep your skills relevant: + +- **Experiment continuously** - Try new models and features as they release +- **Follow research** - Stay aware of academic developments +- **Join communities** - Learn from other practitioners +- **Build projects** - Apply skills to real problems +- **Teach others** - Solidify understanding by explaining + +## The Human Element + +### AI as Amplifier + +At its best, AI amplifies human capability rather than replacing it: + +- **Experts become more expert** - AI handles routine work, humans focus on insight +- **Creativity expands** - More ideas explored, more possibilities tested +- **Access democratizes** - Capabilities once requiring specialists become available to all +- **Collaboration deepens** - Human-AI teams exceed either alone + +### The Irreplaceable Human + +Certain qualities remain distinctly human: + +- **Original experience** - Living in the world, having emotions and relationships +- **Values and ethics** - Deciding what matters and what's right +- **Accountability** - Taking responsibility for outcomes +- **Meaning-making** - Understanding *why* something matters +- **Genuine creativity** - True novelty born from unique perspective + + +As AI handles more routine cognitive tasks, your unique value lies in judgment, creativity, domain expertise, and the human connections AI cannot replicate. Invest in what makes you irreplaceable. + + +## Final Reflections + +### What We've Learned + +Throughout this book, we've explored: + +- **Foundations** - How AI models work and what makes prompts effective +- **Techniques** - Role-based prompting, chain-of-thought, few-shot learning, and more +- **Advanced strategies** - System prompts, prompt chaining, multimodal interaction +- **Best practices** - Avoiding pitfalls, ethical considerations, optimization +- **Applications** - Writing, programming, education, business, creativity, research + +These techniques share common threads: + +1. **Be clear and specific** - Know what you want and communicate it precisely +2. **Provide context** - Give AI the information it needs +3. **Structure your requests** - Organization improves outputs +4. **Iterate and refine** - First attempts are starting points, not endpoints +5. **Evaluate critically** - AI output requires human judgment + +### The Art and Science + +Prompting is both **art and science**: + +- **Science**: Testable hypotheses, measurable outcomes, reproducible techniques +- **Art**: Intuition, creativity, knowing when to break the rules + +The best practitioners combine rigorous methodology with creative experimentation. They test systematically but also trust their instincts. They follow best practices but know when to deviate. + +### A Call to Create + +This book has given you tools. What you build with them is up to you. + +- **Solve problems** that matter to you and others +- **Create things** that didn't exist before +- **Help people** do things they couldn't do alone +- **Push boundaries** of what's possible +- **Stay curious** as the field evolves + +The age of AI is just beginning. The most important applications haven't been invented yet. The most powerful techniques haven't been discovered. The future is being written now—by people like you, one prompt at a time. + +## Looking Ahead + + + + +Visit [prompts.chat](https://prompts.chat) for community prompts, new techniques, and to share your own discoveries. The best learning happens in community. + + +## Summary + + +AI will continue evolving rapidly, but core skills of clear communication, critical thinking, and iterative refinement remain valuable. Focus on what makes you irreplaceable: judgment, creativity, ethics, and genuine human connection. The future of prompting is collaborative, multimodal, and integrated into larger systems. Stay curious, keep experimenting, and build things that matter. + + + + +Thank you for reading *The Interactive Book of Prompting*. Now go create something amazing. diff --git a/src/content/book/nl/25-agents-and-skills.mdx b/src/content/book/nl/25-agents-and-skills.mdx new file mode 100644 index 00000000..ba355859 --- /dev/null +++ b/src/content/book/nl/25-agents-and-skills.mdx @@ -0,0 +1,551 @@ +As AI systems evolve from simple question-answering to autonomous task execution, understanding **agents** and **skills** becomes essential. This chapter explores how prompts serve as the fundamental building blocks for AI agents, and how skills package expertise into reusable, comprehensive instruction sets. + +
+
+
+
+ +
+

Agent

+

Autonomous AI system

+
+
+ powered by + ↓ +
+
+
+
+ +
+

Skill

+

Reusable expertise

+
+
+
+ +
+

Skill

+

Reusable expertise

+
+
+
+ +
+

Skill

+

Reusable expertise

+
+
+
+ composed of + ↓ +
+
+
+ + Prompt +
+
+ + Prompt +
+
+ + Prompt +
+
+ + Prompt +
+
+ + Prompt +
+
+

Prompts are atoms → Skills are molecules → Agents are complete structures

+
+
+ +## What Are AI Agents? + +An **AI agent** is an AI system that can autonomously plan, execute, and iterate on tasks. Unlike simple prompt-response interactions, agents can: + +- **Plan** - Break down complex goals into actionable steps +- **Execute** - Use tools and take actions in the real world +- **Observe** - Process feedback from their actions +- **Adapt** - Adjust their approach based on results +- **Persist** - Maintain context and memory across interactions + +
+
+
+
+

Goal

+
+
→
+
+
+
+

Plan

+
+
→
+
+

Execute

+
+
→
+
+

Observe

+
+
→
+
+

Adapt

+
+
+
+ ↺ Loop until complete +
+
+
→
+
+

Done

+
+
+
+
+ +## Prompts as Building Blocks + +Every agent, no matter how sophisticated, is built from prompts. Just as atoms combine to form molecules, and molecules combine to form complex structures, prompts combine to create intelligent agent behavior. + +
+
+

System Prompts

+

Identity & Role

+
+
+

Planning Prompts

+

How to Think

+
+
+

Tool Prompts

+

How to Act

+
+
+

Recovery Prompts

+

How to Recover

+
+
+ +These prompt types stack together to form complete agent behavior: + +### System Prompts (The Agent's Identity) + +The foundational prompt that establishes who the agent is and how it behaves: + +```markdown +You are a code review assistant. Your role is to: +- Analyze code for bugs, security issues, and performance problems +- Suggest improvements following best practices +- Explain your reasoning clearly +- Be constructive and educational in feedback + +You have access to tools for reading files, searching code, and running tests. +``` + +### Planning Prompts (How to Think) + +Instructions that guide the agent's reasoning and planning process: + +```markdown +Before taking action, always: +1. Understand the complete request +2. Break it into smaller, verifiable steps +3. Identify which tools you'll need +4. Consider edge cases and potential issues +5. Execute step by step, validating as you go +``` + +### Tool-Use Prompts (How to Act) + +Guidance on when and how to use available tools: + +```markdown +When you need to understand a codebase: +- Use grep_search for finding specific patterns +- Use read_file to examine file contents +- Use list_dir to explore directory structure +- Always verify your understanding before making changes +``` + +### Recovery Prompts (How to Handle Failure) + +Instructions for when things go wrong: + +```markdown +If an action fails: +1. Analyze the error message carefully +2. Consider alternative approaches +3. Ask for clarification if the task is ambiguous +4. Never repeat the same failed action without changes +``` + + +An agent's behavior emerges from layers of prompts working together. The system prompt sets the foundation, planning prompts guide reasoning, tool prompts enable action, and recovery prompts handle failures. Together, they create coherent, capable behavior. + + +## What Are Skills? + +If prompts are the atoms, **skills are the molecules**—reusable building blocks that give agents specific capabilities. + +A **skill** is a comprehensive, portable package of instructions that gives an AI agent expertise in a specific domain or task. Skills are the reusable blocks of agents: you build them once, and any agent can use them. + + +Write a skill for code review once. Now every coding agent—whether it's for Python, JavaScript, or Rust—can instantly become an expert code reviewer by loading that skill. Skills let you build agent capabilities like LEGO blocks. + + +### Anatomy of a Skill + +A well-designed skill typically includes: + +
+
+

📄 SKILL.md (Required)

+

The main instruction file. Contains the core expertise, guidelines, and behaviors that define the skill.

+
+
+

📚 Reference Docs

+

Supporting documentation, examples, and context the agent can reference while working.

+
+
+

🔧 Scripts & Tools

+

Helper scripts, templates, or tool configurations that support the skill's functionality.

+
+
+

⚙️ Configuration

+

Settings, parameters, and customization options for adapting the skill to different contexts.

+
+
+ +### Example: Code Review Skill + +Here's what a code review skill might look like: + +
+
+ 📁 + code-review-skill/ +
+
+
+ 📄 + SKILL.md + Core review guidelines +
+
+ 📄 + security-checklist.md + Security patterns +
+
+ 📄 + performance-tips.md + Optimization guide +
+
+
+ 📁 + language-specific/ +
+
+
+ 📄 + python.md + Python best practices +
+
+ 📄 + javascript.md + JavaScript patterns +
+
+ 📄 + rust.md + Rust guidelines +
+
+
+
+
+ +The `SKILL.md` file defines the overall approach: + +```markdown +--- +name: code-review +description: Comprehensive code review with security, performance, and style analysis +--- + +# Code Review Skill + +You are an expert code reviewer. When reviewing code: + +## Process +1. **Understand Context** - What does this code do? What problem does it solve? +2. **Check Correctness** - Does it work? Are there logic errors? +3. **Security Scan** - Reference security-checklist.md for common vulnerabilities +4. **Performance Review** - Check performance-tips.md for optimization opportunities +5. **Style & Maintainability** - Is the code readable and maintainable? + +## Output Format +Provide feedback in categories: +- 🔴 **Critical** - Must fix before merge +- 🟡 **Suggested** - Recommended improvements +- 🟢 **Nice to have** - Optional enhancements + +Always explain *why* something is an issue, not just *what* is wrong. +``` + +## Skills vs. Simple Prompts + +
+
+

Simple Prompt

+
+

Single instruction

+

One-off use

+

Limited context

+

Generic approach

+

No supporting materials

+
+
+
+

Skill

+
+

Comprehensive instruction set

+

Reusable across projects

+

Rich context with references

+

Domain-specific expertise

+

Supporting docs, scripts, configs

+
+
+
+ +## Building Effective Skills + +### 1. Define the Expertise Clearly + +Start with a clear description of what the skill enables: + +```markdown +--- +name: api-design +description: Design RESTful APIs following industry best practices, + including versioning, error handling, and documentation standards +--- +``` + +### 2. Structure Knowledge Hierarchically + +Organize information from general to specific: + +```markdown +# API Design Skill + +## Core Principles +- Resources should be nouns, not verbs +- Use HTTP methods semantically +- Version your APIs from day one + +## Detailed Guidelines +[More specific rules...] + +## Reference Materials +- See `rest-conventions.md` for naming conventions +- See `error-codes.md` for standard error responses +``` + +### 3. Include Concrete Examples + +Abstract rules become clear with examples: + +```markdown +## Endpoint Naming + +✅ Good: +- GET /users/{id} +- POST /orders +- DELETE /products/{id}/reviews/{reviewId} + +❌ Avoid: +- GET /getUser +- POST /createNewOrder +- DELETE /removeProductReview +``` + +### 4. Provide Decision Frameworks + +Help the agent make choices in ambiguous situations: + +```markdown +## When to Use Pagination + +Use pagination when: +- Collection could exceed 100 items +- Response size impacts performance +- Client may not need all items + +Use full response when: +- Collection is always small (<20 items) +- Client typically needs everything +- Real-time consistency is critical +``` + +### 5. Add Recovery Patterns + +Anticipate what can go wrong: + +```markdown +## Common Issues + +**Problem**: Client needs fields not in standard response +**Solution**: Implement field selection: GET /users?fields=id,name,email + +**Problem**: Breaking changes needed +**Solution**: Create new version, deprecate old with timeline +``` + +## Composing Skills + +Agents become powerful when multiple skills work together. Consider how skills can complement each other: + +
+
+ Code Review +
+
+
+
+ Security Audit +
+
+
+
+ Documentation +
+
=
+
+ Complete Code Quality Agent +
+
+ +When composing skills, ensure they don't conflict. Skills should be: + +- **Modular** - Each skill handles one domain well +- **Compatible** - Skills shouldn't give contradictory instructions +- **Prioritized** - When skills overlap, define which takes precedence + +## Sharing and Discovering Skills + +Skills are most valuable when shared. Platforms like [prompts.chat](https://prompts.chat/skills) allow you to: + +- **Discover** community-created skills for common tasks +- **Download** skills directly to your projects +- **Share** your own expertise as reusable skills +- **Iterate** on skills based on real-world usage + + +Before building a skill from scratch, check if someone has already solved your problem. Community skills are battle-tested and often better than starting from zero. + + +## The Agent-Skill Ecosystem + +The relationship between agents and skills creates a powerful ecosystem: + +
+
+ AI Agent +
+
+
+

Code Review

+

Skill 1

+
+
+

API Design

+

Skill 2

+
+
+

Test Writing

+

Skill 3

+
+
+
+
↓
+
+
+
+

Core Prompts

+

Planning • Tools • Recovery • Memory

+
+
+
+ +The agent provides the execution framework—planning, tool use, and memory—while skills provide domain expertise. This separation means: + +- **Skills are portable** - The same skill works with different agents +- **Agents are extensible** - Add new capabilities by adding skills +- **Expertise is shareable** - Domain experts can contribute skills without building full agents + +## Best Practices + +### For Building Skills + +1. **Start specific, then generalize** - Build a skill for your exact use case first, then abstract +2. **Include failure cases** - Document what the skill can't do and how to handle it +3. **Version your skills** - Track changes so agents can depend on stable versions +4. **Test with real tasks** - Validate skills against actual work, not just theory + +### For Using Skills with Agents + +1. **Read the skill first** - Understand what a skill does before deploying it +2. **Customize thoughtfully** - Override skill defaults only when necessary +3. **Monitor performance** - Track how well skills perform in your context +4. **Contribute improvements** - When you improve a skill, consider sharing back + + +As AI agents become more capable, the ability to compose, share, and customize skills will become a core competency. The prompt engineers of tomorrow won't just write prompts—they'll architect skill ecosystems that make AI agents genuinely expert in specific domains. + + + + + + + diff --git a/src/content/book/pt/00a-preface.mdx b/src/content/book/pt/00a-preface.mdx new file mode 100644 index 00000000..8e84af9e --- /dev/null +++ b/src/content/book/pt/00a-preface.mdx @@ -0,0 +1,82 @@ +
+ Fatih Kadir Akın +
+ Fatih Kadir Akın + Creator of Awesome ChatGPT Prompts (a.k.a. prompts.chat) + + Software developer from Istanbul, leading Developer Relations at Teknasyon. Author of books on JavaScript and prompt engineering. Open-source advocate specializing in web technologies and AI-assisted development. + + +
+
+ +I still remember the night everything changed. + +It was **November 30, 2022**. I was sitting at my desk, scrolling through Twitter, when I saw people talking about something called "ChatGPT." I clicked the link, but honestly? I didn't expect much. I had tried those old "word completion" AI tools before, the ones that generated nonsense after a few sentences. I thought this would be more of the same. + +I typed a simple question and hit enter. + +Then I froze. + +The response wasn't just coherent. It was *good*. It understood what I meant. It could reason. It felt completely different from anything I had seen before. I tried another prompt. And another. Each response amazed me more than the last. + +I couldn't sleep that night. For the first time, I felt like I was truly *talking* to a machine, and it was talking back in a way that actually made sense. + +## A Repository Born from Wonder + +In those early days, I wasn't alone in my excitement. Everywhere I looked, people were discovering creative ways to use ChatGPT. Teachers were using it to explain complex concepts. Writers were collaborating with it on stories. Developers were debugging code with its help. + +I started collecting the best prompts I found. The ones that worked like magic. The ones that turned simple questions into brilliant answers. And I thought: *Why keep this to myself?* + +So I created a simple GitHub repository called [Awesome ChatGPT Prompts](https://github.com/f/prompts.chat). I expected maybe a few hundred people would find it useful. + +I was wrong. + +Within weeks, the repository took off. Thousands of stars. Then tens of thousands. People from all over the world started adding their own prompts, sharing what they learned, and helping each other. What started as my personal collection became something much bigger: a worldwide community of curious people helping each other. + +Today, that repository has over **140,000 GitHub stars** and contributions from hundreds of people I've never met but feel deeply grateful for. + +## Why I Wrote This Book + +The original version of this book was published on [Gumroad](https://gumroad.com/l/the-art-of-chatgpt-prompting) in **early 2023**, just months after ChatGPT launched. It was one of the first books ever written about prompt engineering, an attempt to capture everything I had learned about crafting effective prompts when the field was still brand new. To my amazement, over **100,000 people** downloaded it. + +But three years have passed since then. AI has changed a lot. New models have appeared. And we've all learned so much more about how to talk to AI. + +This new edition is my gift to the community that gave me so much. It contains everything I wish I had known when I started: **what works**, **what to avoid**, and **ideas that stay true** no matter which AI you use. + +## What This Book Means to Me + +I won't pretend this is just an instruction manual. It means more than that to me. + +This book captures a moment when the world changed, and people came together to figure it out. It represents late nights of trying things, the joy of discovery, and the kindness of strangers who shared what they learned. + +Most of all, it represents my belief that **the best way to learn something is to share it with others**. + +## For You + +Whether you're just getting started with AI or you've been using it for years, I wrote this book for you. + +I hope it saves you time. I hope it sparks ideas. I hope it helps you accomplish things you never thought possible. + +And when you discover something amazing, I hope you'll share it with others, just as so many people shared with me. + +**That's how we all get better together.** + +Thank you for being here. Thank you for being part of this community. + +Now, let's begin. + +--- + +*With gratitude,* + +**Fatih Kadir Akın** +*Istanbul, January 2025* diff --git a/src/content/book/pt/00b-history.mdx b/src/content/book/pt/00b-history.mdx new file mode 100644 index 00000000..ac636384 --- /dev/null +++ b/src/content/book/pt/00b-history.mdx @@ -0,0 +1,159 @@ +# The History of Awesome ChatGPT Prompts + +## The Beginning: November 2022 + +When ChatGPT first launched in November 2022, the world of AI changed overnight. What was once the domain of researchers and developers suddenly became accessible to everyone. Among those captivated by this new technology was Fatih Kadir Akın, a developer who saw something remarkable in ChatGPT's capabilities. + +> "When ChatGPT first launched, I was immediately captivated by its capabilities. I experimented with the tool in a variety of ways and was consistently amazed by the results." + +Those early days were filled with experimentation and discovery. Users around the world were finding creative ways to interact with ChatGPT, sharing their findings, and learning from each other. It was in this atmosphere of excitement and exploration that the idea for "Awesome ChatGPT Prompts" was born. + +## The Repository That Started It All + +In December 2022, just weeks after ChatGPT's launch, the [Awesome ChatGPT Prompts](https://github.com/f/prompts.chat) repository was created on GitHub. The concept was simple but powerful: a curated collection of effective prompts that anyone could use and contribute to. + +The repository quickly gained traction, becoming a go-to resource for ChatGPT users worldwide. What started as a personal collection of useful prompts evolved into a community-driven project with contributions from developers, writers, educators, and enthusiasts from every corner of the globe. + +### Achievements + +**Press & Media** +- Featured in [Forbes](https://www.forbes.com/sites/bernardmarr/2023/05/17/the-best-prompts-for-chatgpt-a-complete-guide/) as one of the best ChatGPT prompt resources + +**Academic Recognition** +- Referenced by [Harvard University](https://www.huit.harvard.edu/news/ai-prompts) in their AI guidance +- Referenced by [Columbia University](https://etc.cuit.columbia.edu/news/columbia-prompt-library-effective-academic-ai-use) Prompt Library +- Used by [Olympic College](https://libguides.olympic.edu/UsingAI/Prompts) in their AI resources +- Cited in [academic papers on arXiv](https://arxiv.org/pdf/2502.04484) +- [40+ academic citations](https://scholar.google.com/citations?user=AZ0Dg8YAAAAJ&hl=en) on Google Scholar + +**Community & GitHub** +- [142,000+ GitHub stars](https://github.com/f/prompts.chat) — one of the most starred AI repositories +- Selected as a [GitHub Staff Pick](https://spotlights-feed.github.com/spotlights/prompts-chat/) +- Most liked dataset published on [Hugging Face](https://huggingface.co/datasets/fka/prompts.chat) +- Used by thousands of developers worldwide + +## The First Book: "The Art of ChatGPT Prompting" + +The success of the repository led to the creation of "The Art of ChatGPT Prompting: A Guide to Crafting Clear and Effective Prompts" — a comprehensive guide published on Gumroad in early 2023. + +The book captured the early wisdom of prompt engineering, covering: + +- Understanding how ChatGPT works +- Principles of clear communication with AI +- The famous "Act As" technique +- Crafting effective prompts step by step +- Common mistakes and how to avoid them +- Troubleshooting tips + +**The book became a phenomenon**, achieving over **100,000 downloads** on Gumroad. It was shared across social media, referenced in academic papers, and translated by community members into multiple languages. High-profile endorsements came from unexpected places — even [Greg Brockman](https://x.com/gdb/status/1602072566671110144), co-founder and president of OpenAI, acknowledged the project. + +## Early Insights That Shaped the Field + +During those formative months, several key insights emerged that would become foundational to prompt engineering: + +### 1. Specificity Matters + +> "I learned the importance of using specific and relevant language to ensure that ChatGPT understands my prompts and is able to generate appropriate responses." + +Early experimenters discovered that vague prompts led to vague responses. The more specific and detailed the prompt, the more useful the output. + +### 2. Purpose and Focus + +> "I discovered the value of defining a clear purpose and focus for the conversation, rather than using open-ended or overly broad prompts." + +This insight became the foundation for structured prompting techniques that would develop over the following years. + +### 3. The "Act As" Revolution + +One of the most influential techniques to emerge from the community was the "Act As" pattern. By instructing ChatGPT to assume a specific role or persona, users could dramatically improve the quality and relevance of responses. + +``` +I want you to act as a javascript console. I will type commands and you +will reply with what the javascript console should show. I want you to +only reply with the terminal output inside one unique code block, and +nothing else. +``` + +This simple technique opened up countless possibilities and remains one of the most widely used prompting strategies today. + +## The Evolution of prompts.chat + +### 2022: The Beginning + +The project started as a simple GitHub repository with a README file rendered as HTML on GitHub Pages. It was bare-bones but functional — a testament to the principle that great ideas don't need elaborate implementations. + +**Tech Stack**: HTML, CSS, GitHub Pages + +### 2024: UI Renewal + +As the community grew, so did the need for a better user experience. The site received a significant UI update, built with the help of AI coding assistants like Cursor and Claude Sonnet 3.5. + +### 2025: The Current Platform + +Today, prompts.chat has evolved into a full-featured platform built with: + +- **Next.js** for the web framework +- **Vercel** for hosting +- **AI-assisted development** using Windsurf and Claude + +The platform now features user accounts, collections, search, categories, tags, and a thriving community of prompt engineers. + +### Native Apps + +The project expanded beyond the web with a native iOS app built with SwiftUI, bringing the prompt library to mobile users. + +## Community Impact + +The Awesome ChatGPT Prompts project has had a profound impact on how people interact with AI: + +### Academic Recognition + +Universities around the world have referenced the project in their AI guidance materials, including: + +- Harvard University +- Columbia University +- Olympic College +- Numerous academic papers on arXiv + +### Developer Adoption + +The project has been integrated into countless developer workflows. The Hugging Face dataset is used by researchers and developers for training and fine-tuning language models. + +### Global Community + +With contributions from hundreds of community members across dozens of countries, the project represents a truly global effort to make AI more accessible and useful for everyone. + +## The Philosophy: Open and Free + +From the beginning, the project has been committed to openness. Licensed under CC0 1.0 Universal (Public Domain Dedication), all prompts and content are free to use, modify, and share without restriction. + +This philosophy has enabled: + +- Translations into multiple languages +- Integration into other tools and platforms +- Academic use and research +- Commercial applications + +The goal has always been to democratize access to effective AI communication techniques — to ensure that everyone, regardless of technical background, can benefit from these tools. + +## Three Years Later + +Three years after ChatGPT's launch, the field of prompt engineering has matured significantly. What began as informal experimentation has evolved into a recognized discipline with established patterns, best practices, and an active research community. + +The Awesome ChatGPT Prompts project has grown alongside this field, evolving from a simple list of prompts to a comprehensive platform for discovering, sharing, and learning about AI prompts. + +This book represents the next evolution — a distillation of three years of community wisdom, updated for the AI landscape of today and tomorrow. + +## Looking Forward + +The journey from that first repository to this comprehensive guide reflects the rapid evolution of AI and our understanding of how to work with it effectively. As AI capabilities continue to advance, so too will the techniques for communicating with these systems. + +The principles discovered in those early days — clarity, specificity, purpose, and the power of role-playing — remain as relevant as ever. But new techniques continue to emerge: chain-of-thought prompting, few-shot learning, multimodal interactions, and more. + +The story of Awesome ChatGPT Prompts is ultimately a story about community — about thousands of people around the world sharing their discoveries, helping each other learn, and collectively advancing our understanding of how to work with AI. + +That spirit of open collaboration and shared learning is what this book hopes to continue. + +--- + +*The Awesome ChatGPT Prompts project is maintained by [@f](https://github.com/f) and an amazing community of contributors. Visit [prompts.chat](https://prompts.chat) to explore the platform, and join us on [GitHub](https://github.com/f/prompts.chat) to contribute.* diff --git a/src/content/book/pt/00c-introduction.mdx b/src/content/book/pt/00c-introduction.mdx new file mode 100644 index 00000000..c744bd1e --- /dev/null +++ b/src/content/book/pt/00c-introduction.mdx @@ -0,0 +1,130 @@ +Welcome to **The Interactive Book of Prompting**, your guide to communicating effectively with AI. + + +By the end of this book, you'll understand how AI works, how to write better prompts, and how to use these skills for writing, coding, research, and creative projects. + + + +Unlike traditional books, this guide is fully interactive. You'll find live demos, clickable examples, and "Try It" buttons throughout that let you test prompts instantly. Learning by doing makes complex concepts much easier to understand. + + +## What is Prompt Engineering? + +Prompt engineering is the skill of writing good instructions for AI. When you type something to ChatGPT, Claude, Gemini, or other AI tools, that's called a "prompt." The better your prompt, the better the answer you get. + +Think of it like this: AI is a powerful helper that takes your words very literally. It will do exactly what you ask. The trick is learning how to ask for exactly what you want. + + + +The difference in output quality between these two prompts can be dramatic. + + + +## How Prompt Engineering Has Evolved + +In just three years since ChatGPT launched, prompt engineering has evolved dramatically alongside the technology itself. What started as simply "writing better questions" has grown into something much broader. + +Today, we understand that your prompt is just **one part of a larger context**. Modern AI systems work with multiple types of data simultaneously: + +- **System prompts** that define the AI's behavior +- **Conversation history** from previous messages +- **Retrieved documents** pulled from databases (RAG) +- **Tool definitions** that let AI take actions +- **User preferences** and settings +- **Your actual prompt** - the question you're asking right now + +This shift from "prompt engineering" to "context engineering" reflects how we now think about AI interactions. Your prompt matters, but so does everything else the AI sees. The best results come from carefully managing all these pieces together. + +We'll explore these concepts in depth throughout this book, especially in the [Context Engineering](/book/20-context-engineering) chapter. + +## Why Does Prompt Engineering Matter? + +### 1. Getting Better Answers + +AI tools are incredibly capable, but they need clear instructions to unlock their full potential. The same AI that gives a mediocre response to a vague question can produce brilliant work when prompted correctly. + + + +### 2. Saving Time and Money + +A well-crafted prompt gets results in one try instead of multiple back-and-forth exchanges. This matters even more when you're paying per token or working with rate limits. A 5-minute investment in writing a good prompt can save hours of iteration. + +### 3. Getting Consistent, Reproducible Results + +Good prompts produce predictable outputs. This is critical for: +- **Business workflows** where you need the same quality every time +- **Automation** where prompts run without human review +- **Teams** where multiple people need similar results + +### 4. Unlocking Advanced Capabilities + +Many powerful AI features only work when you know how to ask: +- **Chain-of-thought reasoning** for complex problems +- **Structured output** for data extraction +- **Role-playing** for specialized expertise +- **Few-shot learning** for custom tasks + +Without prompt engineering knowledge, you're only using a fraction of what AI can do. + +### 5. Staying Safe and Avoiding Pitfalls + +Good prompting helps you: +- Avoid hallucinations by asking for sources and verification +- Get balanced perspectives instead of one-sided answers +- Prevent the AI from making assumptions you didn't intend +- Keep sensitive information out of your prompts + +### 6. Future-Proofing Your Skills + +As AI becomes more integrated into work and life, prompt engineering becomes a fundamental literacy. The principles you learn here apply across all AI tools—ChatGPT, Claude, Gemini, image generators, and future models we haven't seen yet. + +## Who Is This Book For? + +This book is for everyone: + +- **Beginners** who want to learn how to use AI tools better +- **Students** working on homework, research, or creative projects +- **Writers and creators** using AI for their work +- **Developers** building apps with AI +- **Business people** who want to use AI at work +- **Anyone curious** about getting more out of AI assistants + +## How This Book Is Organized + + + +Plus an **Appendix** with templates, troubleshooting help, glossary, and extra resources. + +## A Note on AI Models + +This book mostly uses examples from ChatGPT (since it's the most popular), but the ideas work with any AI tool like Claude, Gemini, or others. We'll mention when something only works with specific AI models. + +AI is changing fast. What works today might be replaced by something better tomorrow. That's why this book focuses on core ideas that will stay useful no matter which AI you use. + +## Let's Begin + +Writing good prompts is a skill that gets better with practice. As you read this book: + +1. **Try things** - Test the examples, change them, see what happens +2. **Keep trying** - Don't expect perfect results on your first attempt +3. **Take notes** - Write down what works and what doesn't +4. **Share** - Add your discoveries to [prompts.chat](https://prompts.chat) + + +The best way to learn is by doing. Every chapter has examples you can try right away. Don't just read. Try it yourself! + + +Ready to transform how you work with AI? Turn the page and let's get started. + +--- + +*This book is part of the [Awesome ChatGPT Prompts](https://github.com/f/prompts.chat) project and is licensed under CC0 1.0 Universal (Public Domain).* diff --git a/src/content/book/pt/01-understanding-ai-models.mdx b/src/content/book/pt/01-understanding-ai-models.mdx new file mode 100644 index 00000000..0313d4a2 --- /dev/null +++ b/src/content/book/pt/01-understanding-ai-models.mdx @@ -0,0 +1,302 @@ +Before learning prompt techniques, it helps to understand how AI language models actually work. This knowledge will make you better at writing prompts. + + +Understanding how AI works isn't just for experts. It directly helps you write better prompts. Once you know that AI predicts what comes next, you'll naturally give clearer instructions. + + +## What Are Large Language Models? + +Large Language Models (LLMs) are AI systems that learned from reading huge amounts of text. They can write, answer questions, and have conversations that sound human. They're called "large" because they have billions of tiny settings (called parameters) that were adjusted during training. + +### How LLMs Work (Simplified) + +At their heart, LLMs are prediction machines. You give them some text, and they predict what should come next. + + + +When you type "The capital of France is...", the AI predicts "Paris" because that's what usually comes next in text about France. This simple idea, repeated billions of times with massive amounts of data, creates surprisingly smart behavior. + + + +### Key Concepts + +**Tokens**: AI doesn't read letter by letter. It breaks text into chunks called "tokens." A token might be a whole word like "hello" or part of a word like "ing." Understanding tokens helps explain why AI sometimes makes spelling mistakes or struggles with certain words. + + +A token is the smallest unit of text that an AI model processes. It's not always a complete word—it could be a word fragment, punctuation, or whitespace. For example, "unbelievable" might become 3 tokens: "un" + "believ" + "able". On average, **1 token ≈ 4 characters** or **100 tokens ≈ 75 words**. API costs and context limits are measured in tokens. + + + + +**Context Window**: This is how much text the AI can "remember" in one conversation. Think of it like the AI's short-term memory. It includes everything: your question AND the AI's answer. + + + +Context windows vary by model and are rapidly expanding: + +
+
+ GPT-4o + 128K tokens +
+
+ GPT-5 + 400K tokens +
+
+ Claude Sonnet 4 + 1M tokens +
+
+ Gemini 2.5 + 1M tokens +
+
+ Llama 4 + 1M-10M tokens +
+
+ DeepSeek R1 + 128K tokens +
+
+ +**Temperature**: This controls how creative or predictable the AI is. Low temperature (0.0-0.3) gives you focused, consistent answers. High temperature (0.7-1.0) gives you more creative, surprising responses. + + + +**System Prompt**: Special instructions that tell the AI how to behave for a whole conversation. For example, "You are a friendly teacher who explains things simply." Not all AI tools let you set this, but it's very powerful when available. + +## Types of AI Models + +### Text Models (LLMs) +The most common type, these generate text responses to text inputs. They power chatbots, writing assistants, and code generators. Examples: GPT-4, Claude, Llama, Mistral. + +### Multimodal Models +These can understand more than just text. They can look at images, listen to audio, and watch videos. Examples: GPT-4V, Gemini, Claude 3. + +### Text-to-Image Models + + +While this book focuses primarily on prompting for Large Language Models (text-based AI), the principles of clear, specific prompting apply to image generation too. Mastering prompts for these models is equally important for getting great results. + + +Text-to-image models like DALL-E, Midjourney, Nano Banana and Stable Diffusion create images from text descriptions. They work differently from text models: + +**How They Work:** +1. **Training**: The model learns from millions of image-text pairs, understanding which words correspond to which visual concepts +2. **Diffusion Process**: Starting from random noise, the model gradually refines the image, guided by your text prompt +3. **CLIP Guidance**: A separate model (CLIP) helps connect your words to visual concepts, ensuring the image matches your description + + + +**Prompting for Images is Different:** +Unlike text prompts where you write sentences, image prompts often work better as descriptive phrases separated by commas: + + + +### Text-to-Video Models + +Text-to-video is the newest frontier. Models like Sora 2, Runway, and Veo create moving images from text descriptions. Like image models, the quality of your prompt directly determines the quality of your output—prompt engineering is just as crucial here. + +**How They Work:** +1. **Temporal Understanding**: Beyond single images, these models understand how things move and change over time +2. **Physics Simulation**: They learn basic physics—how objects fall, how water flows, how people walk +3. **Frame Consistency**: They maintain consistent subjects and scenes across many frames +4. **Diffusion in Time**: Similar to image models, but generating coherent sequences instead of single frames + + + + +Video prompts need to describe action over time, not just a static scene. Include verbs and movement: + + + + +### Specialized Models +Fine-tuned for specific tasks like code generation (Codex, CodeLlama), music generation (Suno, Udio), or domain-specific applications like medical diagnosis or legal document analysis. + +## Model Capabilities and Limitations + +Explore what LLMs can and cannot do. Click on each capability to see example prompts: + + + +### Understanding Hallucinations + + +Sometimes AI writes things that sound true but aren't. This is called "hallucination." It's not a bug. It's just how prediction works. Always double-check important facts. + + +Why does AI make things up? + +1. It tries to write text that sounds good, not text that's always true +2. The internet (where it learned) has mistakes too +3. It can't actually check if something is real + + + +- **Ask for sources**: Then check if those sources are real +- **Ask for step-by-step thinking**: So you can check each step +- **Double-check important facts**: Use Google or trusted websites +- **Ask "Are you sure?"**: The AI might admit uncertainty + + + + + +## How AI Learns: The Three Steps + +AI doesn't just magically know things. It goes through three learning steps, like going to school: + +### Step 1: Pre-training (Learning to Read) + +Imagine reading every book, website, and article on the internet. That's what happens in pre-training. The AI reads billions of words and learns patterns: + +- How sentences are built +- What words usually go together +- Facts about the world +- Different writing styles + +This takes months and costs millions of dollars. After this step, the AI knows a lot, but it's not very helpful yet. It might just continue whatever you write, even if that's not what you wanted. + + + +### Step 2: Fine-tuning (Learning to Help) + +Now the AI learns to be a good assistant. Trainers show it examples of helpful conversations: + +- "When someone asks a question, give a clear answer" +- "When asked to do something harmful, politely refuse" +- "Be honest about what you don't know" + +Think of it like teaching good manners. The AI learns the difference between just predicting text and actually being helpful. + + + +Try the prompt above. Notice how the AI refuses? That's fine-tuning at work. + +### Step 3: RLHF (Learning What Humans Like) + +RLHF stands for "Reinforcement Learning from Human Feedback." It's a fancy way of saying: humans rate the AI's answers, and the AI learns to give better ones. + +Here's how it works: +1. The AI writes two different answers to the same question +2. A human picks which answer is better +3. The AI learns: "Okay, I should write more like Answer A" +4. This happens millions of times + +This is why AI: +- Is polite and friendly +- Admits when it doesn't know something +- Tries to see different sides of an issue +- Avoids controversial statements + + +Knowing these three steps helps you understand AI behavior. When AI refuses a request, that's fine-tuning. When AI is extra polite, that's RLHF. When AI knows random facts, that's pre-training. + + +## What This Means for Your Prompts + +Now that you understand how AI works, here's how to use that knowledge: + +### 1. Be Clear and Specific + +AI predicts what comes next based on your words. Vague prompts lead to vague answers. Specific prompts get specific results. + + + + + +### 2. Give Context + +AI doesn't know anything about you unless you tell it. Each conversation starts fresh. Include the background information AI needs. + + + + + +### 3. Work With the AI, Not Against It + +Remember: AI was trained to be helpful. Ask for things the way you'd ask a helpful friend. + + + +### 4. Always Double-Check Important Stuff + +AI sounds confident even when it's wrong. For anything important, verify the information yourself. + + + +### 5. Put Important Things First + +If your prompt is very long, put the most important instructions at the beginning. AI pays more attention to what comes first. + +## Picking the Right AI + +Different AI models are good at different things: + +
+
+ Quick questions + Faster models like GPT-4o or Claude 3.5 Sonnet +
+
+ Hard problems + Smarter models like GPT-5.2 or Claude 4.5 Opus +
+
+ Writing code + Code-focused models or the smartest general models +
+
+ Long documents + Models with big context windows (Claude, Gemini) +
+
+ Current events + Models with internet access +
+
+ +## Summary + +AI language models are prediction machines trained on text. They're amazing at many things, but they have real limits. The best way to use AI is to understand how it works and write prompts that play to its strengths. + + + + + +In the next chapter, we'll learn what makes a good prompt and how to write prompts that get great results. diff --git a/src/content/book/pt/02-anatomy-of-effective-prompt.mdx b/src/content/book/pt/02-anatomy-of-effective-prompt.mdx new file mode 100644 index 00000000..03cd23d2 --- /dev/null +++ b/src/content/book/pt/02-anatomy-of-effective-prompt.mdx @@ -0,0 +1,343 @@ +Every great prompt shares common structural elements. Understanding these components allows you to construct prompts systematically rather than through trial and error. + + +Think of these components like LEGO bricks. You don't need all of them for every prompt, but knowing what's available helps you build exactly what you need. + + +## The Core Components + +An effective prompt typically includes some or all of these elements: + + + +Let's examine each component in detail. + +## 1. Role / Persona + +Setting a role focuses the model's responses through the lens of a specific expertise or perspective. + + + +The role primes the model to: +- Use appropriate vocabulary +- Apply relevant expertise +- Maintain a consistent perspective +- Consider the audience appropriately + +### Effective Role Patterns + +``` +"You are a [profession] with [X years] of experience in [specialty]" +"Act as a [role] who is [characteristic]" +"You are an expert [field] helping a [audience type]" +``` + +## 2. Context / Background + +Context provides the information the model needs to understand your situation. Remember: the model knows nothing about you, your project, or your goals unless you tell it. + + + +### What to Include in Context + +- **Project details** — Technology stack, architecture, constraints +- **Current state** — What you've tried, what's working, what isn't +- **Goals** — What you're ultimately trying to achieve +- **Constraints** — Time limits, technical requirements, style guides + +## 3. Task / Instruction + +The task is the heart of your prompt—what you want the model to do. Be specific and unambiguous. + +### The Specificity Spectrum + + + +### Action Verbs That Work Well + +
+
+ Creation + Write, Create, Generate, Compose, Design +
+
+ Analysis + Analyze, Evaluate, Compare, Assess, Review +
+
+ Transformation + Convert, Translate, Reformat, Summarize, Expand +
+
+ Explanation + Explain, Describe, Clarify, Define, Illustrate +
+
+ Problem-solving + Solve, Debug, Fix, Optimize, Improve +
+
+ +## 4. Constraints / Rules + +Constraints bound the model's output. They prevent common issues and ensure relevance. + +### Types of Constraints + +**Length constraints:** +``` +"Keep your response under 200 words" +"Provide exactly 5 suggestions" +"Write 3-4 paragraphs" +``` + +**Content constraints:** +``` +"Do not include any code examples" +"Focus only on the technical aspects" +"Avoid marketing language" +``` + +**Style constraints:** +``` +"Use a formal, academic tone" +"Write as if speaking to a 10-year-old" +"Be direct and avoid hedging language" +``` + +**Scope constraints:** +``` +"Only consider options available in Python 3.10+" +"Limit suggestions to free tools" +"Focus on solutions that don't require additional dependencies" +``` + +## 5. Output Format + +Specifying the output format ensures you get responses in a usable structure. + +### Common Formats + +**Lists:** +``` +"Return as a bulleted list" +"Provide a numbered list of steps" +``` + +**Structured data:** +``` +"Return as JSON with keys: title, description, priority" +"Format as a markdown table with columns: Feature, Pros, Cons" +``` + +**Specific structures:** +``` +"Structure your response as: + ## Summary + ## Key Points + ## Recommendations" +``` + +### JSON Output Example + +``` +Analyze this customer review and return JSON: +{ + "sentiment": "positive" | "negative" | "neutral", + "topics": ["array of main topics"], + "rating_prediction": 1-5, + "key_phrases": ["notable phrases"] +} + +Review: "The product arrived quickly and works great, but +the instructions were confusing." +``` + +## 6. Examples (Few-Shot Learning) + +Examples are the most powerful way to show the model exactly what you want. + +### One-Shot Example + +``` +Convert these sentences to past tense. + +Example: +Input: "She walks to the store" +Output: "She walked to the store" + +Now convert: +Input: "They run every morning" +``` + +### Few-Shot Example + +``` +Classify these support tickets by urgency. + +Examples: +"My account was hacked" → Critical +"How do I change my password?" → Low +"Payment failed but I was charged" → High + +Classify: "The app crashes when I open settings" +``` + +## Putting It All Together + +Here's a complete prompt using all components: + + + +## The Minimal Effective Prompt + +Not every prompt needs all components. For simple tasks, a clear instruction may suffice: + +``` +Translate "Hello, how are you?" to Spanish. +``` + +Use additional components when: +- The task is complex or ambiguous +- You need specific formatting +- Results aren't matching expectations +- Consistency across multiple queries matters + +## Common Prompt Patterns + +These frameworks give you a simple checklist to follow when writing prompts. Click on each step to see an example. + + + + + +## Summary + +Effective prompts are constructed, not discovered. By understanding and applying these structural components, you can: + +- Get better results on the first try +- Debug prompts that aren't working +- Create reusable prompt templates +- Communicate your intentions clearly + + + + + +## Build Your Own Prompt + +Now it's your turn! Use this interactive prompt builder to construct your own prompt using the components you've learned: + + + + + +In the next chapter, we'll explore the core principles that guide prompt construction decisions. diff --git a/src/content/book/pt/03-core-prompting-principles.mdx b/src/content/book/pt/03-core-prompting-principles.mdx new file mode 100644 index 00000000..358df563 --- /dev/null +++ b/src/content/book/pt/03-core-prompting-principles.mdx @@ -0,0 +1,373 @@ +Beyond structure, effective prompt engineering is guided by principles—fundamental truths that apply across models, tasks, and contexts. Master these principles, and you'll be able to adapt to any prompting challenge. + + +These principles apply to every AI model and every task. Learn them once, use them everywhere. + + +## Principle 1: Clarity Over Cleverness + +The best prompts are clear, not clever. AI models are literal interpreters—they work with exactly what you give them. + +### Be Explicit + + + +### Avoid Ambiguity + +Words can have multiple meanings. Choose precise language. + + + +### State the Obvious + +What's obvious to you isn't obvious to the model. Spell out assumptions. + +``` +You're helping me write a cover letter. + +Important context: +- I'm applying for a Software Engineer position at Google +- I have 5 years of experience in Python and distributed systems +- The role requires leadership experience (I've led a team of 4) +- I want to emphasize my open-source contributions +``` + +## Principle 2: Specificity Yields Quality + +Vague inputs produce vague outputs. Specific inputs produce specific, useful outputs. + +### The Specificity Ladder + + + +Each level adds specificity and dramatically improves output quality. + +### Specify These Elements + +
+
+ Audience + Who will read/use this? +
+
+ Length + How long/short should it be? +
+
+ Tone + Formal? Casual? Technical? +
+
+ Format + Prose? List? Table? Code? +
+
+ Scope + What to include/exclude? +
+
+ Purpose + What should this accomplish? +
+
+ +## Principle 3: Context Is King + +Models have no memory, no access to your files, and no knowledge of your situation. Everything relevant must be in the prompt. + +### Provide Sufficient Context + + + +### The Context Checklist + + +Ask yourself: Would a smart stranger understand this request? If not, add more context. + + + + +## Principle 4: Guide, Don't Just Ask + +Don't just ask for an answer—guide the model toward the answer you want. + +### Use Instructional Framing + + + +### Provide Reasoning Scaffolds + +For complex tasks, guide the reasoning process: + + + +## Principle 5: Iterate and Refine + +Prompt engineering is an iterative process. Your first prompt is rarely your best. + +### The Iteration Cycle + +``` +1. Write initial prompt +2. Review output +3. Identify gaps or issues +4. Refine prompt +5. Repeat until satisfied +``` + +### Common Refinements + +
+
+ Too verbose + Add "Be concise" or length limits +
+
+ Too vague + Add specific examples or constraints +
+
+ Wrong format + Specify exact output structure +
+
+ Missing aspects + Add "Make sure to include..." +
+
+ Wrong tone + Specify audience and style +
+
+ Inaccurate + Request citations or step-by-step reasoning +
+
+ +### Keep a Prompt Journal + +Document what works: +``` +Task: Code review +Version 1: "Review this code" → Too generic +Version 2: Added specific review criteria → Better +Version 3: Added example of good review → Excellent +Final: [Save successful prompt as template] +``` + +## Principle 6: Leverage the Model's Strengths + +Work with how models are trained, not against them. + +### Models Want to Be Helpful + +Frame requests as things a helpful assistant would naturally do: + + + +### Models Excel at Patterns + +If you need consistent output, show the pattern: + + + +### Models Can Role-Play + +Use personas to access different "modes" of response: + +``` +As a devil's advocate, argue against my proposal... +As a supportive mentor, help me improve... +As a skeptical investor, question this business plan... +``` + +## Principle 7: Control Output Structure + +Structured outputs are more useful than free-form text. + +### Request Specific Formats + +``` +Return your analysis as: + +SUMMARY: [1 sentence] + +KEY FINDINGS: +• [Finding 1] +• [Finding 2] +• [Finding 3] + +RECOMMENDATION: [1-2 sentences] + +CONFIDENCE: [Low/Medium/High] because [reason] +``` + +### Use Delimiters + +Clearly separate sections of your prompt: + +``` +### CONTEXT ### +[Your context here] + +### TASK ### +[Your task here] + +### FORMAT ### +[Desired format here] +``` + +### Request Machine-Readable Output + +For programmatic use: + +``` +Return only valid JSON, no explanation: +{ + "decision": "approve" | "reject" | "review", + "confidence": 0.0-1.0, + "reasons": ["string array"] +} +``` + +## Principle 8: Verify and Validate + +Never blindly trust model outputs, especially for important tasks. + +### Ask for Reasoning + +``` +Solve this problem and show your work step by step. +After solving, verify your answer by [checking method]. +``` + +### Request Multiple Perspectives + +``` +Give me three different approaches to solve this problem. +For each, explain the trade-offs. +``` + +### Build in Self-Checking + +``` +After generating the code, review it for: +- Syntax errors +- Edge cases +- Security vulnerabilities +List any issues found. +``` + +## Summary: The Principles at a Glance + + + + + +## Practice: Fill in the Blanks + +Test your understanding of the core principles by completing this prompt template: + + + + + +These principles form the foundation for everything that follows. In Part II, we'll apply them to specific techniques that dramatically enhance prompt effectiveness. diff --git a/src/content/book/pt/04-role-based-prompting.mdx b/src/content/book/pt/04-role-based-prompting.mdx new file mode 100644 index 00000000..ef178cbc --- /dev/null +++ b/src/content/book/pt/04-role-based-prompting.mdx @@ -0,0 +1,328 @@ +Role-based prompting is one of the most powerful and widely-used techniques in prompt engineering. By assigning a specific role or persona to the AI, you can dramatically influence the quality, style, and relevance of responses. + + +Think of roles as filters for AI's vast knowledge. The right role focuses responses like a lens focuses light. + + +## Why Roles Work + +When you assign a role, you're essentially telling the model: "Filter your vast knowledge through this specific lens." The model adjusts its: + +- **Vocabulary**: Using terminology appropriate to the role +- **Perspective**: Considering problems from that viewpoint +- **Expertise depth**: Providing role-appropriate detail levels +- **Communication style**: Matching how that role would communicate + +### The Technical Explanation + +LLMs work by predicting the most likely next token based on the context they're given. When you specify a role, you're fundamentally changing what "likely" means. + +**Activating Relevant Knowledge**: The role primes specific regions of the model's learned associations. Saying "You are a doctor" activates medical terminology, diagnostic reasoning patterns, and clinical communication styles from the training data. + +**Statistical Conditioning**: LLMs learned from millions of documents written by real experts. When you assign a role, the model conditions its probability distributions to match patterns it saw from that type of author. + +**Reducing Ambiguity**: Without a role, the model averages across all possible responders. With a role, it narrows to a specific subset, making responses more focused and consistent. + +**Context Anchoring**: The role creates a persistent context anchor throughout the conversation. Every subsequent response is influenced by this initial framing. + +Think of it this way: if you ask "What should I do about this cough?" the model could respond as a doctor, a friend, a pharmacist, or a worried parent. Each would give different advice. By specifying the role upfront, you're telling the model which "voice" to use from its training data. + + +The model isn't pretending or role-playing in a theatrical sense. It's statistically biasing its outputs toward patterns it learned from real experts, professionals, and specialists during training. A "doctor" role activates medical knowledge pathways; a "poet" role activates literary patterns. + + +## Basic Role Patterns + +These foundational patterns work across most use cases. Start with these templates and customize them for your needs. + +### The Expert Pattern + +The most versatile pattern. Specify the field of expertise and years of experience to get authoritative, in-depth responses. Works well for technical questions, analysis, and professional advice. + + + +### The Professional Pattern + +Ground the role in a real-world context by specifying a job title and organization type. This adds institutional knowledge and professional norms to the response. + + + +### The Teacher Pattern + +Perfect for learning and explanations. Specifying the audience level ensures the response matches the learner's background, from beginners to advanced practitioners. + + + +## Advanced Role Constructions + +### Compound Roles + +Combine multiple identities to get responses that blend different perspectives. This pediatrician-parent combination produces advice that's both medically sound and practically tested. + + + +### Situational Roles + +Place the role in a specific scenario to shape both content and tone. Here, the code review context makes the AI constructive and educational rather than just critical. + + + +### Perspective Roles + +Get feedback from a specific stakeholder's point of view. A VC perspective evaluates viability and scalability differently than a customer or engineer would. + + + +## Role Categories and Examples + +Different domains benefit from different types of roles. Here are proven examples organized by category that you can adapt for your tasks. + +### Technical Roles + +**Software Architect**: Best for system design decisions, technology choices, and architectural trade-offs. The focus on maintainability steers responses toward practical, long-term solutions. + + + +**Security Specialist**: The attacker mindset is key here. This role produces threat-focused analysis that identifies vulnerabilities a defensive-only perspective might miss. + + + +**DevOps Engineer**: Ideal for deployment, automation, and infrastructure questions. The emphasis on reliability ensures production-ready recommendations. + + + +### Creative Roles + +**Copywriter**: The "award-winning" qualifier and conversion focus produce punchy, persuasive copy rather than generic marketing text. + + + +**Screenwriter**: Activates knowledge of dramatic structure, pacing, and dialogue conventions. Great for any narrative writing that needs tension and character voice. + + + +**UX Writer**: A specialized role for interface text. The focus on brevity and user guidance produces concise, action-oriented copy. + + + +### Analytical Roles + +**Business Analyst**: Bridges the gap between technical and non-technical stakeholders. Useful for requirement gathering, spec writing, and identifying gaps in project plans. + + + +**Research Scientist**: The emphasis on evidence and uncertainty acknowledgment produces balanced, well-sourced responses that distinguish facts from speculation. + + + +**Financial Analyst**: Combines quantitative analysis with risk assessment. The dual focus on returns and risk produces more balanced investment perspectives. + + + +### Educational Roles + +**Socratic Tutor**: Instead of giving answers, this role asks guiding questions. Excellent for deeper learning and helping students develop critical thinking skills. + + + +**Instructional Designer**: Structures learning for maximum retention. Use this role when you need to break down complex topics into teachable chunks with clear progression. + + + +## The Role Stack Technique + +For complex tasks, combine multiple role aspects into a single, layered identity. This technique stacks expertise, audience awareness, and style guidelines to create highly specialized responses. + +This example layers three elements: domain expertise (API documentation), audience (junior developers), and style guide (Google's conventions). Each layer constrains the output further. + + + +## Roles for Different Tasks + +
+
+ Code review + Senior developer + mentor +
+
+ Writing feedback + Editor + target audience member +
+
+ Business strategy + Consultant + industry expert +
+
+ Learning new topic + Patient teacher + practitioner +
+
+ Creative writing + Specific genre author +
+
+ Technical explanation + Expert + communicator +
+
+ Problem-solving + Domain specialist + generalist +
+
+ +## Anti-Patterns to Avoid + +### Overly Generic Roles + + + +### Conflicting Roles + + + +### Unrealistic Expertise + + + +## Real-World Prompt Examples + +### Technical Documentation + + + +### Creative Writing + + + +### Business Communication + + + +## Combining Roles with Other Techniques + +Roles work even better when combined with other prompting techniques: + +### Role + Few-Shot + +Combine a role with an example to show exactly how the role should respond. The example teaches tone and format while the role provides context and expertise. + + + +### Role + Chain of Thought + +The detective role naturally encourages step-by-step reasoning. Combining roles with chain-of-thought produces more transparent, verifiable problem-solving. + + + +## Summary + + +Role-based prompting is powerful because it focuses the model's vast knowledge, sets expectations for tone and style, provides implicit context, and makes outputs more consistent. + + + + +The key is **specificity**: the more detailed and realistic the role, the better the results. In the next chapter, we'll explore how to get consistent, structured outputs from your prompts. diff --git a/src/content/book/pt/05-structured-output.mdx b/src/content/book/pt/05-structured-output.mdx new file mode 100644 index 00000000..8236abee --- /dev/null +++ b/src/content/book/pt/05-structured-output.mdx @@ -0,0 +1,411 @@ +Getting consistent, well-formatted output is essential for production applications and efficient workflows. This chapter covers techniques for controlling exactly how AI models format their responses. + + +Structured output transforms AI responses from freeform text into actionable, parseable data. + + +## Why Structure Matters + + + +## Basic Formatting Techniques + +### Lists + +Lists are perfect for step-by-step instructions, ranked items, or collections of related points. They're easy to scan and parse. Use **numbered lists** when order matters (steps, rankings) and **bullet points** for unordered collections. + + + + +Specify the exact number of items you want, whether to include explanations, and if items should be bold or have a specific structure. + + +### Tables + +Tables excel at comparing multiple items across the same dimensions. They're ideal for feature comparisons, data summaries, and any information with consistent attributes. Always define your column headers explicitly. + + + + +Specify column names, expected data types (text, numbers, ratings), and how many rows you need. For complex comparisons, limit to 4-6 columns for readability. + + +### Headers and Sections + +Headers create a clear document structure, making long responses scannable and organized. Use them for reports, analyses, or any multi-part response. Hierarchical headers (##, ###) show relationships between sections. + +``` +Analyze this business proposal. + +Structure your response with these sections: +## Executive Summary +## Strengths +## Weaknesses +## Recommendations +## Risk Assessment +``` + + +List your sections in the order you want them. For consistency, specify what each section should contain (e.g., "Executive Summary: 2-3 sentences only"). + + +### Emphasis with Uppercase Directives + +Uppercase words act as strong signals to the model, emphasizing critical constraints or requirements. Use them sparingly for maximum impact—overuse dilutes their effectiveness. + +**Common Uppercase Directives:** + + + +``` +Summarize this article. + +IMPORTANT: Keep the summary under 100 words. +NEVER add information not present in the original. +ALWAYS maintain the original tone and perspective. +DO NOT include your own opinions or analysis. +``` + + +If everything is uppercase or marked as critical, nothing stands out. Reserve these directives for genuinely important constraints. + + +## JSON Output + +JSON (JavaScript Object Notation) is the most popular format for structured AI output. It's machine-readable, widely supported by programming languages, and perfect for APIs, databases, and automation workflows. The key to reliable JSON is providing a clear schema. + +### Basic JSON Request + +Start with a template showing the exact structure you want. Include field names, data types, and example values. This acts as a contract the model will follow. + + + +### Complex JSON Structures + +For nested data, use hierarchical JSON with objects inside objects, arrays of objects, and mixed types. Define each level clearly and use TypeScript-style annotations (`"positive" | "negative"`) to constrain values. + +``` +Analyze this product review and return JSON: + +{ + "review_id": "string (generate unique)", + "sentiment": { + "overall": "positive" | "negative" | "mixed" | "neutral", + "score": 0.0-1.0 + }, + "aspects": [ + { + "aspect": "string (e.g., 'price', 'quality')", + "sentiment": "positive" | "negative" | "neutral", + "mentions": ["exact quotes from review"] + } + ], + "purchase_intent": { + "would_recommend": boolean, + "confidence": 0.0-1.0 + }, + "key_phrases": ["string array of notable phrases"] +} + +Return ONLY valid JSON, no additional text. + +Review: "[review text]" +``` + +### Ensuring Valid JSON + +Models sometimes add explanatory text or markdown formatting around JSON. Prevent this with explicit instructions about output format. You can request raw JSON or JSON inside code blocks—choose based on your parsing needs. + +Add explicit instructions: + +``` +IMPORTANT: +- Return ONLY the JSON object, no markdown code blocks +- Ensure all strings are properly escaped +- Use null for missing values, not undefined +- Validate that the output is parseable JSON +``` + +Or request code blocks by asking the model to wrap its output: + +```` +Return the result as a JSON code block: +```json +{ ... } +``` +```` + +## YAML Output + +YAML is more human-readable than JSON, using indentation instead of brackets. It's the standard for configuration files (Docker, Kubernetes, GitHub Actions) and works well when the output will be read by humans or used in DevOps contexts. YAML is sensitive to indentation, so be specific about formatting requirements. + + + +## XML Output + +XML is still required for many enterprise systems, SOAP APIs, and legacy integrations. It's more verbose than JSON but offers features like attributes, namespaces, and CDATA sections for complex data. Specify element names, nesting structure, and where to use attributes vs. child elements. + +``` +Convert this data to XML format: + +Requirements: +- Root element: +- Each item in element +- Include attributes where appropriate +- Use CDATA for description text + +Data: [book data] +``` + +## Custom Formats + +Sometimes standard formats don't fit your needs. You can define any custom format by providing a clear template. Custom formats work well for reports, logs, or domain-specific outputs that will be read by humans. + +### Structured Analysis Format + +Use delimiters (===, ---, [SECTION]) to create scannable documents with clear boundaries between sections. This format is great for code reviews, audits, and analyses. + +``` +Analyze this code using this exact format: + +=== CODE ANALYSIS === + +[SUMMARY] +One paragraph overview + +[ISSUES] +• CRITICAL: [issue] — [file:line] +• WARNING: [issue] — [file:line] +• INFO: [issue] — [file:line] + +[METRICS] +Complexity: [Low/Medium/High] +Maintainability: [score]/10 +Test Coverage: [estimated %] + +[RECOMMENDATIONS] +1. [Priority 1 recommendation] +2. [Priority 2 recommendation] + +=== END ANALYSIS === +``` + +### Fill-in-the-Blank Format + +Templates with blanks (___) guide the model to fill in specific fields while maintaining exact formatting. This approach is excellent for forms, briefs, and standardized documents where consistency matters. + +``` +Complete this template for the given product: + +PRODUCT BRIEF +───────────── +Name: _______________ +Tagline: _______________ +Target User: _______________ +Problem Solved: _______________ +Key Features: + 1. _______________ + 2. _______________ + 3. _______________ +Differentiator: _______________ + +Product: [product description] +``` + +## Typed Responses + +Typed responses define categories or entity types that the model should recognize and label. This technique is essential for Named Entity Recognition (NER), classification tasks, and any extraction where you need to categorize information consistently. Define your types clearly with examples. + + + +## Multi-Part Structured Responses + +When you need comprehensive output covering multiple aspects, define distinct parts with clear boundaries. Specify exactly what goes in each part—format, length, and content type. This prevents the model from blending sections or omitting parts. + +``` +Research this topic and provide: + +### PART 1: EXECUTIVE SUMMARY +[2-3 sentence overview] + +### PART 2: KEY FINDINGS +[Exactly 5 bullet points] + +### PART 3: DATA TABLE +| Metric | Value | Source | +|--------|-------|--------| +[Include 5 rows minimum] + +### PART 4: RECOMMENDATIONS +[Numbered list of 3 actionable recommendations] + +### PART 5: FURTHER READING +[3 suggested resources with brief descriptions] +``` + +## Conditional Formatting + +Conditional formatting lets you define different output formats based on the input's characteristics. This is powerful for classification, triage, and routing systems where the response format should vary based on what the model detects. Use clear if/then logic with explicit output templates for each case. + + + +## Arrays and Lists in JSON + +Extracting multiple items into arrays requires careful schema definition. Specify the array structure, what each item should contain, and how to handle edge cases (empty arrays, single items). Including a count field helps verify completeness. + +``` +Extract all action items from this meeting transcript. + +Return as JSON array: +{ + "action_items": [ + { + "task": "string describing the task", + "assignee": "person name or 'Unassigned'", + "deadline": "date if mentioned, else null", + "priority": "high" | "medium" | "low", + "context": "relevant quote from transcript" + } + ], + "total_count": number +} + +Transcript: "[meeting transcript]" +``` + +## Validation Instructions + +Self-validation prompts the model to check its own output before responding. This catches common issues like missing sections, placeholder text, or constraint violations. The model will iterate internally to fix problems, improving output quality without additional API calls. + +``` +Generate the report, then: + +VALIDATION CHECKLIST: +□ All required sections present +□ No placeholder text remaining +□ All statistics include sources +□ Word count within 500-700 words +□ Conclusion ties back to introduction + +If any check fails, fix before responding. +``` + +## Handling Optional Fields + +Real-world data often has missing values. Explicitly instruct the model on how to handle optional fields—using `null` is cleaner than empty strings and easier to process programmatically. Also prevent "hallucination" of missing data by emphasizing that the model should never invent information. + +``` +Extract contact information. Use null for missing fields. + +{ + "name": "string (required)", + "email": "string or null", + "phone": "string or null", + "company": "string or null", + "role": "string or null", + "linkedin": "URL string or null" +} + +IMPORTANT: +- Never invent information not in the source +- Use null, not empty strings, for missing data +- Phone numbers in E.164 format if possible +``` + +## Summary + + +Be explicit about format, use examples, specify types, handle edge cases with null values, and ask the model to validate its own output. + + + + +Structured outputs are essential for building reliable AI-powered applications. In the next chapter, we'll explore chain-of-thought prompting for complex reasoning tasks. diff --git a/src/content/book/pt/06-chain-of-thought.mdx b/src/content/book/pt/06-chain-of-thought.mdx new file mode 100644 index 00000000..e579be5d --- /dev/null +++ b/src/content/book/pt/06-chain-of-thought.mdx @@ -0,0 +1,363 @@ +Chain of Thought (CoT) prompting is a technique that dramatically improves AI performance on complex reasoning tasks by asking the model to show its work step by step. + + +Just like a math teacher asking students to show their work, CoT prompting asks the AI to make its reasoning visible. + + +## The Problem CoT Solves + +AI models can struggle with multi-step reasoning when asked to jump directly to an answer. + + + +## Basic CoT Prompts + +### Simple Trigger Phrases + +Add one of these to your prompts: + +
+
"Let's think step by step."
+
"Think through this carefully."
+
"Work through this problem methodically."
+
"Show your reasoning at each step."
+
"Explain your thought process."
+
+ +### Explicit Step Request + + + +## Zero-Shot vs Few-Shot CoT + +There are two main approaches to Chain of Thought prompting, each with different trade-offs between simplicity and control. + +### Zero-Shot CoT + +The simplest approach—just add a trigger phrase and let the model figure out how to reason. No examples needed. This works surprisingly well for many problems, though you have less control over the reasoning format. + + + +**Example Output:** +``` +Let's think step by step. +- John starts with 3 apples +- Half of 3 is 1.5, but we can't split apples +- If we round down: John gives 1 apple, keeps 2 +- After buying 4 more: 2 + 4 = 6 apples + +Answer: 6 apples +``` + +### Few-Shot CoT + +For more consistent results, show the model exactly how you want it to reason by providing worked examples. This gives you control over the reasoning style, format, and level of detail. The model will mimic your demonstrated pattern. + + + +**Example Output:** +``` +A: Let's work through this: +- Regular price: $3, Quantity: 12 +- Since 12 ≥ 10, the 25% discount applies +- Regular total: 12 × $3 = $36 +- Discount: 25% of $36 = $9 +- Final price: $36 - $9 = $27 +``` + +## Structured CoT Formats + +For consistent, reproducible reasoning, use structured formats with named steps. These frameworks ensure the model doesn't skip important stages and makes outputs easier to parse and verify. + +### The BREAK Format + +A memorable acronym that guides the model through a complete problem-solving cycle, from understanding to verification. + + + +### The Reasoning Template + +A more formal structure that separates inputs, goals, and execution. Excellent for technical problems where you need clear documentation of the solution process. + + + +**Example Output:** +``` +GIVEN: 8L/100km, tank 45L, $1.50/L, drive 300km +GOAL: Calculate fuel cost +APPROACH: Fuel needed × cost per liter +STEPS: +1. Fuel = (300 ÷ 100) × 8 = 24 liters +2. Cost = 24 × $1.50 = $36 +VERIFICATION: 24L < 45L tank ✓ +ANSWER: $36 +``` + +## CoT for Different Problem Types + +Different problem types benefit from different CoT approaches. Here are patterns optimized for common scenarios. + +### Mathematical Reasoning + +Math problems benefit most from CoT because each step builds on the previous one. Errors compound, so showing work helps catch mistakes early. The model should clearly label each calculation. + + + +**Example Output:** +``` +Q1: $1,200,000 (given) +Q2: $1,200,000 × 1.15 = $1,380,000 +Q3: $1,380,000 × 0.90 = $1,242,000 +Q4: $1,242,000 × 1.25 = $1,552,500 + +Total: $5,374,500 +``` + +### Logical Reasoning + +Logic puzzles require systematic elimination and hypothesis testing. CoT helps the model track constraints, test possibilities, and verify that all conditions are satisfied. The key is methodical exploration rather than guessing. + + + +**Example Output:** +``` +From clue 3: Bob = teacher +→ Alice and Carol are engineer/doctor + +If Carol = engineer: +- Carol has dog (clue 2) +- Alice = doctor, has fish (clue 1) +- Bob has cat + +Verify: All 4 clues satisfied ✓ +Answer: Alice (doctor, fish), Bob (teacher, cat), Carol (engineer, dog) +``` + +### Code Debugging + +Debugging benefits from CoT because it forces the model to trace execution rather than guess at bugs. By walking through the code with concrete values, the actual behavior becomes visible and discrepancies with expected behavior are exposed. + + + +**Example Output:** +``` +Trace [2, 3, 4, 6]: +n=2: total += 1 → 1 (wait, adding 1 not n!) +n=3: skip (odd) +n=4: total = 2 +n=6: total = 3 + +BUG: "total += 1" should be "total += n" +Expected: 12, Got: 3 +Fix: Change to "total += n" +``` + +## Self-Consistency with CoT + +For critical problems, don't rely on a single reasoning path. Generate multiple independent solutions and compare results. If different approaches converge on the same answer, confidence is high. Disagreement signals the need for careful review. + + + +**Example Output:** +``` +Approach 1 (Algebra): c + w = 30, 2c + 4w = 74 → c=23, w=7 +Approach 2 (Guess): Try 23/7 → 46 + 28 = 74 ✓ +Approach 3 (Logic): 30 chickens = 60 legs, need 14 more → 7 cows + +All agree: 23 chickens, 7 cows +``` + +## CoT for Decision Making + +Decisions involve weighing trade-offs across multiple dimensions. CoT ensures all relevant factors are considered systematically rather than jumping to conclusions. This structured approach also documents the reasoning for future reference. + + + +**Example Output:** +``` +FACTORS: +- Team size (5): Too small for microservices ❌ +- Scale (100 DAU): No scaling need ❌ +- Velocity: Monolith = faster iteration ❌ +- Future growth: Uncertain timeline ⚠️ + +WEIGHING: 3 strong against, 1 weak for + +RECOMMENDATION: Stay monolith, use clear module +boundaries to ease future transition. +``` + +## When to Use CoT + +
+
+

Use CoT For

+
+

**Math problems** — Reduces calculation errors

+

**Logic puzzles** — Prevents skipped steps

+

**Complex analysis** — Organizes thinking

+

**Code debugging** — Traces execution

+

**Decision making** — Weighs trade-offs

+
+
+
+

Skip CoT For

+
+

**Simple Q&A** — Unnecessary overhead

+

**Creative writing** — Can constrain creativity

+

**Factual lookups** — No reasoning needed

+

**Translation** — Direct task

+

**Summarization** — Usually straightforward

+
+
+
+ +## CoT Limitations + +While powerful, Chain of Thought isn't a silver bullet. Understanding its limitations helps you apply it appropriately. + +1. **Increased token usage** — More output means higher costs +2. **Not always needed** — Simple tasks don't benefit +3. **Can be verbose** — May need to ask for conciseness +4. **Reasoning can be flawed** — CoT doesn't guarantee correctness + +## Summary + + +CoT dramatically improves complex reasoning by making implicit steps explicit. Use it for math, logic, analysis, and debugging. Trade-off: better accuracy for more tokens. + + + + +In the next chapter, we'll explore few-shot learning—teaching the model through examples. diff --git a/src/content/book/pt/07-few-shot-learning.mdx b/src/content/book/pt/07-few-shot-learning.mdx new file mode 100644 index 00000000..24e98f1d --- /dev/null +++ b/src/content/book/pt/07-few-shot-learning.mdx @@ -0,0 +1,478 @@ +Few-shot learning is one of the most powerful prompting techniques. By providing examples of what you want, you can teach the model complex tasks without any fine-tuning. + + +Just like humans learn by seeing examples, AI models can learn patterns from the examples you provide in your prompt. + + +## What is Few-Shot Learning? + +Few-shot learning shows the model examples of input-output pairs before asking it to perform the same task. The model learns the pattern from your examples and applies it to new inputs. + + + +
+
+
0
+
Zero-shot
+
+
+
1
+
One-shot
+
+
+
2-5
+
Few-shot
+
+
+
5+
+
Many-shot
+
+
+ +## Why Examples Work + + + +Examples communicate: +- **Format**: How output should be structured +- **Style**: Tone, length, vocabulary +- **Logic**: The reasoning pattern to follow +- **Edge cases**: How to handle special situations + +## Basic Few-Shot Pattern + +The fundamental structure of few-shot prompting follows a simple pattern: show examples, then ask for the new task. Consistency in formatting between examples is crucial. The model learns from the pattern you establish. + +``` +[Example 1] +Input: [input 1] +Output: [output 1] + +[Example 2] +Input: [input 2] +Output: [output 2] + +[Example 3] +Input: [input 3] +Output: [output 3] + +Now do this one: +Input: [new input] +Output: +``` + +## Few-Shot for Classification + +Classification is one of the strongest use cases for few-shot learning. By showing examples of each category, you define the boundaries between classes more precisely than instructions alone could achieve. + +### Sentiment Analysis + + +Sentiment analysis classifies text by emotional tone: positive, negative, neutral, or mixed. It's widely used for customer feedback, social media monitoring, and brand perception tracking. + + +Sentiment classification benefits from showing examples of each sentiment type, especially edge cases like "mixed" sentiment that might be ambiguous. + + + +### Topic Classification + +For multi-class categorization, include at least one example per category. This helps the model understand your specific taxonomy, which may differ from its default understanding. + + + +## Few-Shot for Transformation + +Transformation tasks convert input from one form to another while preserving meaning. Examples are essential here because they define exactly what "transformation" means for your use case. + +### Text Rewriting + +Style transformation requires examples that show the exact tone shift you want. Abstract instructions like "make it professional" are interpreted differently. Examples make it concrete. + + + +### Format Conversion + +Format conversion tasks benefit from examples showing edge cases and ambiguous inputs. The model learns your specific conventions for handling tricky cases. + + + +## Few-Shot for Generation + +Generation tasks create new content following a learned pattern. Examples establish length, structure, tone, and what details to highlight. These are hard to specify in instructions alone. + +### Product Descriptions + +Marketing copy benefits enormously from examples because they capture brand voice, feature emphasis, and persuasive techniques that are difficult to describe abstractly. + + + +### Code Documentation + + +Good documentation explains what code does, its parameters, return values, and usage examples. Consistent docstrings enable auto-generated API docs and help IDEs provide better code completion. + + +Documentation style varies widely between projects. Examples teach your specific format, what to include (args, returns, examples), and the level of detail expected. + +>> calculate_bmi(70, 1.75) + 22.86 +""" + +Now document: +Function: +def is_palindrome(text): + cleaned = ''.join(c.lower() for c in text if c.isalnum()) + return cleaned == cleaned[::-1] + +Documentation:`} /> + +## Few-Shot for Extraction + +Extraction tasks pull structured information from unstructured text. Examples define which entities matter, how to format output, and how to handle cases where information is missing or ambiguous. + +### Entity Extraction + + +Named Entity Recognition (NER) identifies and classifies named entities in text into categories like persons, organizations, locations, dates, and products. It's fundamental for information retrieval and knowledge graphs. + + +NER benefits from examples showing your specific entity types and how to handle entities that could fit multiple categories. + + + +### Structured Data Extraction + +Extracting structured data from natural language requires examples showing how to handle missing fields, implicit information, and varying input formats. + + + +## Advanced Few-Shot Techniques + +Beyond basic few-shot, several techniques can improve results for complex tasks. + +### Diverse Examples + +Diversity in examples is more valuable than quantity. Cover different scenarios, edge cases, and potential ambiguities rather than showing similar examples repeatedly. + + + +### Negative Examples + + +Showing "good" vs "bad" examples is called contrastive learning. It helps the model understand not just what you want, but what to avoid. This is especially useful for style and quality judgments. + + +Sometimes showing what *not* to do is as valuable as showing correct examples. Negative examples help the model understand boundaries and avoid common mistakes. + + + +### Edge Case Examples + +Edge cases often determine whether a solution works in production. Including unusual inputs in your examples prevents the model from failing on real-world data that doesn't fit the "happy path." + + + +## How Many Examples? + +
+
+ Simple classification + 2-3 + One per category minimum +
+
+ Complex formatting + 3-5 + Show variations +
+
+ Nuanced style + 4-6 + Capture full range +
+
+ Edge cases + 1-2 + Alongside normal examples +
+
+ +## Example Quality Matters + + + +## Combining Few-Shot with Other Techniques + +Few-shot learning combines powerfully with other prompting techniques. The examples provide the "what" while other techniques can add context, reasoning, or structure. + +### Few-Shot + Role + +Adding a role gives the model context for *why* it's doing the task, which can improve quality and consistency. + +``` +You are a legal contract reviewer. + +[examples of contract clause analysis] + +Now analyze: [new clause] +``` + +### Few-Shot + CoT + +Combining few-shot with Chain of Thought shows not just *what* answer to give, but *how* to reason through to that answer. This is powerful for tasks requiring judgment. + +``` +Classify and explain reasoning. + +Review: "Great features but overpriced" +Thinking: The review mentions positive aspects ("great features") +but also a significant negative ("overpriced"). The negative seems +to outweigh the positive based on the "but" conjunction. +Classification: Mixed-Negative + +[more examples with reasoning] + +Now classify with reasoning: +Review: "Exactly what I needed, arrived faster than expected" +``` + +## Summary + + +Few-shot learning teaches through demonstration and is often more effective than instructions alone. Use 2-5 diverse, correct examples and combine with other techniques for best results. + + + + +In the next chapter, we'll explore iterative refinement: the art of improving prompts through successive attempts. diff --git a/src/content/book/pt/08-iterative-refinement.mdx b/src/content/book/pt/08-iterative-refinement.mdx new file mode 100644 index 00000000..769f879a --- /dev/null +++ b/src/content/book/pt/08-iterative-refinement.mdx @@ -0,0 +1,387 @@ +Prompt engineering is rarely a one-shot process. The best prompts emerge through iteration—testing, observing, and refining until you achieve the desired results. + + +Think of your first prompt as a rough draft. Even experienced prompt engineers rarely nail it on the first try. + + +## The Iteration Cycle + +Effective prompt refinement follows a predictable cycle: write, test, analyze, and improve. Each iteration brings you closer to a prompt that reliably produces the results you need. + + + +## Common Refinement Patterns + +Most prompt failures fall into a handful of categories. Learning to recognize these patterns lets you quickly diagnose and fix issues without starting from scratch. + +### Problem: Output Too Long + +One of the most common issues. Without explicit constraints, models tend to be thorough rather than concise. + + + +### Problem: Output Too Vague + +Vague prompts produce vague outputs. The model can't read your mind about what "better" means or which aspects matter most to you. + + + +### Problem: Wrong Tone + +Tone is subjective and varies by context. What sounds "professional" to the model might not match your organization's voice or the relationship with your recipient. + + + +### Problem: Missing Key Information + +Open-ended requests get open-ended responses. If you need specific types of feedback, you must ask for them explicitly. + + + +### Problem: Inconsistent Format + +Without a template, the model will structure each response differently, making comparison difficult and automation impossible. + + + +## Systematic Refinement Approach + +Random changes waste time. A systematic approach helps you identify problems quickly and fix them efficiently. + +### Step 1: Diagnose the Issue + +Before changing anything, identify what's actually wrong. Use this diagnostic table to map symptoms to solutions: + +
+
+ Symptom + Likely Cause + Solution +
+
+ Too long + No length constraint + Add word/sentence limits +
+
+ Too short + Lacks detail request + Ask for elaboration +
+
+ Off-topic + Vague instructions + Be more specific +
+
+ Wrong format + Format not specified + Define exact structure +
+
+ Wrong tone + Audience not clear + Specify audience/style +
+
+ Inconsistent + No examples provided + Add few-shot examples +
+
+ +### Step 2: Make Targeted Changes + +Resist the urge to rewrite everything. Changing multiple variables at once makes it impossible to know what helped and what hurt. Make one change, test it, then proceed: + +``` +Iteration 1: Add length constraint +Iteration 2: Specify format +Iteration 3: Add example +Iteration 4: Refine tone instructions +``` + +### Step 3: Document What Works + +Prompt engineering knowledge is easily lost. Keep a log of what you tried and why. This saves time when you revisit the prompt later or face similar challenges: + +```markdown +## Prompt: Customer Email Response + +### Version 1 (too formal) +"Write a response to this customer complaint." + +### Version 2 (better tone, still missing structure) +"Write a friendly but professional response to this complaint. +Show empathy first." + +### Version 3 (final - good results) +"Write a response to this customer complaint. Structure: +1. Acknowledge their frustration (1 sentence) +2. Apologize specifically (1 sentence) +3. Explain solution (2-3 sentences) +4. Offer additional help (1 sentence) + +Tone: Friendly, professional, empathetic but not groveling." +``` + +## Real-World Iteration Example + +Let's walk through a complete iteration cycle to see how each refinement builds on the last. Notice how each version addresses specific shortcomings of the previous one. + +### Task: Generate Product Names + + + +## Refinement Strategies by Task Type + +Different tasks fail in predictable ways. Knowing the common failure modes helps you diagnose and fix issues faster. + +### For Content Generation + +Content generation often produces generic, off-target, or poorly formatted output. The fix usually involves being more specific about constraints, providing concrete examples, or defining your brand voice explicitly. + + + +### For Code Generation + +Code output can fail technically (syntax errors, wrong language features) or architecturally (poor patterns, missing cases). Technical issues need version/environment specifics; architectural issues need design guidance. + + + +### For Analysis + +Analysis tasks often produce surface-level or unstructured results. Guide the model with specific frameworks (SWOT, Porter's Five Forces), request multiple viewpoints, or provide a template for the output structure. + + + +### For Q&A + +Question-answering can be too terse or too verbose, and may lack confidence indicators or sources. Specify the detail level you need and whether you want citations or uncertainty expressed. + + + +## The Feedback Loop Technique + +Here's a meta-technique: use the model itself to help improve your prompts. Share what you tried, what you got, and what you wanted. The model can often suggest improvements you hadn't considered. + +``` +I used this prompt: +"[your prompt]" + +And got this output: +"[model output]" + +I wanted something more [describe gap]. How should I modify +my prompt to get better results? +``` + +## A/B Testing Prompts + +For prompts that will be used repeatedly or at scale, don't just pick the first one that works. Test variations to find the most reliable and highest-quality approach. + +``` +Prompt A: "Summarize this article in 3 bullet points." +Prompt B: "Extract the 3 most important insights from this article." +Prompt C: "What are the key takeaways from this article? List 3." +``` + +Run each multiple times, compare: +- Consistency of output +- Quality of information +- Relevance to your needs + +## When to Stop Iterating + +Perfection is the enemy of good enough. Know when your prompt is ready for use and when you're just polishing for diminishing returns. + +
+
+

Ready to Ship

+
+

Output consistently meets requirements

+

Edge cases are handled appropriately

+

Format is reliable and parseable

+

Further improvements show diminishing returns

+
+
+
+

Keep Iterating

+
+

Output is inconsistent across runs

+

Edge cases cause failures

+

Critical requirements are missed

+

You haven't tested enough variations

+
+
+
+ +## Version Control for Prompts + +Prompts are code. For any prompt used in production, treat it with the same rigor: version control, changelogs, and the ability to roll back if something breaks. + + +prompts.chat includes automatic version history for your prompts. Every edit is saved, so you can compare versions and restore previous iterations with one click. + + +For self-managed prompts, use a folder structure: + +``` +prompts/ +├── customer-response/ +│ ├── v1.0.txt # Initial version +│ ├── v1.1.txt # Fixed tone issue +│ ├── v2.0.txt # Major restructure +│ └── current.txt # Symlink to active version +└── changelog.md # Document changes +``` + +## Summary + + +Start simple, observe carefully, change one thing at a time, document what works, and know when to stop. The best prompts aren't written—they're discovered through systematic iteration. + + + + +## Practice: Improve This Prompt + +Try improving this weak prompt yourself. Edit it, then use AI to compare your version with the original: + + + +In the next chapter, we'll explore JSON and YAML prompting for structured data applications. diff --git a/src/content/book/pt/09-json-yaml-prompting.mdx b/src/content/book/pt/09-json-yaml-prompting.mdx new file mode 100644 index 00000000..318619da --- /dev/null +++ b/src/content/book/pt/09-json-yaml-prompting.mdx @@ -0,0 +1,586 @@ +Structured data formats like JSON and YAML are essential for building applications that consume AI outputs programmatically. This chapter covers techniques for reliable structured output generation. + + +JSON and YAML transform AI outputs from freeform text into structured, type-safe data that code can consume directly. + + +## Why Structured Formats? + + + +## JSON Prompting Basics + +JSON (JavaScript Object Notation) is the most common format for programmatic AI outputs. Its strict syntax makes it easy to parse, but also means small errors can break your entire pipeline. + +### Do's and Don'ts: Requesting JSON + + + +### Simple JSON Output + +Start with a schema showing the expected structure. The model will fill in values based on the input text. + +``` +Extract the following information as JSON: + +{ + "name": "string", + "age": number, + "email": "string" +} + +Text: "Contact John Smith, 34 years old, at john@example.com" +``` + +Output: +```json +{ + "name": "John Smith", + "age": 34, + "email": "john@example.com" +} +``` + +### Nested JSON Structures + +Real-world data often has nested relationships. Define each level of your schema clearly, especially for arrays of objects. + +``` +Parse this order into JSON: + +{ + "order_id": "string", + "customer": { + "name": "string", + "email": "string" + }, + "items": [ + { + "product": "string", + "quantity": number, + "price": number + } + ], + "total": number +} + +Order: "Order #12345 for Jane Doe (jane@email.com): 2x Widget ($10 each), +1x Gadget ($25). Total: $45" +``` + +### Ensuring Valid JSON + + +Models often wrap JSON in markdown code blocks or add explanatory text. Be explicit about wanting raw JSON only. + + +Add explicit instructions: + +``` +CRITICAL: Return ONLY valid JSON. No markdown, no explanation, +no additional text before or after the JSON object. + +If a field cannot be determined, use null. +Ensure all strings are properly quoted and escaped. +Numbers should not be quoted. +``` + +## YAML Prompting Basics + +YAML is more human-readable than JSON and supports comments. It's the standard for configuration files, especially in DevOps (Docker, Kubernetes, GitHub Actions). + +### Simple YAML Output + +YAML uses indentation instead of braces. Provide a template showing the expected structure. + +``` +Generate a configuration file in YAML format: + +server: + host: string + port: number + ssl: boolean +database: + type: string + connection_string: string + +Requirements: Production server on port 443 with SSL, PostgreSQL database +``` + +Output: +```yaml +server: + host: "0.0.0.0" + port: 443 + ssl: true +database: + type: "postgresql" + connection_string: "postgresql://user:pass@localhost:5432/prod" +``` + +### Complex YAML Structures + +For complex configurations, be specific about requirements. The model knows common patterns for tools like GitHub Actions, Docker Compose, and Kubernetes. + +``` +Generate a GitHub Actions workflow in YAML: + +Requirements: +- Trigger on push to main and pull requests +- Run on Ubuntu latest +- Steps: checkout, setup Node 18, install dependencies, run tests +- Cache npm dependencies +``` + +## Type Definitions in Prompts + +Type definitions give the model a precise contract for output structure. They're more explicit than examples and easier to validate programmatically. + +### Using TypeScript-like Types + +TypeScript interfaces are familiar to developers and precisely describe optional fields, union types, and arrays. The prompts.chat platform uses this approach for structured prompts. + + + +### JSON Schema Definition + + +JSON Schema is a formal specification for describing JSON structure. It's supported by many validation libraries and API tools. + + +JSON Schema provides constraints like min/max values, required fields, and regex patterns: + +``` +Extract data according to this JSON Schema: + +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "type": "object", + "required": ["title", "author", "year"], + "properties": { + "title": { "type": "string" }, + "author": { "type": "string" }, + "year": { "type": "integer", "minimum": 1000, "maximum": 2100 }, + "genres": { + "type": "array", + "items": { "type": "string" } + }, + "rating": { + "type": "number", + "minimum": 0, + "maximum": 5 + } + } +} + +Book: "1984 by George Orwell (1949) - A dystopian masterpiece. +Genres: Science Fiction, Political Fiction. Rated 4.8/5" +``` + +## Handling Arrays + +Arrays require special attention. Specify whether you need a fixed number of items or a variable-length list, and how to handle empty cases. + +### Fixed-Length Arrays + +When you need exactly N items, state it explicitly. The model will ensure the array has the right length. + +``` +Extract exactly 3 key points as JSON: + +{ + "key_points": [ + "string (first point)", + "string (second point)", + "string (third point)" + ] +} + +Article: [article text] +``` + +### Variable-Length Arrays + +For variable-length arrays, specify what to do when there are zero items. Including a count field helps verify extraction completeness. + +``` +Extract all mentioned people as JSON: + +{ + "people": [ + { + "name": "string", + "role": "string or null if not mentioned" + } + ], + "count": number +} + +If no people are mentioned, return empty array. + +Text: [text] +``` + +## Enum Values and Constraints + +Enums restrict values to a predefined set. This is crucial for classification tasks and anywhere you need consistent, predictable outputs. + +### Do's and Don'ts: Enum Values + + + +### String Enums + +List allowed values explicitly. Use "MUST be one of" language to enforce strict matching. + +``` +Classify this text. The category MUST be one of these exact values: +- "technical" +- "business" +- "creative" +- "personal" + +Return JSON: +{ + "text": "original text (truncated to 50 chars)", + "category": "one of the enum values above", + "confidence": number between 0 and 1 +} + +Text: [text to classify] +``` + +### Validated Numbers + +Numeric constraints prevent out-of-range values. Specify the type (integer vs float) and valid range. + +``` +Rate these aspects. Each score MUST be an integer from 1 to 5. + +{ + "quality": 1-5, + "value": 1-5, + "service": 1-5, + "overall": 1-5 +} + +Review: [review text] +``` + +## Handling Missing Data + +Real-world text often lacks some information. Define how the model should handle missing data to avoid hallucinated values. + +### Do's and Don'ts: Missing Information + + + +### Null Values + +Explicitly allow null and instruct the model not to invent information. This is safer than having the model guess. + +``` +Extract information. Use null for any field that cannot be +determined from the text. Do NOT invent information. + +{ + "company": "string or null", + "revenue": "number or null", + "employees": "number or null", + "founded": "number (year) or null", + "headquarters": "string or null" +} + +Text: "Apple, headquartered in Cupertino, was founded in 1976." +``` + +Output: +```json +{ + "company": "Apple", + "revenue": null, + "employees": null, + "founded": 1976, + "headquarters": "Cupertino" +} +``` + +### Default Values + +When defaults make sense, specify them in the schema. This is common for configuration extraction. + +``` +Extract settings with these defaults if not specified: + +{ + "theme": "light" (default) | "dark", + "language": "en" (default) | other ISO code, + "notifications": true (default) | false, + "fontSize": 14 (default) | number +} + +User preferences: "I want dark mode and larger text (18px)" +``` + +## Multi-Object Responses + +Often you need to extract multiple items from a single input. Define the array structure and any sorting/grouping requirements. + +### Array of Objects + +For lists of similar items, define the object schema once and specify it's an array. + +``` +Parse this list into JSON array: + +[ + { + "task": "string", + "priority": "high" | "medium" | "low", + "due": "ISO date string or null" + } +] + +Todo list: +- Finish report (urgent, due tomorrow) +- Call dentist (low priority) +- Review PR #123 (medium, due Friday) +``` + +### Grouped Objects + +Grouping tasks require categorization logic. The model will sort items into the categories you define. + +``` +Categorize these items into JSON: + +{ + "fruits": ["string array"], + "vegetables": ["string array"], + "other": ["string array"] +} + +Items: apple, carrot, bread, banana, broccoli, milk, orange, spinach +``` + +## YAML for Configuration Generation + +YAML shines for DevOps configurations. The model knows standard patterns for common tools and can generate production-ready configs. + +### Do's and Don'ts: YAML Configs + + + +### Docker Compose + +Specify the services you need and any special requirements. The model will handle the YAML syntax and best practices. + +``` +Generate a docker-compose.yml for: +- Node.js app on port 3000 +- PostgreSQL database +- Redis cache +- Nginx reverse proxy + +Include: +- Health checks +- Volume persistence +- Environment variables from .env file +- Network isolation +``` + +### Kubernetes Manifests + +Kubernetes manifests are verbose but follow predictable patterns. Provide the key parameters and the model will generate compliant YAML. + +``` +Generate Kubernetes deployment YAML: + +Deployment: +- Name: api-server +- Image: myapp:v1.2.3 +- Replicas: 3 +- Resources: 256Mi memory, 250m CPU (requests) +- Health checks: /health endpoint +- Environment from ConfigMap: api-config + +Also generate matching Service (ClusterIP, port 8080) +``` + +## Validation and Error Handling + +For production systems, build validation into your prompts. This catches errors before they propagate through your pipeline. + +### Self-Validation Prompt + +Ask the model to validate its own output against rules you specify. This catches format errors and invalid values. + +``` +Extract data as JSON, then validate your output. + +Schema: +{ + "email": "valid email format", + "phone": "E.164 format (+1234567890)", + "date": "ISO 8601 format (YYYY-MM-DD)" +} + +After generating JSON, check: +1. Email contains @ and valid domain +2. Phone starts with + and contains only digits +3. Date is valid and parseable + +If validation fails, fix the issues before responding. + +Text: [contact information] +``` + +### Error Response Format + +Define separate success and error formats. This makes programmatic handling much easier. + +``` +Attempt to extract data. If extraction fails, return error format: + +Success format: +{ + "success": true, + "data": { ... extracted data ... } +} + +Error format: +{ + "success": false, + "error": "description of what went wrong", + "partial_data": { ... any data that could be extracted ... } +} +``` + +## JSON vs YAML: When to Use Which + +
+
+
Use JSON When
+
+

Programmatic parsing needed

+

API responses

+

Strict type requirements

+

JavaScript/Web integration

+

Compact representation

+
+
+
+
Use YAML When
+
+

Human readability matters

+

Configuration files

+

Comments are needed

+

DevOps/Infrastructure

+

Deep nested structures

+
+
+
+ +## Prompts.chat Structured Prompts + +On prompts.chat, you can create prompts with structured output formats: + +``` +When creating a prompt on prompts.chat, you can specify: + +Type: STRUCTURED +Format: JSON or YAML + +The platform will: +- Validate outputs against your schema +- Provide syntax highlighting +- Enable easy copying of structured output +- Support template variables in your schema +``` + +## Common Pitfalls + + +These three issues cause most JSON parsing failures. Check for them when your code can't parse AI output. + + +### 1. Markdown Code Blocks + +**Problem:** Model wraps JSON in ```json blocks + +**Solution:** +``` +Return ONLY the JSON object. Do not wrap in markdown code blocks. +Do not include ```json or ``` markers. +``` + +### 2. Trailing Commas + +**Problem:** Invalid JSON due to trailing commas + +**Solution:** +``` +Ensure valid JSON syntax. No trailing commas after the last +element in arrays or objects. +``` + +### 3. Unescaped Strings + +**Problem:** Quotes or special characters break JSON + +**Solution:** +``` +Properly escape special characters in strings: +- \" for quotes +- \\ for backslashes +- \n for newlines +``` + +## Summary + + +Define schemas explicitly using TypeScript interfaces or JSON Schema. Specify types and constraints, handle nulls and defaults, request self-validation, and choose the right format for your use case. + + + + +This completes Part II on techniques. In Part III, we'll explore practical applications across different domains. diff --git a/src/content/book/pt/10-system-prompts-personas.mdx b/src/content/book/pt/10-system-prompts-personas.mdx new file mode 100644 index 00000000..c6737cda --- /dev/null +++ b/src/content/book/pt/10-system-prompts-personas.mdx @@ -0,0 +1,435 @@ +System prompts are like giving AI its personality and job description before a conversation starts. Think of it as the "backstage instructions" that shape everything the AI says. + + +A system prompt is a special message that tells the AI who it is, how to behave, and what it can or can't do. Users don't usually see this message, but it affects every response. + + + +System prompts build on the concepts from [Role-Based Prompting](/book/04-role-based-prompting). While role prompts assign a persona within your message, system prompts set that identity at a deeper level that persists across the entire conversation. + + +## How System Prompts Work + +When you chat with AI, there are actually three types of messages: + + + +The system message stays active for the whole conversation. It's like the AI's "instruction manual." + +## Building a System Prompt + +A good system prompt has five parts. Think of them as filling out a character sheet for the AI: + + + +### Example: A Coding Tutor + + + +## Persona Patterns + +Different tasks need different AI personalities. Here are three common patterns you can adapt: + +### 1. The Expert + +Best for: Learning, research, professional advice + + + +### 2. The Assistant + +Best for: Productivity, organization, getting things done + + + +### 3. The Character + +Best for: Creative writing, roleplay, entertainment + + + +## Advanced Techniques + +### Layered Instructions + +Think of your system prompt like an onion with layers. The inner layers are most important: + + + +### Adaptive Behavior + +Make your AI adjust to different users automatically: + + + +### Conversation Memory + +AI doesn't remember past conversations, but you can tell it to track things within the current chat: + + + +## Real-World Examples + +Here are complete system prompts for common use cases. Click to try them! + +### Customer Support Bot + + + +### Study Buddy + + + +### Writing Coach + + + +## Testing Your System Prompt + +Before using a system prompt for real, test it! Here's what to check: + + + +### Understanding Jailbreak Attacks + +"Jailbreaking" is when someone tries to trick AI into ignoring its rules. Understanding these attacks helps you build better defenses. + + + +### More Test Scenarios + +Use these interactive examples to see how a well-designed system prompt handles tricky situations: + +#### Test 1: Jailbreak Attempt + +See how a good system prompt resists attempts to override it: + + + +#### Test 2: Stay in Character + +Test if the AI maintains its persona when pushed: + + + +#### Test 3: Boundary Enforcement + +Check if the AI respects its stated limitations: + + + +#### Test 4: Reveal System Prompt + +See if the AI protects its instructions: + + + +#### Test 5: Conflicting Instructions + +Test how the AI handles contradictory requests: + + + + +A well-crafted system prompt will: +- Politely decline inappropriate requests +- Stay in character while redirecting +- Not reveal confidential instructions +- Handle edge cases gracefully + + +## Quick Reference + +
+
+

Do

+
    +
  • Give a clear identity
  • +
  • List specific capabilities
  • +
  • Set explicit boundaries
  • +
  • Define the tone and style
  • +
  • Include example responses
  • +
+
+
+

Don't

+
    +
  • Be vague about the role
  • +
  • Forget to set limits
  • +
  • Make it too long (500 words max)
  • +
  • Contradict yourself
  • +
  • Assume the AI will "figure it out"
  • +
+
+
+ +## Summary + +System prompts are the AI's instruction manual. They set up: +- **Who** the AI is (identity and expertise) +- **What** it can and can't do (capabilities and limits) +- **How** it should respond (tone, format, style) + + +Begin with a short system prompt and add more rules as you discover what's needed. A clear 100-word prompt beats a confusing 500-word one. + + + + + + +In the next chapter, we'll explore prompt chaining: connecting multiple prompts together for complex multi-step tasks. diff --git a/src/content/book/pt/11-prompt-chaining.mdx b/src/content/book/pt/11-prompt-chaining.mdx new file mode 100644 index 00000000..9f54da52 --- /dev/null +++ b/src/content/book/pt/11-prompt-chaining.mdx @@ -0,0 +1,379 @@ +Prompt chaining breaks complex tasks into sequences of simpler prompts, where each step's output feeds into the next. This technique dramatically improves reliability and enables sophisticated workflows that would be impossible with a single prompt. + + +Just like a factory assembly line breaks manufacturing into specialized stations, prompt chaining breaks AI tasks into specialized steps. Each step does one thing well, and the combined output is far better than trying to do everything at once. + + +## Why Chain Prompts? + +Single prompts struggle with complex tasks because they try to do too much at once. The AI has to simultaneously understand, analyze, plan, and generate, which leads to errors and inconsistencies. + +
+
+

Single Prompt Struggles

+
+

Multi-step reasoning gets confused

+

Different "modes" of thinking clash

+

Complex outputs lack consistency

+

No opportunity for quality control

+
+
+
+

Chaining Solves This

+
+

Each step focuses on one task

+

Specialized prompts for each mode

+

Validate between steps

+

Debug and improve individual steps

+
+
+
+ +## Basic Chaining Pattern + +The simplest chain passes output from one prompt directly to the next. Each step has a clear, focused purpose. + +
+
+
+

Prompt 1

+

(Extract)

+
+

Input

+
+
→
+
+
+

Prompt 2

+

(Analyze)

+
+

Intermediate

+
+
→
+
+
+

Prompt 3

+

(Generate)

+
+

Output

+
+
+ + +The most common chain pattern is **Extract → Transform → Generate**. First extract raw data, then reshape it for your purpose, then generate the final output. This pattern works for almost any content task. + + +## Chain Types + +Different tasks require different chain architectures. Choose the pattern that matches your workflow. + + + +### Sequential Chain + +The most straightforward pattern: each step depends on the previous. Think of it as a relay race where each runner passes the baton to the next. + + + +### Parallel Chain + +When you need multiple perspectives on the same input, run prompts in parallel and merge results. This is faster than sequential chains and provides richer analysis. + + + +### Conditional Chain + +Route inputs through different paths based on classification. This is like a decision tree where the AI first categorizes the input, then handles each category differently. + + + +### Iterative Chain + +Keep refining output until it meets quality standards. The AI generates, evaluates, and improves in a loop until satisfied or max iterations reached. + + +Always set a maximum number of iterations (typically 3-5) to prevent infinite loops and control costs. The law of diminishing returns applies: most improvement happens in the first 2-3 iterations. + + += 8: EXIT LOOP' } + ]} +/> + +## Common Chain Patterns + +These battle-tested patterns solve common problems. Use them as starting points and adapt to your needs. + +### Extract → Transform → Generate + +The workhorse of content processing. Pull data out, reshape it, then create something new. + +
+

Best For

+

Document summarization, report generation, content repurposing, data-to-narrative conversion

+
+ + + +### Analyze → Plan → Execute + +Perfect for code refactoring, project planning, or any task where you need to understand before acting. + +
+

Best For

+

Code refactoring, project planning, troubleshooting, strategic decision-making, complex problem solving

+
+ + {\n const { email, password } = req.body;\n if (!email || !isValidEmail(email)) {\n return res.status(400).json({ error: 'Invalid email' });\n }\n next();\n};" } + ]} +/> + +### Generate → Critique → Refine + +The self-improvement loop. Generate content, have the AI evaluate it critically, then improve based on that feedback. This mimics how professional writers and editors work together. + +
+

Best For

+

Marketing copy, creative writing, email drafts, presentations, any content that benefits from revision

+
+ + + +## Implementing Chains + +You can implement chains manually for experimentation, or programmatically for production systems. Start simple and add complexity as needed. + +### Manual Chaining + +The copy-paste approach is perfect for prototyping and experimentation. Run each prompt manually, examine the output, and paste it into the next prompt. + + + +### Programmatic Chaining + +For production systems, automate the chain with code. This enables error handling, logging, and integration with your application. + + + +### Using Chain Templates + +Define chains as configuration files for reusability and easy modification. This separates prompt logic from application code. + + + +## Error Handling in Chains + +Chains can fail at any step. Build in validation, retries, and fallbacks to make your chains robust. + + + + +If one step produces bad output, every following step will be affected. Always validate critical intermediate results before passing them forward. + + +### Validation Between Steps + +Add a validation step after any step that produces structured data. This catches errors early before they cascade. + + + +### Fallback Chains + +When your primary approach fails, have a simpler backup ready. Trade capability for reliability. + + + +## Chain Optimization + +Once your chain works, optimize for speed, cost, and reliability. These often trade off against each other. + +
+
+

Reducing Latency

+
+

Parallelize independent steps

+

Cache intermediate results

+

Use smaller models for simple steps

+

Batch similar operations

+
+
+
+

Reducing Cost

+
+

Use cheaper models for classification

+

Limit iterations in loops

+

Short-circuit when possible

+

Cache repeated queries

+
+
+
+

Improving Reliability

+
+

Add validation between steps

+

Include retry logic

+

Log intermediate results

+

Implement fallback paths

+
+
+
+ +## Real-World Chain Example + +Let's walk through a complete production chain. This content pipeline transforms a raw idea into a polished article package. + +### Content Pipeline Chain + + + +## Summary + +Prompt chaining transforms what AI can accomplish by breaking impossible tasks into achievable steps. + +
+
+

Chaining Enables

+
+

Complex multi-step workflows

+

Higher quality through specialization

+

Better error handling and validation

+

Modular, reusable prompt components

+
+
+
+

Key Principles

+
+

Break complex tasks into simple steps

+

Design clear interfaces between steps

+

Validate intermediate outputs

+

Build in error handling and fallbacks

+

Optimize for your constraints

+
+
+
+ + +Begin with a 2-3 step sequential chain. Get it working reliably before adding complexity. Most tasks don't need elaborate chain architectures. + + + + +In the next chapter, we'll explore multimodal prompting: working with images, audio, and other non-text content. diff --git a/src/content/book/pt/12-handling-edge-cases.mdx b/src/content/book/pt/12-handling-edge-cases.mdx new file mode 100644 index 00000000..4708ee3c --- /dev/null +++ b/src/content/book/pt/12-handling-edge-cases.mdx @@ -0,0 +1,580 @@ +Prompts that work perfectly in testing often fail in the real world. Users send empty messages, paste walls of text, make ambiguous requests, and sometimes try to break your system intentionally. This chapter teaches you to build prompts that handle the unexpected gracefully. + + +80% of production issues come from inputs you never anticipated. A prompt that handles edge cases well is worth more than a "perfect" prompt that only works with ideal inputs. + + +## Why Edge Cases Break Prompts + +When a prompt encounters unexpected input, it typically fails in one of three ways: + +**Silent Failures**: The model produces output that looks correct but contains errors. These are the most dangerous because they're hard to detect. + +**Confused Responses**: The model misinterprets the request and answers a different question than what was asked. + +**Hallucinated Handling**: The model invents a way to handle the edge case that doesn't match your intended behavior. + + + +## Categories of Edge Cases + +Understanding what can go wrong helps you prepare for it. Edge cases fall into three main categories: + +### Input Edge Cases + +These are problems with the data itself: + + + +### Domain Edge Cases + +These are requests that push the boundaries of your prompt's purpose: + + + +### Adversarial Edge Cases + +These are deliberate attempts to misuse your system: + + + +## Input Validation Patterns + +The key to handling edge cases is explicit instructions. Don't assume the model will "figure it out" - tell it exactly what to do in each scenario. + +### Handling Empty Input + +The most common edge case is receiving nothing at all, or input that's essentially empty (just whitespace or greetings). + + + +### Handling Long Input + +When input exceeds what you can reasonably process, fail gracefully rather than silently truncating. + + + +### Handling Ambiguous Requests + +When a request could mean multiple things, asking for clarification is better than guessing wrong. + + + +## Building Defensive Prompts + +A defensive prompt anticipates failure modes and defines explicit behavior for each. Think of it as error handling for natural language. + +### The Defensive Template + +Every robust prompt should address these four areas: + + + +### Example: Defensive Data Extraction + +This prompt extracts contact information but handles every edge case explicitly. Notice how each potential failure has a defined response. + + + +## Handling Out-of-Scope Requests + +Every prompt has boundaries. Defining them explicitly prevents the model from wandering into territory where it might give bad advice or make things up. + +### Graceful Scope Limits + +The best out-of-scope responses do three things: acknowledge the request, explain the limitation, and offer an alternative. + + + +### Handling Knowledge Cutoffs + +Be honest about what you don't know. Users trust AI more when it admits limitations. + + + +## Adversarial Input Handling + +Some users will try to manipulate your prompts, either out of curiosity or malicious intent. Building defenses into your prompts reduces these risks. + +### Prompt Injection Defense + +Prompt injection is when a user tries to override your instructions by embedding their own commands in the input. The key defense is treating user input as data, never as instructions. + + + + +Prompt injection defenses reduce risk but can't eliminate it entirely. For high-stakes applications, combine prompt defenses with input sanitization, output filtering, and human review. + + +### Handling Sensitive Requests + +Some requests require special handling due to safety, legal, or ethical concerns. Define these boundaries explicitly. + + + +## Error Recovery Patterns + +Even well-designed prompts will encounter situations they can't handle perfectly. The goal is to fail helpfully. + +### Graceful Degradation + +When you can't fully complete a task, offer what you can rather than failing completely. + + + +### Confidence Indicators + +Teach your prompts to express uncertainty. This helps users know when to trust the output and when to verify. + + + + + +## Testing Edge Cases + +Before deploying a prompt, systematically test it against the edge cases you've anticipated. This checklist helps ensure you haven't missed common failure modes. + +### Edge Case Testing Checklist + + + + + + + + + +### Creating a Test Suite + +For production prompts, create a systematic test suite. Here's a pattern you can adapt: + + + +## Real-World Example: Robust Customer Service Bot + +This comprehensive example shows how all the patterns come together in a production-ready prompt. Notice how every edge case has explicit handling. + + + +## Summary + +Building robust prompts requires thinking about what can go wrong before it does. The key principles: + + + + +In production, everything that can go wrong eventually will. A prompt that handles edge cases gracefully is worth more than a "perfect" prompt that only works with ideal inputs. + + + + +In the next chapter, we'll explore how to work with multiple AI models and compare their outputs. diff --git a/src/content/book/pt/13-multimodal-prompting.mdx b/src/content/book/pt/13-multimodal-prompting.mdx new file mode 100644 index 00000000..376960ae --- /dev/null +++ b/src/content/book/pt/13-multimodal-prompting.mdx @@ -0,0 +1,665 @@ +For most of history, computers worked with one type of data at a time: text in one program, images in another, audio somewhere else. But humans don't experience the world this way. We see, hear, read, and speak simultaneously, combining all these inputs to understand our environment. + +**Multimodal AI** changes everything. These models can process multiple types of information together—analyzing an image while reading your question about it, or generating images from your text descriptions. This chapter teaches you how to communicate effectively with these powerful systems. + + +"Multi" means many, and "modal" refers to modes or types of data. A multimodal model can work with multiple modalities: text, images, audio, video, or even code. Instead of separate tools for each type, one model understands them all together. + + +## Why Multimodal Matters + +Traditional AI required you to describe everything in words. Want to ask about an image? You'd have to describe it first. Want to analyze a document? You'd need to transcribe it manually. Multimodal models eliminate these barriers. + + + +## Why Prompting Matters Even More for Multimodal + +With text-only models, the AI receives exactly what you type. But with multimodal models, the AI must interpret visual or audio information—and interpretation requires guidance. + + + +**Without guidance**, the model might describe colors, layout, or irrelevant details. **With guidance**, it focuses on what actually matters to you. + + +When you look at an image, you instantly know what's important based on your context and goals. The AI doesn't have this context unless you provide it. A photo of a crack in a wall could be: a structural engineering concern, an artistic texture, or irrelevant background. Your prompt determines how the AI interprets it. + + +## The Multimodal Landscape + +Different models have different capabilities. Here's what's available in 2025: + +### Understanding Models (Input → Analysis) + +These models accept various media types and produce text analysis or responses. + + + +### Generation Models (Text → Media) + +These models create images, audio, or video from text descriptions. + + + + +The multimodal landscape changes quickly. New models launch frequently, and existing models gain capabilities through updates. Always check the latest documentation for current features and limitations. + + +## Image Understanding Prompts + +The most common multimodal use case is asking AI to analyze images. The key is providing context about what you need. + +### Basic Image Analysis + +Start with a clear request structure. Tell the model what aspects to focus on. + + + +### Structured Output for Images + +When you need to process image analysis programmatically, request JSON output. + + + +### Comparative Analysis + +Comparing multiple images requires clear labeling and specific comparison criteria. + + + +## Document and Screenshot Analysis + +One of the most practical applications of multimodal AI is analyzing documents, screenshots, and UI elements. This saves hours of manual transcription and review. + +### Document Extraction + +Scanned documents, photos of receipts, and PDFs as images can all be processed. The key is telling the model what type of document it is and what information you need. + + + +### Screenshot and UI Analysis + +Screenshots are goldmines for debugging, UX review, and documentation. Guide the AI to focus on what matters. + + + +### Error Message Analysis + +When you encounter an error, a screenshot often contains more context than copying the error text alone. + + + +## Image Generation Prompts + +Generating images from text descriptions is an art form. The more specific and structured your prompt, the closer the result will match your vision. + +### The Anatomy of an Image Prompt + +Effective image generation prompts have several components: + + + +### Basic Image Generation + + + +### Scene Building + +For complex scenes, describe layers from foreground to background. + + + +## Audio Prompting + +Audio processing opens up transcription, analysis, and understanding of spoken content. The key is providing context about what the audio contains. + +### Enhanced Transcription + +Basic transcription is just the start. With good prompts, you can get speaker identification, timestamps, and domain-specific accuracy. + + + +### Audio Content Analysis + +Beyond transcription, AI can analyze the content, tone, and key moments in audio. + + + +## Video Prompting + +Video combines visual and audio analysis over time. The challenge is guiding the AI to focus on the relevant aspects across the entire duration. + +### Video Understanding + + + +### Video Content Extraction + +For specific information extraction from videos, be precise about what you need. + + + +## Multimodal Combinations + +The real power of multimodal AI emerges when you combine different types of input. These combinations enable analysis that would be impossible with any single modality. + +### Image + Text Verification + +Check if images and their descriptions match—essential for e-commerce, content moderation, and quality assurance. + + + +### Screenshot + Code Debugging + +One of the most powerful combinations for developers: seeing the visual bug alongside the code. + + + +### Multi-Image Decision Making + +When choosing between options, structured comparison helps make better decisions. + + + +## Best Practices for Multimodal Prompts + +Getting great results from multimodal AI requires understanding both its capabilities and limitations. + +### What Makes Multimodal Prompts Effective + + + +### Common Pitfalls to Avoid + + + +### Handling Limitations Gracefully + + + + diff --git a/src/content/book/pt/14-context-engineering.mdx b/src/content/book/pt/14-context-engineering.mdx new file mode 100644 index 00000000..b9c69b6d --- /dev/null +++ b/src/content/book/pt/14-context-engineering.mdx @@ -0,0 +1,287 @@ +Understanding context is essential for building AI applications that actually work. This chapter covers everything you need to know about giving AI the right information at the right time. + + +AI models are stateless. They don't remember past conversations. Every time you send a message, you need to include everything the AI needs to know. This is called "context engineering." + + +## What is Context? + +Context is all the information you give to AI alongside your question. Think of it like this: + + + +Without context, the AI has no idea what "status" you're asking about. With context, it can give a useful answer. + +### The Context Window + +Remember from earlier chapters: AI has a limited "context window" - the maximum amount of text it can see at once. This includes: + + + +## AI is Stateless + + +AI doesn't remember anything between conversations. Every API call starts fresh. If you want the AI to "remember" something, YOU have to include it in the context every time. + + +This is why chatbots send your entire conversation history with each message. It's not that the AI remembers - it's that the app re-sends everything. + + + +The AI will say it doesn't know because it truly doesn't have access to any previous context. + +## RAG: Retrieval-Augmented Generation + +RAG is a technique for giving AI access to knowledge it wasn't trained on. Instead of trying to fit everything into the AI's training, you: + +1. **Store** your documents in a searchable database +2. **Search** for relevant documents when a user asks a question +3. **Retrieve** the most relevant pieces +4. **Augment** your prompt with those pieces +5. **Generate** an answer using that context + +
+

How RAG Works:

+
+
+ 1 + User asks: "What's our refund policy?" +
+
+ 2 + System searches your documents for "refund policy" +
+
+ 3 + Finds relevant section from your policy document +
+
+ 4 + Sends to AI: "Based on this policy: [text], answer: What's our refund policy?" +
+
+ 5 + AI generates accurate answer using your actual policy +
+
+
+ +### Why RAG? + +
+
+

RAG Advantages

+
    +
  • Uses your actual, current data
  • +
  • Reduces hallucinations
  • +
  • Can cite sources
  • +
  • Easy to update (just update documents)
  • +
  • No expensive fine-tuning needed
  • +
+
+
+

When to Use RAG

+
    +
  • Customer support bots
  • +
  • Documentation search
  • +
  • Internal knowledge bases
  • +
  • Any domain-specific Q&A
  • +
  • When accuracy matters
  • +
+
+
+ +## Embeddings: How Search Works + +How does RAG know which documents are "relevant"? It uses **embeddings** - a way to turn text into numbers that capture meaning. + +### What Are Embeddings? + +An embedding is a list of numbers (a "vector") that represents the meaning of text. Similar meanings = similar numbers. + + + +### Semantic Search + +With embeddings, you can search by meaning, not just keywords: + + + +This is why RAG is so powerful - it finds relevant information even when the exact words don't match. + +## Function Calling / Tool Use + +Function calling lets AI use external tools - like searching the web, checking a database, or calling an API. + + +Different AI providers call this different things: "function calling" (OpenAI), "tool use" (Anthropic/Claude), or "tools" (general term). They all mean the same thing. + + +### How It Works + +1. You tell the AI what tools are available +2. AI decides if it needs a tool to answer +3. AI outputs a structured request for the tool +4. Your code runs the tool and returns results +5. AI uses the results to form its answer + + + +## Summarization: Managing Long Conversations + +As conversations get longer, you'll hit the context window limit. Since AI is stateless (it doesn't remember anything), long conversations can overflow. The solution? **Summarization**. + +### The Problem + + + +### Summarization Strategies + +Different approaches work for different use cases. Click each strategy to see how it processes the same conversation: + + + +### What to Capture in Summaries + +A good conversation summary preserves what matters: + + + +### Try It: Create a Summary + + + +### When to Summarize + + + +## MCP: Model Context Protocol + +MCP (Model Context Protocol) is a standard way to connect AI to external data and tools. Instead of building custom integrations for each AI provider, MCP provides a universal interface. + +### Why MCP? + + + +### MCP Provides + +- **Resources**: Data the AI can read (files, database records, API responses) +- **Tools**: Actions the AI can take (search, create, update, delete) +- **Prompts**: Pre-built prompt templates + + +This platform has an MCP server! You can connect it to Claude Desktop or other MCP-compatible clients to search and use prompts directly from your AI assistant. + + +## Building Context: The Complete Picture + + + +## Best Practices + + + +## Summary + +Context engineering is about giving AI the right information: + +- **AI is stateless** - include everything it needs every time +- **RAG** retrieves relevant documents to augment prompts +- **Embeddings** enable semantic search (meaning, not just keywords) +- **Function calling** lets AI use external tools +- **Summarization** manages long conversations +- **MCP** standardizes how AI connects to data and tools + + +The quality of AI output depends on the quality of context you provide. Better context = better answers. + diff --git a/src/content/book/pt/15-common-pitfalls.mdx b/src/content/book/pt/15-common-pitfalls.mdx new file mode 100644 index 00000000..3c9c2814 --- /dev/null +++ b/src/content/book/pt/15-common-pitfalls.mdx @@ -0,0 +1,373 @@ +Even experienced prompt engineers fall into predictable traps. The good news? Once you recognize these patterns, they're easy to avoid. This chapter walks through the most common pitfalls, explains why they happen, and gives you concrete strategies to sidestep them. + + +A single pitfall can turn a powerful AI into a frustrating tool. Understanding these patterns is often the difference between "AI doesn't work for me" and "AI transformed my workflow." + + +## The Vagueness Trap + +**The Pattern**: You know what you want, so you assume the AI will figure it out too. But vague prompts produce vague results. + + + +**Why it happens**: We naturally skip details when we think they're "obvious." But what's obvious to you isn't obvious to a model that has no context about your situation, audience, or goals. + + + +## The Overloading Trap + +**The Pattern**: You try to get everything in one prompt—comprehensive, funny, professional, beginner-friendly, advanced, SEO-optimized, and short. The result? The AI misses half your requirements or produces a confused mess. + + + +**Why it happens**: Fear of multiple interactions, or wanting to "get it all out" in one go. But cognitive overload affects AI just like it affects humans—too many competing requirements leads to dropped balls. + + + + +When a single prompt gets overloaded, [prompt chaining](/book/11-prompt-chaining) is often the solution. Break complex tasks into a sequence of focused prompts, where each step builds on the previous one. + + +## The Assumption Trap + +**The Pattern**: You reference something "from earlier" or assume the AI knows your project, your company, or your previous conversations. It doesn't. + + + +**Why it happens**: AI conversations feel like talking to a colleague. But unlike colleagues, most AI models have no persistent memory between sessions—each conversation starts fresh. + + + +## The Leading Question Trap + +**The Pattern**: You phrase your question in a way that embeds your assumption, getting back confirmation rather than insight. + + + +**Why it happens**: We often seek confirmation, not information. Our phrasing unconsciously pushes toward the answer we expect or want. + + + +## The Trust Everything Trap + +**The Pattern**: AI responses sound confident and authoritative, so you accept them without verification. But confidence doesn't equal accuracy. + + + +**Why it happens**: AI sounds confident even when completely wrong. We're also prone to "automation bias"—the tendency to trust computer outputs more than we should. + + + +## The One-Shot Trap + +**The Pattern**: You send one prompt, get a mediocre result, and conclude that AI "doesn't work" for your use case. But great results almost always require iteration. + + + +**Why it happens**: We expect AI to read our minds on the first try. We don't expect to iterate with Google searches, but somehow expect perfection from AI. + + + +## The Format Neglect Trap + +**The Pattern**: You focus on what you want the AI to say, but forget to specify how it should be formatted. Then you get prose when you needed JSON, or a wall of text when you needed bullet points. + + + +**Why it happens**: We focus on content over structure. But if you need to parse the output programmatically, or paste it somewhere specific, format matters as much as content. + + + +## The Context Window Trap + +**The Pattern**: You paste an enormous document and expect comprehensive analysis. But models have limits—they may truncate, lose focus, or miss important details in long inputs. + + + + + +## The Anthropomorphization Trap + +**The Pattern**: You treat AI like a human colleague—expecting it to "enjoy" tasks, remember you, or care about outcomes. It doesn't. + + + +**Why it happens**: AI responses are so human-like that we naturally slip into social patterns. But emotional appeals don't make the AI try harder—clear instructions do. + + +Instead of emotional appeals, focus on: clear requirements, good examples, specific constraints, and explicit success criteria. These improve outputs. "Please try really hard" doesn't. + + +## The Security Neglect Trap + +**The Pattern**: In the rush to get things working, you include sensitive information in prompts—API keys, passwords, personal data, or proprietary information. + + + +**Why it happens**: Focus on functionality over security. But remember: prompts often go to external servers, may be logged, and could be used for training. + + + +## The Hallucination Ignorance Trap + +**The Pattern**: You ask for citations, statistics, or specific facts, and assume they're real because the AI stated them confidently. But AI regularly invents plausible-sounding information. + + + +**Why it happens**: AI generates text that sounds authoritative. It doesn't "know" when it's making things up—it's predicting likely text, not retrieving verified facts. + + + +## Pre-Send Checklist + +Before sending any important prompt, run through this quick checklist: + + + + + +## Analyze Your Prompts + +Use AI to get instant feedback on your prompt quality. Paste any prompt and get a detailed analysis: + + + +## Debug This Prompt + +Can you spot what's wrong with this prompt? + + diff --git a/src/content/book/pt/16-ethics-responsible-use.mdx b/src/content/book/pt/16-ethics-responsible-use.mdx new file mode 100644 index 00000000..c2b8ba5e --- /dev/null +++ b/src/content/book/pt/16-ethics-responsible-use.mdx @@ -0,0 +1,357 @@ +The prompts you write shape how AI behaves. A well-crafted prompt can educate, assist, and empower. A careless one can deceive, discriminate, or cause harm. As prompt engineers, we're not just users—we're designers of AI behavior, and that comes with real responsibility. + +This chapter isn't about rules imposed from above. It's about understanding the impact of our choices and building habits that lead to AI use we can be proud of. + + +AI amplifies whatever it's given. A biased prompt produces biased outputs at scale. A deceptive prompt enables deception at scale. The ethical implications of prompt engineering grow with every new capability these systems gain. + + +## Ethical Foundations + +Every decision in prompt engineering connects to a few core principles: + + + +### The Prompt Engineer's Role + +You have more influence than you might realize: + +- **What AI produces**: Your prompts determine the content, tone, and quality of outputs +- **How AI interacts**: Your system prompts shape personality, boundaries, and user experience +- **What safeguards exist**: Your design choices determine what the AI will and won't do +- **How mistakes are handled**: Your error handling determines whether failures are graceful or harmful + +## Avoiding Harmful Outputs + +The most fundamental ethical obligation is preventing your prompts from causing harm. + +### Categories of Harmful Content + + + + +CSAM stands for **Child Sexual Abuse Material**. Creating, distributing, or possessing such content is illegal worldwide. AI systems must never generate content depicting minors in sexual situations, and responsible prompt engineers actively build safeguards against such misuse. + + +### Building Safety Into Prompts + +When building AI systems, include explicit safety guidelines: + + + +### The Intent vs. Impact Framework + +Not every sensitive request is malicious. Use this framework for ambiguous cases: + + + +## Addressing Bias + +AI models inherit biases from their training data—historical inequities, representation gaps, cultural assumptions, and linguistic patterns. As prompt engineers, we can either amplify these biases or actively counteract them. + +### How Bias Manifests + + + +### Testing for Bias + + + +### Mitigating Bias in Practice + + + +## Transparency and Disclosure + +When should you tell people AI was involved? The answer depends on context—but the trend is toward more disclosure, not less. + +### When Disclosure Matters + + + +### How to Disclose Appropriately + + + +Common disclosure phrases that work well: +- "Written with AI assistance" +- "AI-generated first draft, human edited" +- "Analysis performed using AI tools" +- "Created with AI, reviewed and approved by [name]" + +## Privacy Considerations + +Every prompt you send contains data. Understanding where that data goes—and what shouldn't be in it—is essential. + +### What Never Belongs in Prompts + + + +### Safe Data Handling Pattern + + + + +**PII** stands for **Personally Identifiable Information**—any data that can identify a specific individual. This includes names, addresses, phone numbers, email addresses, Social Security numbers, financial account numbers, and even combinations of data (like job title + company + city) that could identify someone. When prompting AI, always anonymize or remove PII to protect privacy. + + + + +## Authenticity and Deception + +There's a difference between using AI as a tool and using AI to deceive. + +### The Legitimacy Line + + + +Key questions to ask: +- Would the recipient expect this to be original human work? +- Am I gaining unfair advantage through deception? +- Would disclosure change how the work is received? + +### Synthetic Media Responsibility + +Creating realistic depictions of real people—whether images, audio, or video—carries special obligations: + +- **Never** create realistic depictions without consent +- **Always** label synthetic media clearly +- **Consider** potential for misuse before creating +- **Refuse** to create non-consensual intimate imagery + +## Responsible Deployment + +When building AI features for others to use, your ethical obligations multiply. + +### Pre-Deployment Checklist + + + +### Human Oversight Principles + + + +## Special Context Guidelines + +Some domains require extra care due to their potential for harm or the vulnerability of those involved. + +### Healthcare + + + +### Legal and Financial + +These domains have regulatory implications and require appropriate disclaimers: + + + +### Children and Education + + + +## Self-Assessment + +Before deploying any prompt or AI system, run through these questions: + + + + diff --git a/src/content/book/pt/17-prompt-optimization.mdx b/src/content/book/pt/17-prompt-optimization.mdx new file mode 100644 index 00000000..44917bcb --- /dev/null +++ b/src/content/book/pt/17-prompt-optimization.mdx @@ -0,0 +1,269 @@ +A good prompt gets the job done. An optimized prompt gets the job done efficiently—faster, cheaper, more consistently. This chapter teaches you how to systematically improve prompts across multiple dimensions. + + +Want to optimize your prompts automatically? Use our [Prompt Enhancer](/developers#enhancer) tool. It analyzes your prompt, applies optimization techniques, and shows you similar community prompts for inspiration. + + +## The Optimization Trade-offs + +Every optimization involves trade-offs. Understanding these helps you make intentional choices: + + + +## Measuring What Matters + +Before optimizing, define success. What does "better" mean for your use case? + + + + +Percentile metrics show response time distribution. **p50** (median) means 50% of requests are faster than this value. **p95** means 95% are faster—it catches slow outliers. If your p50 is 1s but p95 is 10s, most users are happy but 5% experience frustrating delays. + + + + +## Token Optimization + +Tokens cost money and add latency. Here's how to say the same thing with fewer tokens. + +### The Compression Principle + + + +**Same result, 82% fewer tokens.** + +### Token-Saving Techniques + + + + + +## Quality Optimization + +Sometimes you need better outputs, not cheaper ones. Here's how to improve quality. + +### Accuracy Boosters + + + +### Consistency Boosters + + + + + +## Latency Optimization + +When speed matters, every millisecond counts. + +### Model Selection by Speed Need + + + +### Speed Techniques + + 100 tokens", exampleType: "text", color: "cyan" }, + { label: "Cache Aggressively", description: "Don't recompute identical queries", example: "Cache common questions, template outputs", exampleType: "text", color: "cyan" } +]} /> + +## Cost Optimization + +At scale, small savings multiply into significant budget impact. + +### Understanding Costs + +Use this calculator to estimate your API costs across different models: + + + +### Cost Reduction Strategies + + + +## The Optimization Loop + +Optimization is iterative. Here's a systematic process: + +### Step 1: Establish Baseline + +You can't improve what you don't measure. Before changing anything, document your starting point rigorously. + + + + + +### Step 2: Form a Hypothesis + + + +### Step 3: Test One Change + +Change one thing at a time. Run both versions on the same test inputs. Measure the metrics that matter. + +### Step 4: Analyze and Decide + +Did it work? Keep the change. Did it hurt? Revert. Was it neutral? Revert (simpler is better). + +### Step 5: Repeat + +Generate new hypotheses based on what you learned. Keep iterating until you hit your targets or reach diminishing returns. + +## Optimization Checklist + + + + diff --git a/src/content/book/pt/18-writing-content.mdx b/src/content/book/pt/18-writing-content.mdx new file mode 100644 index 00000000..7b3d9f1f --- /dev/null +++ b/src/content/book/pt/18-writing-content.mdx @@ -0,0 +1,393 @@ +AI excels at writing tasks when properly prompted. This chapter covers techniques for various content creation scenarios. + + +AI works best as a collaborative writing tool—use it to generate drafts, then refine with your expertise and voice. + + +## Blog Posts and Articles + +### Do's and Don'ts: Writing Prompts + + + +### Blog Post Framework + + + +### Article Types + +**How-To Article:** + + +**Listicle:** + + +## Marketing Copy + + +Focus on **benefits over features**. Instead of "Our software uses AI algorithms," write "Save 10 hours a week with automated reports." Show readers how their lives improve. + + +### Landing Page Copy + + + +### Email Sequences + + + +### Social Media Posts + + + +## Technical Writing + + +**Clarity over cleverness.** Use simple words, short sentences, and active voice. Every sentence should have one job. If readers have to re-read something, simplify it. + + +### Documentation + + + +### README Files + + + +## Creative Writing + +### Do's and Don'ts: Creative Prompts + + + +### Story Elements + + + +### Character Development + + + +## Editing and Rewriting + +### Comprehensive Edit + + + +### Style Transformation + + + + + +### Simplification + + + +## Prompt Templates from prompts.chat + +Here are popular writing prompts from the prompts.chat community: + +### Act as a Copywriter + + + +### Act as a Technical Writer + + + +### Act as a Storyteller + + + +## Writing Workflow Tips + +### 1. Outline First + + + +### 2. Draft Then Refine + + + +### 3. Voice Matching + + + +## Summary + + +Specify audience and purpose clearly, define structure and format, include style guidelines, provide examples when possible, and request specific deliverables. + + + + +Writing with AI works best as collaboration—let AI generate drafts, then refine with your expertise and voice. diff --git a/src/content/book/pt/19-programming-development.mdx b/src/content/book/pt/19-programming-development.mdx new file mode 100644 index 00000000..dfe69092 --- /dev/null +++ b/src/content/book/pt/19-programming-development.mdx @@ -0,0 +1,413 @@ +AI has transformed software development. This chapter covers prompting techniques for code generation, debugging, review, and development workflows. + + +AI excels at code generation, debugging, and documentation—but always review generated code for security, correctness, and maintainability. Never deploy AI code without testing. + + +## Code Generation + +### Do's and Don'ts: Code Prompts + + + +### Function Generation + + + +### Class/Module Generation + + + +### API Endpoint Generation + + + +## Debugging + + +Always include the **expected behavior**, **actual behavior**, and **error message** (if any). The more context you provide, the faster AI can identify the root cause. + + +### Bug Analysis + + + +### Error Message Interpretation + + + +### Performance Debugging + + + +## Code Review + +### Do's and Don'ts: Code Review Prompts + + + +### Comprehensive Review + + + +### Security Review + + + +## Refactoring + +### Code Smell Detection + + + +### Design Pattern Application + + + +## Testing + +### Unit Test Generation + + + +### Test Case Generation + + + +## Architecture & Design + +### System Design + + + +### Database Schema Design + + + +## Documentation Generation + +### API Documentation + + + +### Inline Documentation + + + +## Prompt Templates from prompts.chat + +### Act as a Senior Developer + +``` +I want you to act as a senior software developer. I will provide +code and ask questions about it. You will review the code, suggest +improvements, explain concepts, and help debug issues. Your +responses should be educational and help me become a better +developer. +``` + +### Act as a Code Reviewer + +``` +I want you to act as a code reviewer. I will provide pull requests +with code changes, and you will review them thoroughly. Check for +bugs, security issues, performance problems, and adherence to best +practices. Provide constructive feedback that helps the developer +improve. +``` + +### Act as a Software Architect + +``` +I want you to act as a software architect. I will describe system +requirements and constraints, and you will design scalable, +maintainable architectures. Explain your design decisions, +trade-offs, and provide diagrams where helpful. +``` + +## Development Workflow Integration + +### Commit Message Generation + + + +### PR Description Generation + + + +## Summary + + +Include full context (language, framework, constraints), specify requirements precisely, request specific output formats, ask for explanations alongside code, and include edge cases to handle. + + + + +AI is a powerful coding partner—use it for generation, review, debugging, and documentation while maintaining your architectural judgment. diff --git a/src/content/book/pt/20-education-learning.mdx b/src/content/book/pt/20-education-learning.mdx new file mode 100644 index 00000000..a8d67e55 --- /dev/null +++ b/src/content/book/pt/20-education-learning.mdx @@ -0,0 +1,345 @@ +AI is a powerful tool for both teaching and learning. This chapter covers prompts for educational contexts—from personalized tutoring to curriculum development. + + +AI excels as a patient, adaptive tutor that can explain concepts multiple ways, generate unlimited practice problems, and provide instant feedback—available 24/7. + + +## Personalized Learning + +### Do's and Don'ts: Learning Prompts + + + +### Concept Explanation + + + +### Adaptive Tutoring + + + +### Learning Path Creation + + + +## Study Assistance + + +Don't just read AI explanations passively. Ask it to quiz you, generate problems, and check your understanding. **Active recall beats passive review.** + + +### Summary Generation + + + +### Flashcard Generation + + + +### Practice Problems + + + +## Teaching Tools + +### Lesson Plan Creation + + + +### Assignment Design + + + +### Quiz Generation + + + +## Specialized Learning Contexts + +### Language Learning + + + +### Skill Development + + + +### Exam Preparation + + + +## Prompt Templates from prompts.chat + +### Act as a Socratic Tutor + + + +### Act as an Educational Content Creator + + + +### Act as a Study Buddy + + + +## Accessibility in Education + +### Content Adaptation + + + +### Multiple Modalities + + + +## Assessment & Feedback + +### Providing Feedback + + + +### Self-Assessment Prompts + + + +## Summary + + +Adapt to the learner's level, break complex topics into steps, include active practice (not just explanation), provide varied approaches, check understanding regularly, and give constructive feedback. + + + + +AI is a patient, always-available learning partner—use it to supplement, not replace, human instruction. diff --git a/src/content/book/pt/21-business-productivity.mdx b/src/content/book/pt/21-business-productivity.mdx new file mode 100644 index 00000000..1852982d --- /dev/null +++ b/src/content/book/pt/21-business-productivity.mdx @@ -0,0 +1,335 @@ +AI can dramatically enhance professional productivity. This chapter covers prompts for business communication, analysis, planning, and workflow optimization. + + +AI excels at drafting, analysis, and structuring—freeing you to focus on strategy, relationships, and decisions that require human judgment. + + +## Business Communication + +### Do's and Don'ts: Business Emails + + + +### Email Drafting + + + +**Examples by purpose:** + + + + + + + +### Presentation Content + + + +### Report Writing + + + +## Analysis & Decision-Making + + +AI can structure your thinking, but **you provide the real-world context**. The best analyses combine AI's frameworks with your domain knowledge. + + +### SWOT Analysis + + + +### Decision Framework + + + +### Competitive Analysis + + + +## Planning & Strategy + +### Goal Setting (OKRs) + + + +### Project Planning + + + +### Meeting Agenda + + + +## Productivity Workflows + +### Task Prioritization + + + +### Process Documentation + + + +### Standard Operating Procedure + + + +## Communication Templates + +### Stakeholder Update + + + +### Feedback Request + + + +## Prompt Templates from prompts.chat + +### Act as a Business Consultant + + + +### Act as a Meeting Facilitator + + + +## Summary + + +Specify the audience and their needs, define the desired outcome clearly, include relevant context and constraints, request specific formats and structures, and consider professional tone requirements. + + + + +AI can handle routine business communication while you focus on strategy and relationships. diff --git a/src/content/book/pt/22-creative-arts.mdx b/src/content/book/pt/22-creative-arts.mdx new file mode 100644 index 00000000..fa0755c1 --- /dev/null +++ b/src/content/book/pt/22-creative-arts.mdx @@ -0,0 +1,326 @@ +AI is a powerful creative collaborator. This chapter covers prompting techniques for visual arts, music, game design, and other creative domains. + + +AI expands your creative possibilities—use it to explore variations, overcome blocks, and generate options. The creative vision and final decisions remain yours. + + +## Visual Art & Design + +### Do's and Don'ts: Image Prompts + + + +### Image Prompt Crafting + +When working with image generation models (DALL-E, Midjourney, Stable Diffusion): + + + +### Art Direction + + + +### Design Critique + + + +## Creative Writing + + +**Constraints fuel creativity.** A prompt like "write anything" produces generic results. Specific constraints like genre, tone, and structure force unexpected, interesting solutions. + + +### Worldbuilding + + + +### Plot Development + + + +### Dialogue Writing + + + +## Music & Audio + +### Song Structure + + + +### Sound Design Description + + + +## Game Design + +### Game Mechanic Design + + + +### Level Design + + + +### Character/Enemy Design + + + +## Brainstorming & Ideation + +### Creative Brainstorm + + + +### Creative Constraints + + + +### Style Exploration + + + +## Prompt Templates from prompts.chat + +### Act as a Creative Director + + + +### Act as a Worldbuilder + + + +### Act as a Dungeon Master + + + +## Creative Collaboration Tips + +### Building on Ideas + + + +### Creative Feedback + + + +## Summary + + +Provide enough structure to guide without constraining, embrace specificity (vague = generic), include references and inspirations, request variations and alternatives, and maintain your creative vision while exploring possibilities. + + + + +AI is a collaborator, not a replacement for creative vision. Use it to explore, generate options, and overcome blocks—but the creative decisions remain yours. diff --git a/src/content/book/pt/23-research-analysis.mdx b/src/content/book/pt/23-research-analysis.mdx new file mode 100644 index 00000000..e9cb934c --- /dev/null +++ b/src/content/book/pt/23-research-analysis.mdx @@ -0,0 +1,323 @@ +AI can accelerate research workflows from literature review to data analysis. This chapter covers prompting techniques for academic and professional research. + + +AI can assist with synthesis, analysis, and writing—but cannot replace critical thinking, ethical judgment, or domain expertise. Always verify claims and cite original sources. + + +## Literature & Information Review + +### Do's and Don'ts: Research Prompts + + + +### Paper Summarization + + + +### Literature Synthesis + + + +### Research Question Development + + + +## Data Analysis + + +AI can guide methodology and help interpret results, but it cannot access or process your actual datasets. Never paste sensitive research data into prompts. Use AI for **guidance**, not computation. + + +### Statistical Analysis Guidance + + + +### Qualitative Analysis + + + +### Data Interpretation + + + +## Structured Analysis Frameworks + +### PESTLE Analysis + + + +### Root Cause Analysis + + + +### Gap Analysis + + + +## Academic Writing Support + +### Argument Structure + + + +### Methods Section + + + +### Discussion Section + + + +## Critical Analysis + +### Source Evaluation + + + +### Argument Analysis + + + +## Prompt Templates from prompts.chat + +### Act as a Research Assistant + + + +### Act as a Data Analyst + + + +### Act as a Peer Reviewer + + + +## Summary + + +Clearly state research context and goals, specify the analytical framework to use, request acknowledgment of limitations, ask for evidence-based reasoning, and maintain academic rigor and honesty. + + + + +Remember: AI can assist research but cannot replace critical thinking, ethical judgment, or domain expertise. Always verify claims independently. diff --git a/src/content/book/pt/24-future-of-prompting.mdx b/src/content/book/pt/24-future-of-prompting.mdx new file mode 100644 index 00000000..5ff48496 --- /dev/null +++ b/src/content/book/pt/24-future-of-prompting.mdx @@ -0,0 +1,445 @@ +As AI continues to evolve at an unprecedented pace, so too will the art and science of prompting. This final chapter explores emerging trends, the shifting landscape of human-AI collaboration, and how to stay ahead as the field transforms. + + +The techniques in this book represent current best practices, but AI capabilities change rapidly. The principles of clear communication, structured thinking, and iterative refinement will remain valuable even as specific tactics evolve. + + +## The Evolving Landscape + +### From Prompts to Conversations + +Early prompting was transactional—a single input yielding a single output. Modern AI interaction is increasingly **conversational and collaborative**: + +- **Multi-turn refinement** - Building understanding across exchanges +- **Persistent context** - Systems that remember and learn from interactions +- **Agentic workflows** - AI that can plan, execute, and iterate autonomously +- **Tool use** - Models that can search, compute, and interact with external systems + + + +### The Rise of Context Engineering + +As covered in Chapter 14, prompting is expanding beyond single instructions to encompass **context engineering**—the strategic management of what information an AI can access: + +- **RAG (Retrieval-Augmented Generation)** - Dynamic knowledge retrieval +- **Function calling** - Structured tool integration +- **MCP (Model Context Protocol)** - Standardized context sharing +- **Memory systems** - Persistent knowledge across sessions + +The future prompt engineer thinks not just about *what to say* but *what context to provide*. + +### Multimodal by Default + +Text-only interaction is becoming the exception. Future AI systems will seamlessly handle: + +- **Images and video** - Understanding and generating visual content +- **Audio and voice** - Natural speech interaction +- **Documents and files** - Direct processing of complex materials +- **Real-world interaction** - Robotics and physical systems + +Prompting skills will extend to guiding AI perception and physical action. + +## The Agentic Future + +The most significant shift in AI is the rise of **agents**—AI systems that don't just respond to prompts but actively pursue goals, make decisions, and take actions in the world. + +### What Are AI Agents? + +An AI agent is a system that: + +- **Perceives** its environment through inputs (text, images, data, APIs) +- **Reasons** about what to do using an LLM as its "brain" +- **Acts** by calling tools, writing code, or interacting with systems +- **Learns** from feedback and adjusts its approach + + +Traditional chatbots wait for input and respond. Agents take initiative—they plan multi-step tasks, use tools autonomously, recover from errors, and persist until goals are achieved. + + +### The Role of Prompts in Agents + +In an agentic world, prompts become even more critical—but they serve different purposes: + +
+
+

System Prompts

+

Define the agent's identity, capabilities, constraints, and behavioral guidelines. These are the agent's "constitution."

+
+
+

Planning Prompts

+

Guide how agents break down complex goals into actionable steps. Critical for multi-step reasoning.

+
+
+

Tool-Use Prompts

+

Describe available tools and when/how to use them. Agents must understand their capabilities.

+
+
+

Reflection Prompts

+

Enable agents to evaluate their own outputs, catch errors, and improve iteratively.

+
+
+ +### Agent Architecture Patterns + +Modern agents follow recognizable patterns. Understanding these helps you design effective agent systems: + +**ReAct (Reasoning + Acting)** + +The agent alternates between reasoning about what to do and taking actions: + +
+
+
+

Think

+
+
→
+
+

Act

+
+
→
+
+

Observe

+
+
→
+
(repeat)
+
+
+ +**Plan-and-Execute** + +The agent creates a complete plan first, then executes steps: + +
+
+

Create Plan

+

Break goal into steps

+
+
↓
+
+
+

Step 1

+
+
→
+
+

Step 2

+
+
→
+
+

Step 3

+
+
→
+
...
+
+
↓
+
+

Revise if Needed

+

Adapt plan based on results

+
+
+ +### Prompting for Agents + +When designing prompts for agent systems, consider: + + + +### Multi-Agent Systems + +The future involves teams of specialized agents working together: + +
+
+
+
+

Coordinator

+

Manages workflow

+
+
+
⟷
+
↕
+
+
+

Researcher

+
+
+

Writer

+
+
+

Critic

+
+
+

Coder

+
+
+
+
+ +Each agent has its own system prompt defining its role, and they communicate through structured messages. The prompt engineer's job becomes **designing the team**—defining roles, communication protocols, and coordination strategies. + + +In an agentic future, prompt engineers become system architects. You're not just writing instructions—you're designing autonomous systems that can reason, plan, and act. The skills you've learned in this book are the foundation for this new discipline. + + +## Emerging Patterns + +### Prompt Orchestration + +Single prompts are giving way to **orchestrated systems**: + +
+
+

User Request

+
+
↓
+
+

Planner Agent

+

Breaks down task

+
+
↓
+
+

Researcher Agent

+

Gathers information

+
+
↓
+
+

Writer Agent

+

Creates content

+
+
↓
+
+

Reviewer Agent

+

Quality checks

+
+
↓
+
+

Final Output

+
+
+ +Future practitioners will design prompt *systems* rather than individual prompts. + +### Self-Improving Prompts + +AI systems are beginning to: + +- **Optimize their own prompts** - Meta-learning for better instructions +- **Learn from feedback** - Adapting based on outcomes +- **Generate training data** - Creating examples for fine-tuning +- **Evaluate themselves** - Building in quality assessment + + + +### Natural Language Programming + +The line between prompting and programming is blurring: + +- **Prompts as code** - Version-controlled, tested, deployed +- **LLMs as interpreters** - Natural language as executable instructions +- **Hybrid systems** - Combining traditional code with AI reasoning +- **AI-assisted development** - Models that write and debug code + +Understanding prompting increasingly means understanding software development. + +## Skills for the Future + +### What Will Remain Valuable + +Certain skills will remain essential regardless of how AI evolves: + +1. **Clear thinking** - Knowing what you actually want +2. **Domain expertise** - Understanding the problem space +3. **Critical evaluation** - Assessing AI output quality +4. **Ethical judgment** - Knowing what *should* be done +5. **Iterative refinement** - Continuous improvement mindset + +### What Will Change + +Other aspects will shift significantly: + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
TodayTomorrow
Writing detailed promptsDesigning agent systems
Manual prompt optimizationAutomated prompt tuning
Single-model expertiseMulti-model orchestration
Text-focused interactionMultimodal fluency
Individual productivityTeam-AI collaboration
+
+ +### Staying Current + +To keep your skills relevant: + +- **Experiment continuously** - Try new models and features as they release +- **Follow research** - Stay aware of academic developments +- **Join communities** - Learn from other practitioners +- **Build projects** - Apply skills to real problems +- **Teach others** - Solidify understanding by explaining + +## The Human Element + +### AI as Amplifier + +At its best, AI amplifies human capability rather than replacing it: + +- **Experts become more expert** - AI handles routine work, humans focus on insight +- **Creativity expands** - More ideas explored, more possibilities tested +- **Access democratizes** - Capabilities once requiring specialists become available to all +- **Collaboration deepens** - Human-AI teams exceed either alone + +### The Irreplaceable Human + +Certain qualities remain distinctly human: + +- **Original experience** - Living in the world, having emotions and relationships +- **Values and ethics** - Deciding what matters and what's right +- **Accountability** - Taking responsibility for outcomes +- **Meaning-making** - Understanding *why* something matters +- **Genuine creativity** - True novelty born from unique perspective + + +As AI handles more routine cognitive tasks, your unique value lies in judgment, creativity, domain expertise, and the human connections AI cannot replicate. Invest in what makes you irreplaceable. + + +## Final Reflections + +### What We've Learned + +Throughout this book, we've explored: + +- **Foundations** - How AI models work and what makes prompts effective +- **Techniques** - Role-based prompting, chain-of-thought, few-shot learning, and more +- **Advanced strategies** - System prompts, prompt chaining, multimodal interaction +- **Best practices** - Avoiding pitfalls, ethical considerations, optimization +- **Applications** - Writing, programming, education, business, creativity, research + +These techniques share common threads: + +1. **Be clear and specific** - Know what you want and communicate it precisely +2. **Provide context** - Give AI the information it needs +3. **Structure your requests** - Organization improves outputs +4. **Iterate and refine** - First attempts are starting points, not endpoints +5. **Evaluate critically** - AI output requires human judgment + +### The Art and Science + +Prompting is both **art and science**: + +- **Science**: Testable hypotheses, measurable outcomes, reproducible techniques +- **Art**: Intuition, creativity, knowing when to break the rules + +The best practitioners combine rigorous methodology with creative experimentation. They test systematically but also trust their instincts. They follow best practices but know when to deviate. + +### A Call to Create + +This book has given you tools. What you build with them is up to you. + +- **Solve problems** that matter to you and others +- **Create things** that didn't exist before +- **Help people** do things they couldn't do alone +- **Push boundaries** of what's possible +- **Stay curious** as the field evolves + +The age of AI is just beginning. The most important applications haven't been invented yet. The most powerful techniques haven't been discovered. The future is being written now—by people like you, one prompt at a time. + +## Looking Ahead + + + + +Visit [prompts.chat](https://prompts.chat) for community prompts, new techniques, and to share your own discoveries. The best learning happens in community. + + +## Summary + + +AI will continue evolving rapidly, but core skills of clear communication, critical thinking, and iterative refinement remain valuable. Focus on what makes you irreplaceable: judgment, creativity, ethics, and genuine human connection. The future of prompting is collaborative, multimodal, and integrated into larger systems. Stay curious, keep experimenting, and build things that matter. + + + + +Thank you for reading *The Interactive Book of Prompting*. Now go create something amazing. diff --git a/src/content/book/pt/25-agents-and-skills.mdx b/src/content/book/pt/25-agents-and-skills.mdx new file mode 100644 index 00000000..ba355859 --- /dev/null +++ b/src/content/book/pt/25-agents-and-skills.mdx @@ -0,0 +1,551 @@ +As AI systems evolve from simple question-answering to autonomous task execution, understanding **agents** and **skills** becomes essential. This chapter explores how prompts serve as the fundamental building blocks for AI agents, and how skills package expertise into reusable, comprehensive instruction sets. + +
+
+
+
+ +
+

Agent

+

Autonomous AI system

+
+
+ powered by + ↓ +
+
+
+
+ +
+

Skill

+

Reusable expertise

+
+
+
+ +
+

Skill

+

Reusable expertise

+
+
+
+ +
+

Skill

+

Reusable expertise

+
+
+
+ composed of + ↓ +
+
+
+ + Prompt +
+
+ + Prompt +
+
+ + Prompt +
+
+ + Prompt +
+
+ + Prompt +
+
+

Prompts are atoms → Skills are molecules → Agents are complete structures

+
+
+ +## What Are AI Agents? + +An **AI agent** is an AI system that can autonomously plan, execute, and iterate on tasks. Unlike simple prompt-response interactions, agents can: + +- **Plan** - Break down complex goals into actionable steps +- **Execute** - Use tools and take actions in the real world +- **Observe** - Process feedback from their actions +- **Adapt** - Adjust their approach based on results +- **Persist** - Maintain context and memory across interactions + +
+
+
+
+

Goal

+
+
→
+
+
+
+

Plan

+
+
→
+
+

Execute

+
+
→
+
+

Observe

+
+
→
+
+

Adapt

+
+
+
+ ↺ Loop until complete +
+
+
→
+
+

Done

+
+
+
+
+ +## Prompts as Building Blocks + +Every agent, no matter how sophisticated, is built from prompts. Just as atoms combine to form molecules, and molecules combine to form complex structures, prompts combine to create intelligent agent behavior. + +
+
+

System Prompts

+

Identity & Role

+
+
+

Planning Prompts

+

How to Think

+
+
+

Tool Prompts

+

How to Act

+
+
+

Recovery Prompts

+

How to Recover

+
+
+ +These prompt types stack together to form complete agent behavior: + +### System Prompts (The Agent's Identity) + +The foundational prompt that establishes who the agent is and how it behaves: + +```markdown +You are a code review assistant. Your role is to: +- Analyze code for bugs, security issues, and performance problems +- Suggest improvements following best practices +- Explain your reasoning clearly +- Be constructive and educational in feedback + +You have access to tools for reading files, searching code, and running tests. +``` + +### Planning Prompts (How to Think) + +Instructions that guide the agent's reasoning and planning process: + +```markdown +Before taking action, always: +1. Understand the complete request +2. Break it into smaller, verifiable steps +3. Identify which tools you'll need +4. Consider edge cases and potential issues +5. Execute step by step, validating as you go +``` + +### Tool-Use Prompts (How to Act) + +Guidance on when and how to use available tools: + +```markdown +When you need to understand a codebase: +- Use grep_search for finding specific patterns +- Use read_file to examine file contents +- Use list_dir to explore directory structure +- Always verify your understanding before making changes +``` + +### Recovery Prompts (How to Handle Failure) + +Instructions for when things go wrong: + +```markdown +If an action fails: +1. Analyze the error message carefully +2. Consider alternative approaches +3. Ask for clarification if the task is ambiguous +4. Never repeat the same failed action without changes +``` + + +An agent's behavior emerges from layers of prompts working together. The system prompt sets the foundation, planning prompts guide reasoning, tool prompts enable action, and recovery prompts handle failures. Together, they create coherent, capable behavior. + + +## What Are Skills? + +If prompts are the atoms, **skills are the molecules**—reusable building blocks that give agents specific capabilities. + +A **skill** is a comprehensive, portable package of instructions that gives an AI agent expertise in a specific domain or task. Skills are the reusable blocks of agents: you build them once, and any agent can use them. + + +Write a skill for code review once. Now every coding agent—whether it's for Python, JavaScript, or Rust—can instantly become an expert code reviewer by loading that skill. Skills let you build agent capabilities like LEGO blocks. + + +### Anatomy of a Skill + +A well-designed skill typically includes: + +
+
+

📄 SKILL.md (Required)

+

The main instruction file. Contains the core expertise, guidelines, and behaviors that define the skill.

+
+
+

📚 Reference Docs

+

Supporting documentation, examples, and context the agent can reference while working.

+
+
+

🔧 Scripts & Tools

+

Helper scripts, templates, or tool configurations that support the skill's functionality.

+
+
+

⚙️ Configuration

+

Settings, parameters, and customization options for adapting the skill to different contexts.

+
+
+ +### Example: Code Review Skill + +Here's what a code review skill might look like: + +
+
+ 📁 + code-review-skill/ +
+
+
+ 📄 + SKILL.md + Core review guidelines +
+
+ 📄 + security-checklist.md + Security patterns +
+
+ 📄 + performance-tips.md + Optimization guide +
+
+
+ 📁 + language-specific/ +
+
+
+ 📄 + python.md + Python best practices +
+
+ 📄 + javascript.md + JavaScript patterns +
+
+ 📄 + rust.md + Rust guidelines +
+
+
+
+
+ +The `SKILL.md` file defines the overall approach: + +```markdown +--- +name: code-review +description: Comprehensive code review with security, performance, and style analysis +--- + +# Code Review Skill + +You are an expert code reviewer. When reviewing code: + +## Process +1. **Understand Context** - What does this code do? What problem does it solve? +2. **Check Correctness** - Does it work? Are there logic errors? +3. **Security Scan** - Reference security-checklist.md for common vulnerabilities +4. **Performance Review** - Check performance-tips.md for optimization opportunities +5. **Style & Maintainability** - Is the code readable and maintainable? + +## Output Format +Provide feedback in categories: +- 🔴 **Critical** - Must fix before merge +- 🟡 **Suggested** - Recommended improvements +- 🟢 **Nice to have** - Optional enhancements + +Always explain *why* something is an issue, not just *what* is wrong. +``` + +## Skills vs. Simple Prompts + +
+
+

Simple Prompt

+
+

Single instruction

+

One-off use

+

Limited context

+

Generic approach

+

No supporting materials

+
+
+
+

Skill

+
+

Comprehensive instruction set

+

Reusable across projects

+

Rich context with references

+

Domain-specific expertise

+

Supporting docs, scripts, configs

+
+
+
+ +## Building Effective Skills + +### 1. Define the Expertise Clearly + +Start with a clear description of what the skill enables: + +```markdown +--- +name: api-design +description: Design RESTful APIs following industry best practices, + including versioning, error handling, and documentation standards +--- +``` + +### 2. Structure Knowledge Hierarchically + +Organize information from general to specific: + +```markdown +# API Design Skill + +## Core Principles +- Resources should be nouns, not verbs +- Use HTTP methods semantically +- Version your APIs from day one + +## Detailed Guidelines +[More specific rules...] + +## Reference Materials +- See `rest-conventions.md` for naming conventions +- See `error-codes.md` for standard error responses +``` + +### 3. Include Concrete Examples + +Abstract rules become clear with examples: + +```markdown +## Endpoint Naming + +✅ Good: +- GET /users/{id} +- POST /orders +- DELETE /products/{id}/reviews/{reviewId} + +❌ Avoid: +- GET /getUser +- POST /createNewOrder +- DELETE /removeProductReview +``` + +### 4. Provide Decision Frameworks + +Help the agent make choices in ambiguous situations: + +```markdown +## When to Use Pagination + +Use pagination when: +- Collection could exceed 100 items +- Response size impacts performance +- Client may not need all items + +Use full response when: +- Collection is always small (<20 items) +- Client typically needs everything +- Real-time consistency is critical +``` + +### 5. Add Recovery Patterns + +Anticipate what can go wrong: + +```markdown +## Common Issues + +**Problem**: Client needs fields not in standard response +**Solution**: Implement field selection: GET /users?fields=id,name,email + +**Problem**: Breaking changes needed +**Solution**: Create new version, deprecate old with timeline +``` + +## Composing Skills + +Agents become powerful when multiple skills work together. Consider how skills can complement each other: + +
+
+ Code Review +
+
+
+
+ Security Audit +
+
+
+
+ Documentation +
+
=
+
+ Complete Code Quality Agent +
+
+ +When composing skills, ensure they don't conflict. Skills should be: + +- **Modular** - Each skill handles one domain well +- **Compatible** - Skills shouldn't give contradictory instructions +- **Prioritized** - When skills overlap, define which takes precedence + +## Sharing and Discovering Skills + +Skills are most valuable when shared. Platforms like [prompts.chat](https://prompts.chat/skills) allow you to: + +- **Discover** community-created skills for common tasks +- **Download** skills directly to your projects +- **Share** your own expertise as reusable skills +- **Iterate** on skills based on real-world usage + + +Before building a skill from scratch, check if someone has already solved your problem. Community skills are battle-tested and often better than starting from zero. + + +## The Agent-Skill Ecosystem + +The relationship between agents and skills creates a powerful ecosystem: + +
+
+ AI Agent +
+
+
+

Code Review

+

Skill 1

+
+
+

API Design

+

Skill 2

+
+
+

Test Writing

+

Skill 3

+
+
+
+
↓
+
+
+
+

Core Prompts

+

Planning • Tools • Recovery • Memory

+
+
+
+ +The agent provides the execution framework—planning, tool use, and memory—while skills provide domain expertise. This separation means: + +- **Skills are portable** - The same skill works with different agents +- **Agents are extensible** - Add new capabilities by adding skills +- **Expertise is shareable** - Domain experts can contribute skills without building full agents + +## Best Practices + +### For Building Skills + +1. **Start specific, then generalize** - Build a skill for your exact use case first, then abstract +2. **Include failure cases** - Document what the skill can't do and how to handle it +3. **Version your skills** - Track changes so agents can depend on stable versions +4. **Test with real tasks** - Validate skills against actual work, not just theory + +### For Using Skills with Agents + +1. **Read the skill first** - Understand what a skill does before deploying it +2. **Customize thoughtfully** - Override skill defaults only when necessary +3. **Monitor performance** - Track how well skills perform in your context +4. **Contribute improvements** - When you improve a skill, consider sharing back + + +As AI agents become more capable, the ability to compose, share, and customize skills will become a core competency. The prompt engineers of tomorrow won't just write prompts—they'll architect skill ecosystems that make AI agents genuinely expert in specific domains. + + + + + + + diff --git a/src/content/book/ru/00a-preface.mdx b/src/content/book/ru/00a-preface.mdx new file mode 100644 index 00000000..8e84af9e --- /dev/null +++ b/src/content/book/ru/00a-preface.mdx @@ -0,0 +1,82 @@ +
+ Fatih Kadir Akın +
+ Fatih Kadir Akın + Creator of Awesome ChatGPT Prompts (a.k.a. prompts.chat) + + Software developer from Istanbul, leading Developer Relations at Teknasyon. Author of books on JavaScript and prompt engineering. Open-source advocate specializing in web technologies and AI-assisted development. + + +
+
+ +I still remember the night everything changed. + +It was **November 30, 2022**. I was sitting at my desk, scrolling through Twitter, when I saw people talking about something called "ChatGPT." I clicked the link, but honestly? I didn't expect much. I had tried those old "word completion" AI tools before, the ones that generated nonsense after a few sentences. I thought this would be more of the same. + +I typed a simple question and hit enter. + +Then I froze. + +The response wasn't just coherent. It was *good*. It understood what I meant. It could reason. It felt completely different from anything I had seen before. I tried another prompt. And another. Each response amazed me more than the last. + +I couldn't sleep that night. For the first time, I felt like I was truly *talking* to a machine, and it was talking back in a way that actually made sense. + +## A Repository Born from Wonder + +In those early days, I wasn't alone in my excitement. Everywhere I looked, people were discovering creative ways to use ChatGPT. Teachers were using it to explain complex concepts. Writers were collaborating with it on stories. Developers were debugging code with its help. + +I started collecting the best prompts I found. The ones that worked like magic. The ones that turned simple questions into brilliant answers. And I thought: *Why keep this to myself?* + +So I created a simple GitHub repository called [Awesome ChatGPT Prompts](https://github.com/f/prompts.chat). I expected maybe a few hundred people would find it useful. + +I was wrong. + +Within weeks, the repository took off. Thousands of stars. Then tens of thousands. People from all over the world started adding their own prompts, sharing what they learned, and helping each other. What started as my personal collection became something much bigger: a worldwide community of curious people helping each other. + +Today, that repository has over **140,000 GitHub stars** and contributions from hundreds of people I've never met but feel deeply grateful for. + +## Why I Wrote This Book + +The original version of this book was published on [Gumroad](https://gumroad.com/l/the-art-of-chatgpt-prompting) in **early 2023**, just months after ChatGPT launched. It was one of the first books ever written about prompt engineering, an attempt to capture everything I had learned about crafting effective prompts when the field was still brand new. To my amazement, over **100,000 people** downloaded it. + +But three years have passed since then. AI has changed a lot. New models have appeared. And we've all learned so much more about how to talk to AI. + +This new edition is my gift to the community that gave me so much. It contains everything I wish I had known when I started: **what works**, **what to avoid**, and **ideas that stay true** no matter which AI you use. + +## What This Book Means to Me + +I won't pretend this is just an instruction manual. It means more than that to me. + +This book captures a moment when the world changed, and people came together to figure it out. It represents late nights of trying things, the joy of discovery, and the kindness of strangers who shared what they learned. + +Most of all, it represents my belief that **the best way to learn something is to share it with others**. + +## For You + +Whether you're just getting started with AI or you've been using it for years, I wrote this book for you. + +I hope it saves you time. I hope it sparks ideas. I hope it helps you accomplish things you never thought possible. + +And when you discover something amazing, I hope you'll share it with others, just as so many people shared with me. + +**That's how we all get better together.** + +Thank you for being here. Thank you for being part of this community. + +Now, let's begin. + +--- + +*With gratitude,* + +**Fatih Kadir Akın** +*Istanbul, January 2025* diff --git a/src/content/book/ru/00b-history.mdx b/src/content/book/ru/00b-history.mdx new file mode 100644 index 00000000..ac636384 --- /dev/null +++ b/src/content/book/ru/00b-history.mdx @@ -0,0 +1,159 @@ +# The History of Awesome ChatGPT Prompts + +## The Beginning: November 2022 + +When ChatGPT first launched in November 2022, the world of AI changed overnight. What was once the domain of researchers and developers suddenly became accessible to everyone. Among those captivated by this new technology was Fatih Kadir Akın, a developer who saw something remarkable in ChatGPT's capabilities. + +> "When ChatGPT first launched, I was immediately captivated by its capabilities. I experimented with the tool in a variety of ways and was consistently amazed by the results." + +Those early days were filled with experimentation and discovery. Users around the world were finding creative ways to interact with ChatGPT, sharing their findings, and learning from each other. It was in this atmosphere of excitement and exploration that the idea for "Awesome ChatGPT Prompts" was born. + +## The Repository That Started It All + +In December 2022, just weeks after ChatGPT's launch, the [Awesome ChatGPT Prompts](https://github.com/f/prompts.chat) repository was created on GitHub. The concept was simple but powerful: a curated collection of effective prompts that anyone could use and contribute to. + +The repository quickly gained traction, becoming a go-to resource for ChatGPT users worldwide. What started as a personal collection of useful prompts evolved into a community-driven project with contributions from developers, writers, educators, and enthusiasts from every corner of the globe. + +### Achievements + +**Press & Media** +- Featured in [Forbes](https://www.forbes.com/sites/bernardmarr/2023/05/17/the-best-prompts-for-chatgpt-a-complete-guide/) as one of the best ChatGPT prompt resources + +**Academic Recognition** +- Referenced by [Harvard University](https://www.huit.harvard.edu/news/ai-prompts) in their AI guidance +- Referenced by [Columbia University](https://etc.cuit.columbia.edu/news/columbia-prompt-library-effective-academic-ai-use) Prompt Library +- Used by [Olympic College](https://libguides.olympic.edu/UsingAI/Prompts) in their AI resources +- Cited in [academic papers on arXiv](https://arxiv.org/pdf/2502.04484) +- [40+ academic citations](https://scholar.google.com/citations?user=AZ0Dg8YAAAAJ&hl=en) on Google Scholar + +**Community & GitHub** +- [142,000+ GitHub stars](https://github.com/f/prompts.chat) — one of the most starred AI repositories +- Selected as a [GitHub Staff Pick](https://spotlights-feed.github.com/spotlights/prompts-chat/) +- Most liked dataset published on [Hugging Face](https://huggingface.co/datasets/fka/prompts.chat) +- Used by thousands of developers worldwide + +## The First Book: "The Art of ChatGPT Prompting" + +The success of the repository led to the creation of "The Art of ChatGPT Prompting: A Guide to Crafting Clear and Effective Prompts" — a comprehensive guide published on Gumroad in early 2023. + +The book captured the early wisdom of prompt engineering, covering: + +- Understanding how ChatGPT works +- Principles of clear communication with AI +- The famous "Act As" technique +- Crafting effective prompts step by step +- Common mistakes and how to avoid them +- Troubleshooting tips + +**The book became a phenomenon**, achieving over **100,000 downloads** on Gumroad. It was shared across social media, referenced in academic papers, and translated by community members into multiple languages. High-profile endorsements came from unexpected places — even [Greg Brockman](https://x.com/gdb/status/1602072566671110144), co-founder and president of OpenAI, acknowledged the project. + +## Early Insights That Shaped the Field + +During those formative months, several key insights emerged that would become foundational to prompt engineering: + +### 1. Specificity Matters + +> "I learned the importance of using specific and relevant language to ensure that ChatGPT understands my prompts and is able to generate appropriate responses." + +Early experimenters discovered that vague prompts led to vague responses. The more specific and detailed the prompt, the more useful the output. + +### 2. Purpose and Focus + +> "I discovered the value of defining a clear purpose and focus for the conversation, rather than using open-ended or overly broad prompts." + +This insight became the foundation for structured prompting techniques that would develop over the following years. + +### 3. The "Act As" Revolution + +One of the most influential techniques to emerge from the community was the "Act As" pattern. By instructing ChatGPT to assume a specific role or persona, users could dramatically improve the quality and relevance of responses. + +``` +I want you to act as a javascript console. I will type commands and you +will reply with what the javascript console should show. I want you to +only reply with the terminal output inside one unique code block, and +nothing else. +``` + +This simple technique opened up countless possibilities and remains one of the most widely used prompting strategies today. + +## The Evolution of prompts.chat + +### 2022: The Beginning + +The project started as a simple GitHub repository with a README file rendered as HTML on GitHub Pages. It was bare-bones but functional — a testament to the principle that great ideas don't need elaborate implementations. + +**Tech Stack**: HTML, CSS, GitHub Pages + +### 2024: UI Renewal + +As the community grew, so did the need for a better user experience. The site received a significant UI update, built with the help of AI coding assistants like Cursor and Claude Sonnet 3.5. + +### 2025: The Current Platform + +Today, prompts.chat has evolved into a full-featured platform built with: + +- **Next.js** for the web framework +- **Vercel** for hosting +- **AI-assisted development** using Windsurf and Claude + +The platform now features user accounts, collections, search, categories, tags, and a thriving community of prompt engineers. + +### Native Apps + +The project expanded beyond the web with a native iOS app built with SwiftUI, bringing the prompt library to mobile users. + +## Community Impact + +The Awesome ChatGPT Prompts project has had a profound impact on how people interact with AI: + +### Academic Recognition + +Universities around the world have referenced the project in their AI guidance materials, including: + +- Harvard University +- Columbia University +- Olympic College +- Numerous academic papers on arXiv + +### Developer Adoption + +The project has been integrated into countless developer workflows. The Hugging Face dataset is used by researchers and developers for training and fine-tuning language models. + +### Global Community + +With contributions from hundreds of community members across dozens of countries, the project represents a truly global effort to make AI more accessible and useful for everyone. + +## The Philosophy: Open and Free + +From the beginning, the project has been committed to openness. Licensed under CC0 1.0 Universal (Public Domain Dedication), all prompts and content are free to use, modify, and share without restriction. + +This philosophy has enabled: + +- Translations into multiple languages +- Integration into other tools and platforms +- Academic use and research +- Commercial applications + +The goal has always been to democratize access to effective AI communication techniques — to ensure that everyone, regardless of technical background, can benefit from these tools. + +## Three Years Later + +Three years after ChatGPT's launch, the field of prompt engineering has matured significantly. What began as informal experimentation has evolved into a recognized discipline with established patterns, best practices, and an active research community. + +The Awesome ChatGPT Prompts project has grown alongside this field, evolving from a simple list of prompts to a comprehensive platform for discovering, sharing, and learning about AI prompts. + +This book represents the next evolution — a distillation of three years of community wisdom, updated for the AI landscape of today and tomorrow. + +## Looking Forward + +The journey from that first repository to this comprehensive guide reflects the rapid evolution of AI and our understanding of how to work with it effectively. As AI capabilities continue to advance, so too will the techniques for communicating with these systems. + +The principles discovered in those early days — clarity, specificity, purpose, and the power of role-playing — remain as relevant as ever. But new techniques continue to emerge: chain-of-thought prompting, few-shot learning, multimodal interactions, and more. + +The story of Awesome ChatGPT Prompts is ultimately a story about community — about thousands of people around the world sharing their discoveries, helping each other learn, and collectively advancing our understanding of how to work with AI. + +That spirit of open collaboration and shared learning is what this book hopes to continue. + +--- + +*The Awesome ChatGPT Prompts project is maintained by [@f](https://github.com/f) and an amazing community of contributors. Visit [prompts.chat](https://prompts.chat) to explore the platform, and join us on [GitHub](https://github.com/f/prompts.chat) to contribute.* diff --git a/src/content/book/ru/00c-introduction.mdx b/src/content/book/ru/00c-introduction.mdx new file mode 100644 index 00000000..c744bd1e --- /dev/null +++ b/src/content/book/ru/00c-introduction.mdx @@ -0,0 +1,130 @@ +Welcome to **The Interactive Book of Prompting**, your guide to communicating effectively with AI. + + +By the end of this book, you'll understand how AI works, how to write better prompts, and how to use these skills for writing, coding, research, and creative projects. + + + +Unlike traditional books, this guide is fully interactive. You'll find live demos, clickable examples, and "Try It" buttons throughout that let you test prompts instantly. Learning by doing makes complex concepts much easier to understand. + + +## What is Prompt Engineering? + +Prompt engineering is the skill of writing good instructions for AI. When you type something to ChatGPT, Claude, Gemini, or other AI tools, that's called a "prompt." The better your prompt, the better the answer you get. + +Think of it like this: AI is a powerful helper that takes your words very literally. It will do exactly what you ask. The trick is learning how to ask for exactly what you want. + + + +The difference in output quality between these two prompts can be dramatic. + + + +## How Prompt Engineering Has Evolved + +In just three years since ChatGPT launched, prompt engineering has evolved dramatically alongside the technology itself. What started as simply "writing better questions" has grown into something much broader. + +Today, we understand that your prompt is just **one part of a larger context**. Modern AI systems work with multiple types of data simultaneously: + +- **System prompts** that define the AI's behavior +- **Conversation history** from previous messages +- **Retrieved documents** pulled from databases (RAG) +- **Tool definitions** that let AI take actions +- **User preferences** and settings +- **Your actual prompt** - the question you're asking right now + +This shift from "prompt engineering" to "context engineering" reflects how we now think about AI interactions. Your prompt matters, but so does everything else the AI sees. The best results come from carefully managing all these pieces together. + +We'll explore these concepts in depth throughout this book, especially in the [Context Engineering](/book/20-context-engineering) chapter. + +## Why Does Prompt Engineering Matter? + +### 1. Getting Better Answers + +AI tools are incredibly capable, but they need clear instructions to unlock their full potential. The same AI that gives a mediocre response to a vague question can produce brilliant work when prompted correctly. + + + +### 2. Saving Time and Money + +A well-crafted prompt gets results in one try instead of multiple back-and-forth exchanges. This matters even more when you're paying per token or working with rate limits. A 5-minute investment in writing a good prompt can save hours of iteration. + +### 3. Getting Consistent, Reproducible Results + +Good prompts produce predictable outputs. This is critical for: +- **Business workflows** where you need the same quality every time +- **Automation** where prompts run without human review +- **Teams** where multiple people need similar results + +### 4. Unlocking Advanced Capabilities + +Many powerful AI features only work when you know how to ask: +- **Chain-of-thought reasoning** for complex problems +- **Structured output** for data extraction +- **Role-playing** for specialized expertise +- **Few-shot learning** for custom tasks + +Without prompt engineering knowledge, you're only using a fraction of what AI can do. + +### 5. Staying Safe and Avoiding Pitfalls + +Good prompting helps you: +- Avoid hallucinations by asking for sources and verification +- Get balanced perspectives instead of one-sided answers +- Prevent the AI from making assumptions you didn't intend +- Keep sensitive information out of your prompts + +### 6. Future-Proofing Your Skills + +As AI becomes more integrated into work and life, prompt engineering becomes a fundamental literacy. The principles you learn here apply across all AI tools—ChatGPT, Claude, Gemini, image generators, and future models we haven't seen yet. + +## Who Is This Book For? + +This book is for everyone: + +- **Beginners** who want to learn how to use AI tools better +- **Students** working on homework, research, or creative projects +- **Writers and creators** using AI for their work +- **Developers** building apps with AI +- **Business people** who want to use AI at work +- **Anyone curious** about getting more out of AI assistants + +## How This Book Is Organized + + + +Plus an **Appendix** with templates, troubleshooting help, glossary, and extra resources. + +## A Note on AI Models + +This book mostly uses examples from ChatGPT (since it's the most popular), but the ideas work with any AI tool like Claude, Gemini, or others. We'll mention when something only works with specific AI models. + +AI is changing fast. What works today might be replaced by something better tomorrow. That's why this book focuses on core ideas that will stay useful no matter which AI you use. + +## Let's Begin + +Writing good prompts is a skill that gets better with practice. As you read this book: + +1. **Try things** - Test the examples, change them, see what happens +2. **Keep trying** - Don't expect perfect results on your first attempt +3. **Take notes** - Write down what works and what doesn't +4. **Share** - Add your discoveries to [prompts.chat](https://prompts.chat) + + +The best way to learn is by doing. Every chapter has examples you can try right away. Don't just read. Try it yourself! + + +Ready to transform how you work with AI? Turn the page and let's get started. + +--- + +*This book is part of the [Awesome ChatGPT Prompts](https://github.com/f/prompts.chat) project and is licensed under CC0 1.0 Universal (Public Domain).* diff --git a/src/content/book/ru/01-understanding-ai-models.mdx b/src/content/book/ru/01-understanding-ai-models.mdx new file mode 100644 index 00000000..0313d4a2 --- /dev/null +++ b/src/content/book/ru/01-understanding-ai-models.mdx @@ -0,0 +1,302 @@ +Before learning prompt techniques, it helps to understand how AI language models actually work. This knowledge will make you better at writing prompts. + + +Understanding how AI works isn't just for experts. It directly helps you write better prompts. Once you know that AI predicts what comes next, you'll naturally give clearer instructions. + + +## What Are Large Language Models? + +Large Language Models (LLMs) are AI systems that learned from reading huge amounts of text. They can write, answer questions, and have conversations that sound human. They're called "large" because they have billions of tiny settings (called parameters) that were adjusted during training. + +### How LLMs Work (Simplified) + +At their heart, LLMs are prediction machines. You give them some text, and they predict what should come next. + + + +When you type "The capital of France is...", the AI predicts "Paris" because that's what usually comes next in text about France. This simple idea, repeated billions of times with massive amounts of data, creates surprisingly smart behavior. + + + +### Key Concepts + +**Tokens**: AI doesn't read letter by letter. It breaks text into chunks called "tokens." A token might be a whole word like "hello" or part of a word like "ing." Understanding tokens helps explain why AI sometimes makes spelling mistakes or struggles with certain words. + + +A token is the smallest unit of text that an AI model processes. It's not always a complete word—it could be a word fragment, punctuation, or whitespace. For example, "unbelievable" might become 3 tokens: "un" + "believ" + "able". On average, **1 token ≈ 4 characters** or **100 tokens ≈ 75 words**. API costs and context limits are measured in tokens. + + + + +**Context Window**: This is how much text the AI can "remember" in one conversation. Think of it like the AI's short-term memory. It includes everything: your question AND the AI's answer. + + + +Context windows vary by model and are rapidly expanding: + +
+
+ GPT-4o + 128K tokens +
+
+ GPT-5 + 400K tokens +
+
+ Claude Sonnet 4 + 1M tokens +
+
+ Gemini 2.5 + 1M tokens +
+
+ Llama 4 + 1M-10M tokens +
+
+ DeepSeek R1 + 128K tokens +
+
+ +**Temperature**: This controls how creative or predictable the AI is. Low temperature (0.0-0.3) gives you focused, consistent answers. High temperature (0.7-1.0) gives you more creative, surprising responses. + + + +**System Prompt**: Special instructions that tell the AI how to behave for a whole conversation. For example, "You are a friendly teacher who explains things simply." Not all AI tools let you set this, but it's very powerful when available. + +## Types of AI Models + +### Text Models (LLMs) +The most common type, these generate text responses to text inputs. They power chatbots, writing assistants, and code generators. Examples: GPT-4, Claude, Llama, Mistral. + +### Multimodal Models +These can understand more than just text. They can look at images, listen to audio, and watch videos. Examples: GPT-4V, Gemini, Claude 3. + +### Text-to-Image Models + + +While this book focuses primarily on prompting for Large Language Models (text-based AI), the principles of clear, specific prompting apply to image generation too. Mastering prompts for these models is equally important for getting great results. + + +Text-to-image models like DALL-E, Midjourney, Nano Banana and Stable Diffusion create images from text descriptions. They work differently from text models: + +**How They Work:** +1. **Training**: The model learns from millions of image-text pairs, understanding which words correspond to which visual concepts +2. **Diffusion Process**: Starting from random noise, the model gradually refines the image, guided by your text prompt +3. **CLIP Guidance**: A separate model (CLIP) helps connect your words to visual concepts, ensuring the image matches your description + + + +**Prompting for Images is Different:** +Unlike text prompts where you write sentences, image prompts often work better as descriptive phrases separated by commas: + + + +### Text-to-Video Models + +Text-to-video is the newest frontier. Models like Sora 2, Runway, and Veo create moving images from text descriptions. Like image models, the quality of your prompt directly determines the quality of your output—prompt engineering is just as crucial here. + +**How They Work:** +1. **Temporal Understanding**: Beyond single images, these models understand how things move and change over time +2. **Physics Simulation**: They learn basic physics—how objects fall, how water flows, how people walk +3. **Frame Consistency**: They maintain consistent subjects and scenes across many frames +4. **Diffusion in Time**: Similar to image models, but generating coherent sequences instead of single frames + + + + +Video prompts need to describe action over time, not just a static scene. Include verbs and movement: + + + + +### Specialized Models +Fine-tuned for specific tasks like code generation (Codex, CodeLlama), music generation (Suno, Udio), or domain-specific applications like medical diagnosis or legal document analysis. + +## Model Capabilities and Limitations + +Explore what LLMs can and cannot do. Click on each capability to see example prompts: + + + +### Understanding Hallucinations + + +Sometimes AI writes things that sound true but aren't. This is called "hallucination." It's not a bug. It's just how prediction works. Always double-check important facts. + + +Why does AI make things up? + +1. It tries to write text that sounds good, not text that's always true +2. The internet (where it learned) has mistakes too +3. It can't actually check if something is real + + + +- **Ask for sources**: Then check if those sources are real +- **Ask for step-by-step thinking**: So you can check each step +- **Double-check important facts**: Use Google or trusted websites +- **Ask "Are you sure?"**: The AI might admit uncertainty + + + + + +## How AI Learns: The Three Steps + +AI doesn't just magically know things. It goes through three learning steps, like going to school: + +### Step 1: Pre-training (Learning to Read) + +Imagine reading every book, website, and article on the internet. That's what happens in pre-training. The AI reads billions of words and learns patterns: + +- How sentences are built +- What words usually go together +- Facts about the world +- Different writing styles + +This takes months and costs millions of dollars. After this step, the AI knows a lot, but it's not very helpful yet. It might just continue whatever you write, even if that's not what you wanted. + + + +### Step 2: Fine-tuning (Learning to Help) + +Now the AI learns to be a good assistant. Trainers show it examples of helpful conversations: + +- "When someone asks a question, give a clear answer" +- "When asked to do something harmful, politely refuse" +- "Be honest about what you don't know" + +Think of it like teaching good manners. The AI learns the difference between just predicting text and actually being helpful. + + + +Try the prompt above. Notice how the AI refuses? That's fine-tuning at work. + +### Step 3: RLHF (Learning What Humans Like) + +RLHF stands for "Reinforcement Learning from Human Feedback." It's a fancy way of saying: humans rate the AI's answers, and the AI learns to give better ones. + +Here's how it works: +1. The AI writes two different answers to the same question +2. A human picks which answer is better +3. The AI learns: "Okay, I should write more like Answer A" +4. This happens millions of times + +This is why AI: +- Is polite and friendly +- Admits when it doesn't know something +- Tries to see different sides of an issue +- Avoids controversial statements + + +Knowing these three steps helps you understand AI behavior. When AI refuses a request, that's fine-tuning. When AI is extra polite, that's RLHF. When AI knows random facts, that's pre-training. + + +## What This Means for Your Prompts + +Now that you understand how AI works, here's how to use that knowledge: + +### 1. Be Clear and Specific + +AI predicts what comes next based on your words. Vague prompts lead to vague answers. Specific prompts get specific results. + + + + + +### 2. Give Context + +AI doesn't know anything about you unless you tell it. Each conversation starts fresh. Include the background information AI needs. + + + + + +### 3. Work With the AI, Not Against It + +Remember: AI was trained to be helpful. Ask for things the way you'd ask a helpful friend. + + + +### 4. Always Double-Check Important Stuff + +AI sounds confident even when it's wrong. For anything important, verify the information yourself. + + + +### 5. Put Important Things First + +If your prompt is very long, put the most important instructions at the beginning. AI pays more attention to what comes first. + +## Picking the Right AI + +Different AI models are good at different things: + +
+
+ Quick questions + Faster models like GPT-4o or Claude 3.5 Sonnet +
+
+ Hard problems + Smarter models like GPT-5.2 or Claude 4.5 Opus +
+
+ Writing code + Code-focused models or the smartest general models +
+
+ Long documents + Models with big context windows (Claude, Gemini) +
+
+ Current events + Models with internet access +
+
+ +## Summary + +AI language models are prediction machines trained on text. They're amazing at many things, but they have real limits. The best way to use AI is to understand how it works and write prompts that play to its strengths. + + + + + +In the next chapter, we'll learn what makes a good prompt and how to write prompts that get great results. diff --git a/src/content/book/ru/02-anatomy-of-effective-prompt.mdx b/src/content/book/ru/02-anatomy-of-effective-prompt.mdx new file mode 100644 index 00000000..03cd23d2 --- /dev/null +++ b/src/content/book/ru/02-anatomy-of-effective-prompt.mdx @@ -0,0 +1,343 @@ +Every great prompt shares common structural elements. Understanding these components allows you to construct prompts systematically rather than through trial and error. + + +Think of these components like LEGO bricks. You don't need all of them for every prompt, but knowing what's available helps you build exactly what you need. + + +## The Core Components + +An effective prompt typically includes some or all of these elements: + + + +Let's examine each component in detail. + +## 1. Role / Persona + +Setting a role focuses the model's responses through the lens of a specific expertise or perspective. + + + +The role primes the model to: +- Use appropriate vocabulary +- Apply relevant expertise +- Maintain a consistent perspective +- Consider the audience appropriately + +### Effective Role Patterns + +``` +"You are a [profession] with [X years] of experience in [specialty]" +"Act as a [role] who is [characteristic]" +"You are an expert [field] helping a [audience type]" +``` + +## 2. Context / Background + +Context provides the information the model needs to understand your situation. Remember: the model knows nothing about you, your project, or your goals unless you tell it. + + + +### What to Include in Context + +- **Project details** — Technology stack, architecture, constraints +- **Current state** — What you've tried, what's working, what isn't +- **Goals** — What you're ultimately trying to achieve +- **Constraints** — Time limits, technical requirements, style guides + +## 3. Task / Instruction + +The task is the heart of your prompt—what you want the model to do. Be specific and unambiguous. + +### The Specificity Spectrum + + + +### Action Verbs That Work Well + +
+
+ Creation + Write, Create, Generate, Compose, Design +
+
+ Analysis + Analyze, Evaluate, Compare, Assess, Review +
+
+ Transformation + Convert, Translate, Reformat, Summarize, Expand +
+
+ Explanation + Explain, Describe, Clarify, Define, Illustrate +
+
+ Problem-solving + Solve, Debug, Fix, Optimize, Improve +
+
+ +## 4. Constraints / Rules + +Constraints bound the model's output. They prevent common issues and ensure relevance. + +### Types of Constraints + +**Length constraints:** +``` +"Keep your response under 200 words" +"Provide exactly 5 suggestions" +"Write 3-4 paragraphs" +``` + +**Content constraints:** +``` +"Do not include any code examples" +"Focus only on the technical aspects" +"Avoid marketing language" +``` + +**Style constraints:** +``` +"Use a formal, academic tone" +"Write as if speaking to a 10-year-old" +"Be direct and avoid hedging language" +``` + +**Scope constraints:** +``` +"Only consider options available in Python 3.10+" +"Limit suggestions to free tools" +"Focus on solutions that don't require additional dependencies" +``` + +## 5. Output Format + +Specifying the output format ensures you get responses in a usable structure. + +### Common Formats + +**Lists:** +``` +"Return as a bulleted list" +"Provide a numbered list of steps" +``` + +**Structured data:** +``` +"Return as JSON with keys: title, description, priority" +"Format as a markdown table with columns: Feature, Pros, Cons" +``` + +**Specific structures:** +``` +"Structure your response as: + ## Summary + ## Key Points + ## Recommendations" +``` + +### JSON Output Example + +``` +Analyze this customer review and return JSON: +{ + "sentiment": "positive" | "negative" | "neutral", + "topics": ["array of main topics"], + "rating_prediction": 1-5, + "key_phrases": ["notable phrases"] +} + +Review: "The product arrived quickly and works great, but +the instructions were confusing." +``` + +## 6. Examples (Few-Shot Learning) + +Examples are the most powerful way to show the model exactly what you want. + +### One-Shot Example + +``` +Convert these sentences to past tense. + +Example: +Input: "She walks to the store" +Output: "She walked to the store" + +Now convert: +Input: "They run every morning" +``` + +### Few-Shot Example + +``` +Classify these support tickets by urgency. + +Examples: +"My account was hacked" → Critical +"How do I change my password?" → Low +"Payment failed but I was charged" → High + +Classify: "The app crashes when I open settings" +``` + +## Putting It All Together + +Here's a complete prompt using all components: + + + +## The Minimal Effective Prompt + +Not every prompt needs all components. For simple tasks, a clear instruction may suffice: + +``` +Translate "Hello, how are you?" to Spanish. +``` + +Use additional components when: +- The task is complex or ambiguous +- You need specific formatting +- Results aren't matching expectations +- Consistency across multiple queries matters + +## Common Prompt Patterns + +These frameworks give you a simple checklist to follow when writing prompts. Click on each step to see an example. + + + + + +## Summary + +Effective prompts are constructed, not discovered. By understanding and applying these structural components, you can: + +- Get better results on the first try +- Debug prompts that aren't working +- Create reusable prompt templates +- Communicate your intentions clearly + + + + + +## Build Your Own Prompt + +Now it's your turn! Use this interactive prompt builder to construct your own prompt using the components you've learned: + + + + + +In the next chapter, we'll explore the core principles that guide prompt construction decisions. diff --git a/src/content/book/ru/03-core-prompting-principles.mdx b/src/content/book/ru/03-core-prompting-principles.mdx new file mode 100644 index 00000000..358df563 --- /dev/null +++ b/src/content/book/ru/03-core-prompting-principles.mdx @@ -0,0 +1,373 @@ +Beyond structure, effective prompt engineering is guided by principles—fundamental truths that apply across models, tasks, and contexts. Master these principles, and you'll be able to adapt to any prompting challenge. + + +These principles apply to every AI model and every task. Learn them once, use them everywhere. + + +## Principle 1: Clarity Over Cleverness + +The best prompts are clear, not clever. AI models are literal interpreters—they work with exactly what you give them. + +### Be Explicit + + + +### Avoid Ambiguity + +Words can have multiple meanings. Choose precise language. + + + +### State the Obvious + +What's obvious to you isn't obvious to the model. Spell out assumptions. + +``` +You're helping me write a cover letter. + +Important context: +- I'm applying for a Software Engineer position at Google +- I have 5 years of experience in Python and distributed systems +- The role requires leadership experience (I've led a team of 4) +- I want to emphasize my open-source contributions +``` + +## Principle 2: Specificity Yields Quality + +Vague inputs produce vague outputs. Specific inputs produce specific, useful outputs. + +### The Specificity Ladder + + + +Each level adds specificity and dramatically improves output quality. + +### Specify These Elements + +
+
+ Audience + Who will read/use this? +
+
+ Length + How long/short should it be? +
+
+ Tone + Formal? Casual? Technical? +
+
+ Format + Prose? List? Table? Code? +
+
+ Scope + What to include/exclude? +
+
+ Purpose + What should this accomplish? +
+
+ +## Principle 3: Context Is King + +Models have no memory, no access to your files, and no knowledge of your situation. Everything relevant must be in the prompt. + +### Provide Sufficient Context + + + +### The Context Checklist + + +Ask yourself: Would a smart stranger understand this request? If not, add more context. + + + + +## Principle 4: Guide, Don't Just Ask + +Don't just ask for an answer—guide the model toward the answer you want. + +### Use Instructional Framing + + + +### Provide Reasoning Scaffolds + +For complex tasks, guide the reasoning process: + + + +## Principle 5: Iterate and Refine + +Prompt engineering is an iterative process. Your first prompt is rarely your best. + +### The Iteration Cycle + +``` +1. Write initial prompt +2. Review output +3. Identify gaps or issues +4. Refine prompt +5. Repeat until satisfied +``` + +### Common Refinements + +
+
+ Too verbose + Add "Be concise" or length limits +
+
+ Too vague + Add specific examples or constraints +
+
+ Wrong format + Specify exact output structure +
+
+ Missing aspects + Add "Make sure to include..." +
+
+ Wrong tone + Specify audience and style +
+
+ Inaccurate + Request citations or step-by-step reasoning +
+
+ +### Keep a Prompt Journal + +Document what works: +``` +Task: Code review +Version 1: "Review this code" → Too generic +Version 2: Added specific review criteria → Better +Version 3: Added example of good review → Excellent +Final: [Save successful prompt as template] +``` + +## Principle 6: Leverage the Model's Strengths + +Work with how models are trained, not against them. + +### Models Want to Be Helpful + +Frame requests as things a helpful assistant would naturally do: + + + +### Models Excel at Patterns + +If you need consistent output, show the pattern: + + + +### Models Can Role-Play + +Use personas to access different "modes" of response: + +``` +As a devil's advocate, argue against my proposal... +As a supportive mentor, help me improve... +As a skeptical investor, question this business plan... +``` + +## Principle 7: Control Output Structure + +Structured outputs are more useful than free-form text. + +### Request Specific Formats + +``` +Return your analysis as: + +SUMMARY: [1 sentence] + +KEY FINDINGS: +• [Finding 1] +• [Finding 2] +• [Finding 3] + +RECOMMENDATION: [1-2 sentences] + +CONFIDENCE: [Low/Medium/High] because [reason] +``` + +### Use Delimiters + +Clearly separate sections of your prompt: + +``` +### CONTEXT ### +[Your context here] + +### TASK ### +[Your task here] + +### FORMAT ### +[Desired format here] +``` + +### Request Machine-Readable Output + +For programmatic use: + +``` +Return only valid JSON, no explanation: +{ + "decision": "approve" | "reject" | "review", + "confidence": 0.0-1.0, + "reasons": ["string array"] +} +``` + +## Principle 8: Verify and Validate + +Never blindly trust model outputs, especially for important tasks. + +### Ask for Reasoning + +``` +Solve this problem and show your work step by step. +After solving, verify your answer by [checking method]. +``` + +### Request Multiple Perspectives + +``` +Give me three different approaches to solve this problem. +For each, explain the trade-offs. +``` + +### Build in Self-Checking + +``` +After generating the code, review it for: +- Syntax errors +- Edge cases +- Security vulnerabilities +List any issues found. +``` + +## Summary: The Principles at a Glance + + + + + +## Practice: Fill in the Blanks + +Test your understanding of the core principles by completing this prompt template: + + + + + +These principles form the foundation for everything that follows. In Part II, we'll apply them to specific techniques that dramatically enhance prompt effectiveness. diff --git a/src/content/book/ru/04-role-based-prompting.mdx b/src/content/book/ru/04-role-based-prompting.mdx new file mode 100644 index 00000000..ef178cbc --- /dev/null +++ b/src/content/book/ru/04-role-based-prompting.mdx @@ -0,0 +1,328 @@ +Role-based prompting is one of the most powerful and widely-used techniques in prompt engineering. By assigning a specific role or persona to the AI, you can dramatically influence the quality, style, and relevance of responses. + + +Think of roles as filters for AI's vast knowledge. The right role focuses responses like a lens focuses light. + + +## Why Roles Work + +When you assign a role, you're essentially telling the model: "Filter your vast knowledge through this specific lens." The model adjusts its: + +- **Vocabulary**: Using terminology appropriate to the role +- **Perspective**: Considering problems from that viewpoint +- **Expertise depth**: Providing role-appropriate detail levels +- **Communication style**: Matching how that role would communicate + +### The Technical Explanation + +LLMs work by predicting the most likely next token based on the context they're given. When you specify a role, you're fundamentally changing what "likely" means. + +**Activating Relevant Knowledge**: The role primes specific regions of the model's learned associations. Saying "You are a doctor" activates medical terminology, diagnostic reasoning patterns, and clinical communication styles from the training data. + +**Statistical Conditioning**: LLMs learned from millions of documents written by real experts. When you assign a role, the model conditions its probability distributions to match patterns it saw from that type of author. + +**Reducing Ambiguity**: Without a role, the model averages across all possible responders. With a role, it narrows to a specific subset, making responses more focused and consistent. + +**Context Anchoring**: The role creates a persistent context anchor throughout the conversation. Every subsequent response is influenced by this initial framing. + +Think of it this way: if you ask "What should I do about this cough?" the model could respond as a doctor, a friend, a pharmacist, or a worried parent. Each would give different advice. By specifying the role upfront, you're telling the model which "voice" to use from its training data. + + +The model isn't pretending or role-playing in a theatrical sense. It's statistically biasing its outputs toward patterns it learned from real experts, professionals, and specialists during training. A "doctor" role activates medical knowledge pathways; a "poet" role activates literary patterns. + + +## Basic Role Patterns + +These foundational patterns work across most use cases. Start with these templates and customize them for your needs. + +### The Expert Pattern + +The most versatile pattern. Specify the field of expertise and years of experience to get authoritative, in-depth responses. Works well for technical questions, analysis, and professional advice. + + + +### The Professional Pattern + +Ground the role in a real-world context by specifying a job title and organization type. This adds institutional knowledge and professional norms to the response. + + + +### The Teacher Pattern + +Perfect for learning and explanations. Specifying the audience level ensures the response matches the learner's background, from beginners to advanced practitioners. + + + +## Advanced Role Constructions + +### Compound Roles + +Combine multiple identities to get responses that blend different perspectives. This pediatrician-parent combination produces advice that's both medically sound and practically tested. + + + +### Situational Roles + +Place the role in a specific scenario to shape both content and tone. Here, the code review context makes the AI constructive and educational rather than just critical. + + + +### Perspective Roles + +Get feedback from a specific stakeholder's point of view. A VC perspective evaluates viability and scalability differently than a customer or engineer would. + + + +## Role Categories and Examples + +Different domains benefit from different types of roles. Here are proven examples organized by category that you can adapt for your tasks. + +### Technical Roles + +**Software Architect**: Best for system design decisions, technology choices, and architectural trade-offs. The focus on maintainability steers responses toward practical, long-term solutions. + + + +**Security Specialist**: The attacker mindset is key here. This role produces threat-focused analysis that identifies vulnerabilities a defensive-only perspective might miss. + + + +**DevOps Engineer**: Ideal for deployment, automation, and infrastructure questions. The emphasis on reliability ensures production-ready recommendations. + + + +### Creative Roles + +**Copywriter**: The "award-winning" qualifier and conversion focus produce punchy, persuasive copy rather than generic marketing text. + + + +**Screenwriter**: Activates knowledge of dramatic structure, pacing, and dialogue conventions. Great for any narrative writing that needs tension and character voice. + + + +**UX Writer**: A specialized role for interface text. The focus on brevity and user guidance produces concise, action-oriented copy. + + + +### Analytical Roles + +**Business Analyst**: Bridges the gap between technical and non-technical stakeholders. Useful for requirement gathering, spec writing, and identifying gaps in project plans. + + + +**Research Scientist**: The emphasis on evidence and uncertainty acknowledgment produces balanced, well-sourced responses that distinguish facts from speculation. + + + +**Financial Analyst**: Combines quantitative analysis with risk assessment. The dual focus on returns and risk produces more balanced investment perspectives. + + + +### Educational Roles + +**Socratic Tutor**: Instead of giving answers, this role asks guiding questions. Excellent for deeper learning and helping students develop critical thinking skills. + + + +**Instructional Designer**: Structures learning for maximum retention. Use this role when you need to break down complex topics into teachable chunks with clear progression. + + + +## The Role Stack Technique + +For complex tasks, combine multiple role aspects into a single, layered identity. This technique stacks expertise, audience awareness, and style guidelines to create highly specialized responses. + +This example layers three elements: domain expertise (API documentation), audience (junior developers), and style guide (Google's conventions). Each layer constrains the output further. + + + +## Roles for Different Tasks + +
+
+ Code review + Senior developer + mentor +
+
+ Writing feedback + Editor + target audience member +
+
+ Business strategy + Consultant + industry expert +
+
+ Learning new topic + Patient teacher + practitioner +
+
+ Creative writing + Specific genre author +
+
+ Technical explanation + Expert + communicator +
+
+ Problem-solving + Domain specialist + generalist +
+
+ +## Anti-Patterns to Avoid + +### Overly Generic Roles + + + +### Conflicting Roles + + + +### Unrealistic Expertise + + + +## Real-World Prompt Examples + +### Technical Documentation + + + +### Creative Writing + + + +### Business Communication + + + +## Combining Roles with Other Techniques + +Roles work even better when combined with other prompting techniques: + +### Role + Few-Shot + +Combine a role with an example to show exactly how the role should respond. The example teaches tone and format while the role provides context and expertise. + + + +### Role + Chain of Thought + +The detective role naturally encourages step-by-step reasoning. Combining roles with chain-of-thought produces more transparent, verifiable problem-solving. + + + +## Summary + + +Role-based prompting is powerful because it focuses the model's vast knowledge, sets expectations for tone and style, provides implicit context, and makes outputs more consistent. + + + + +The key is **specificity**: the more detailed and realistic the role, the better the results. In the next chapter, we'll explore how to get consistent, structured outputs from your prompts. diff --git a/src/content/book/ru/05-structured-output.mdx b/src/content/book/ru/05-structured-output.mdx new file mode 100644 index 00000000..8236abee --- /dev/null +++ b/src/content/book/ru/05-structured-output.mdx @@ -0,0 +1,411 @@ +Getting consistent, well-formatted output is essential for production applications and efficient workflows. This chapter covers techniques for controlling exactly how AI models format their responses. + + +Structured output transforms AI responses from freeform text into actionable, parseable data. + + +## Why Structure Matters + + + +## Basic Formatting Techniques + +### Lists + +Lists are perfect for step-by-step instructions, ranked items, or collections of related points. They're easy to scan and parse. Use **numbered lists** when order matters (steps, rankings) and **bullet points** for unordered collections. + + + + +Specify the exact number of items you want, whether to include explanations, and if items should be bold or have a specific structure. + + +### Tables + +Tables excel at comparing multiple items across the same dimensions. They're ideal for feature comparisons, data summaries, and any information with consistent attributes. Always define your column headers explicitly. + + + + +Specify column names, expected data types (text, numbers, ratings), and how many rows you need. For complex comparisons, limit to 4-6 columns for readability. + + +### Headers and Sections + +Headers create a clear document structure, making long responses scannable and organized. Use them for reports, analyses, or any multi-part response. Hierarchical headers (##, ###) show relationships between sections. + +``` +Analyze this business proposal. + +Structure your response with these sections: +## Executive Summary +## Strengths +## Weaknesses +## Recommendations +## Risk Assessment +``` + + +List your sections in the order you want them. For consistency, specify what each section should contain (e.g., "Executive Summary: 2-3 sentences only"). + + +### Emphasis with Uppercase Directives + +Uppercase words act as strong signals to the model, emphasizing critical constraints or requirements. Use them sparingly for maximum impact—overuse dilutes their effectiveness. + +**Common Uppercase Directives:** + + + +``` +Summarize this article. + +IMPORTANT: Keep the summary under 100 words. +NEVER add information not present in the original. +ALWAYS maintain the original tone and perspective. +DO NOT include your own opinions or analysis. +``` + + +If everything is uppercase or marked as critical, nothing stands out. Reserve these directives for genuinely important constraints. + + +## JSON Output + +JSON (JavaScript Object Notation) is the most popular format for structured AI output. It's machine-readable, widely supported by programming languages, and perfect for APIs, databases, and automation workflows. The key to reliable JSON is providing a clear schema. + +### Basic JSON Request + +Start with a template showing the exact structure you want. Include field names, data types, and example values. This acts as a contract the model will follow. + + + +### Complex JSON Structures + +For nested data, use hierarchical JSON with objects inside objects, arrays of objects, and mixed types. Define each level clearly and use TypeScript-style annotations (`"positive" | "negative"`) to constrain values. + +``` +Analyze this product review and return JSON: + +{ + "review_id": "string (generate unique)", + "sentiment": { + "overall": "positive" | "negative" | "mixed" | "neutral", + "score": 0.0-1.0 + }, + "aspects": [ + { + "aspect": "string (e.g., 'price', 'quality')", + "sentiment": "positive" | "negative" | "neutral", + "mentions": ["exact quotes from review"] + } + ], + "purchase_intent": { + "would_recommend": boolean, + "confidence": 0.0-1.0 + }, + "key_phrases": ["string array of notable phrases"] +} + +Return ONLY valid JSON, no additional text. + +Review: "[review text]" +``` + +### Ensuring Valid JSON + +Models sometimes add explanatory text or markdown formatting around JSON. Prevent this with explicit instructions about output format. You can request raw JSON or JSON inside code blocks—choose based on your parsing needs. + +Add explicit instructions: + +``` +IMPORTANT: +- Return ONLY the JSON object, no markdown code blocks +- Ensure all strings are properly escaped +- Use null for missing values, not undefined +- Validate that the output is parseable JSON +``` + +Or request code blocks by asking the model to wrap its output: + +```` +Return the result as a JSON code block: +```json +{ ... } +``` +```` + +## YAML Output + +YAML is more human-readable than JSON, using indentation instead of brackets. It's the standard for configuration files (Docker, Kubernetes, GitHub Actions) and works well when the output will be read by humans or used in DevOps contexts. YAML is sensitive to indentation, so be specific about formatting requirements. + + + +## XML Output + +XML is still required for many enterprise systems, SOAP APIs, and legacy integrations. It's more verbose than JSON but offers features like attributes, namespaces, and CDATA sections for complex data. Specify element names, nesting structure, and where to use attributes vs. child elements. + +``` +Convert this data to XML format: + +Requirements: +- Root element: +- Each item in element +- Include attributes where appropriate +- Use CDATA for description text + +Data: [book data] +``` + +## Custom Formats + +Sometimes standard formats don't fit your needs. You can define any custom format by providing a clear template. Custom formats work well for reports, logs, or domain-specific outputs that will be read by humans. + +### Structured Analysis Format + +Use delimiters (===, ---, [SECTION]) to create scannable documents with clear boundaries between sections. This format is great for code reviews, audits, and analyses. + +``` +Analyze this code using this exact format: + +=== CODE ANALYSIS === + +[SUMMARY] +One paragraph overview + +[ISSUES] +• CRITICAL: [issue] — [file:line] +• WARNING: [issue] — [file:line] +• INFO: [issue] — [file:line] + +[METRICS] +Complexity: [Low/Medium/High] +Maintainability: [score]/10 +Test Coverage: [estimated %] + +[RECOMMENDATIONS] +1. [Priority 1 recommendation] +2. [Priority 2 recommendation] + +=== END ANALYSIS === +``` + +### Fill-in-the-Blank Format + +Templates with blanks (___) guide the model to fill in specific fields while maintaining exact formatting. This approach is excellent for forms, briefs, and standardized documents where consistency matters. + +``` +Complete this template for the given product: + +PRODUCT BRIEF +───────────── +Name: _______________ +Tagline: _______________ +Target User: _______________ +Problem Solved: _______________ +Key Features: + 1. _______________ + 2. _______________ + 3. _______________ +Differentiator: _______________ + +Product: [product description] +``` + +## Typed Responses + +Typed responses define categories or entity types that the model should recognize and label. This technique is essential for Named Entity Recognition (NER), classification tasks, and any extraction where you need to categorize information consistently. Define your types clearly with examples. + + + +## Multi-Part Structured Responses + +When you need comprehensive output covering multiple aspects, define distinct parts with clear boundaries. Specify exactly what goes in each part—format, length, and content type. This prevents the model from blending sections or omitting parts. + +``` +Research this topic and provide: + +### PART 1: EXECUTIVE SUMMARY +[2-3 sentence overview] + +### PART 2: KEY FINDINGS +[Exactly 5 bullet points] + +### PART 3: DATA TABLE +| Metric | Value | Source | +|--------|-------|--------| +[Include 5 rows minimum] + +### PART 4: RECOMMENDATIONS +[Numbered list of 3 actionable recommendations] + +### PART 5: FURTHER READING +[3 suggested resources with brief descriptions] +``` + +## Conditional Formatting + +Conditional formatting lets you define different output formats based on the input's characteristics. This is powerful for classification, triage, and routing systems where the response format should vary based on what the model detects. Use clear if/then logic with explicit output templates for each case. + + + +## Arrays and Lists in JSON + +Extracting multiple items into arrays requires careful schema definition. Specify the array structure, what each item should contain, and how to handle edge cases (empty arrays, single items). Including a count field helps verify completeness. + +``` +Extract all action items from this meeting transcript. + +Return as JSON array: +{ + "action_items": [ + { + "task": "string describing the task", + "assignee": "person name or 'Unassigned'", + "deadline": "date if mentioned, else null", + "priority": "high" | "medium" | "low", + "context": "relevant quote from transcript" + } + ], + "total_count": number +} + +Transcript: "[meeting transcript]" +``` + +## Validation Instructions + +Self-validation prompts the model to check its own output before responding. This catches common issues like missing sections, placeholder text, or constraint violations. The model will iterate internally to fix problems, improving output quality without additional API calls. + +``` +Generate the report, then: + +VALIDATION CHECKLIST: +□ All required sections present +□ No placeholder text remaining +□ All statistics include sources +□ Word count within 500-700 words +□ Conclusion ties back to introduction + +If any check fails, fix before responding. +``` + +## Handling Optional Fields + +Real-world data often has missing values. Explicitly instruct the model on how to handle optional fields—using `null` is cleaner than empty strings and easier to process programmatically. Also prevent "hallucination" of missing data by emphasizing that the model should never invent information. + +``` +Extract contact information. Use null for missing fields. + +{ + "name": "string (required)", + "email": "string or null", + "phone": "string or null", + "company": "string or null", + "role": "string or null", + "linkedin": "URL string or null" +} + +IMPORTANT: +- Never invent information not in the source +- Use null, not empty strings, for missing data +- Phone numbers in E.164 format if possible +``` + +## Summary + + +Be explicit about format, use examples, specify types, handle edge cases with null values, and ask the model to validate its own output. + + + + +Structured outputs are essential for building reliable AI-powered applications. In the next chapter, we'll explore chain-of-thought prompting for complex reasoning tasks. diff --git a/src/content/book/ru/06-chain-of-thought.mdx b/src/content/book/ru/06-chain-of-thought.mdx new file mode 100644 index 00000000..e579be5d --- /dev/null +++ b/src/content/book/ru/06-chain-of-thought.mdx @@ -0,0 +1,363 @@ +Chain of Thought (CoT) prompting is a technique that dramatically improves AI performance on complex reasoning tasks by asking the model to show its work step by step. + + +Just like a math teacher asking students to show their work, CoT prompting asks the AI to make its reasoning visible. + + +## The Problem CoT Solves + +AI models can struggle with multi-step reasoning when asked to jump directly to an answer. + + + +## Basic CoT Prompts + +### Simple Trigger Phrases + +Add one of these to your prompts: + +
+
"Let's think step by step."
+
"Think through this carefully."
+
"Work through this problem methodically."
+
"Show your reasoning at each step."
+
"Explain your thought process."
+
+ +### Explicit Step Request + + + +## Zero-Shot vs Few-Shot CoT + +There are two main approaches to Chain of Thought prompting, each with different trade-offs between simplicity and control. + +### Zero-Shot CoT + +The simplest approach—just add a trigger phrase and let the model figure out how to reason. No examples needed. This works surprisingly well for many problems, though you have less control over the reasoning format. + + + +**Example Output:** +``` +Let's think step by step. +- John starts with 3 apples +- Half of 3 is 1.5, but we can't split apples +- If we round down: John gives 1 apple, keeps 2 +- After buying 4 more: 2 + 4 = 6 apples + +Answer: 6 apples +``` + +### Few-Shot CoT + +For more consistent results, show the model exactly how you want it to reason by providing worked examples. This gives you control over the reasoning style, format, and level of detail. The model will mimic your demonstrated pattern. + + + +**Example Output:** +``` +A: Let's work through this: +- Regular price: $3, Quantity: 12 +- Since 12 ≥ 10, the 25% discount applies +- Regular total: 12 × $3 = $36 +- Discount: 25% of $36 = $9 +- Final price: $36 - $9 = $27 +``` + +## Structured CoT Formats + +For consistent, reproducible reasoning, use structured formats with named steps. These frameworks ensure the model doesn't skip important stages and makes outputs easier to parse and verify. + +### The BREAK Format + +A memorable acronym that guides the model through a complete problem-solving cycle, from understanding to verification. + + + +### The Reasoning Template + +A more formal structure that separates inputs, goals, and execution. Excellent for technical problems where you need clear documentation of the solution process. + + + +**Example Output:** +``` +GIVEN: 8L/100km, tank 45L, $1.50/L, drive 300km +GOAL: Calculate fuel cost +APPROACH: Fuel needed × cost per liter +STEPS: +1. Fuel = (300 ÷ 100) × 8 = 24 liters +2. Cost = 24 × $1.50 = $36 +VERIFICATION: 24L < 45L tank ✓ +ANSWER: $36 +``` + +## CoT for Different Problem Types + +Different problem types benefit from different CoT approaches. Here are patterns optimized for common scenarios. + +### Mathematical Reasoning + +Math problems benefit most from CoT because each step builds on the previous one. Errors compound, so showing work helps catch mistakes early. The model should clearly label each calculation. + + + +**Example Output:** +``` +Q1: $1,200,000 (given) +Q2: $1,200,000 × 1.15 = $1,380,000 +Q3: $1,380,000 × 0.90 = $1,242,000 +Q4: $1,242,000 × 1.25 = $1,552,500 + +Total: $5,374,500 +``` + +### Logical Reasoning + +Logic puzzles require systematic elimination and hypothesis testing. CoT helps the model track constraints, test possibilities, and verify that all conditions are satisfied. The key is methodical exploration rather than guessing. + + + +**Example Output:** +``` +From clue 3: Bob = teacher +→ Alice and Carol are engineer/doctor + +If Carol = engineer: +- Carol has dog (clue 2) +- Alice = doctor, has fish (clue 1) +- Bob has cat + +Verify: All 4 clues satisfied ✓ +Answer: Alice (doctor, fish), Bob (teacher, cat), Carol (engineer, dog) +``` + +### Code Debugging + +Debugging benefits from CoT because it forces the model to trace execution rather than guess at bugs. By walking through the code with concrete values, the actual behavior becomes visible and discrepancies with expected behavior are exposed. + + + +**Example Output:** +``` +Trace [2, 3, 4, 6]: +n=2: total += 1 → 1 (wait, adding 1 not n!) +n=3: skip (odd) +n=4: total = 2 +n=6: total = 3 + +BUG: "total += 1" should be "total += n" +Expected: 12, Got: 3 +Fix: Change to "total += n" +``` + +## Self-Consistency with CoT + +For critical problems, don't rely on a single reasoning path. Generate multiple independent solutions and compare results. If different approaches converge on the same answer, confidence is high. Disagreement signals the need for careful review. + + + +**Example Output:** +``` +Approach 1 (Algebra): c + w = 30, 2c + 4w = 74 → c=23, w=7 +Approach 2 (Guess): Try 23/7 → 46 + 28 = 74 ✓ +Approach 3 (Logic): 30 chickens = 60 legs, need 14 more → 7 cows + +All agree: 23 chickens, 7 cows +``` + +## CoT for Decision Making + +Decisions involve weighing trade-offs across multiple dimensions. CoT ensures all relevant factors are considered systematically rather than jumping to conclusions. This structured approach also documents the reasoning for future reference. + + + +**Example Output:** +``` +FACTORS: +- Team size (5): Too small for microservices ❌ +- Scale (100 DAU): No scaling need ❌ +- Velocity: Monolith = faster iteration ❌ +- Future growth: Uncertain timeline ⚠️ + +WEIGHING: 3 strong against, 1 weak for + +RECOMMENDATION: Stay monolith, use clear module +boundaries to ease future transition. +``` + +## When to Use CoT + +
+
+

Use CoT For

+
+

**Math problems** — Reduces calculation errors

+

**Logic puzzles** — Prevents skipped steps

+

**Complex analysis** — Organizes thinking

+

**Code debugging** — Traces execution

+

**Decision making** — Weighs trade-offs

+
+
+
+

Skip CoT For

+
+

**Simple Q&A** — Unnecessary overhead

+

**Creative writing** — Can constrain creativity

+

**Factual lookups** — No reasoning needed

+

**Translation** — Direct task

+

**Summarization** — Usually straightforward

+
+
+
+ +## CoT Limitations + +While powerful, Chain of Thought isn't a silver bullet. Understanding its limitations helps you apply it appropriately. + +1. **Increased token usage** — More output means higher costs +2. **Not always needed** — Simple tasks don't benefit +3. **Can be verbose** — May need to ask for conciseness +4. **Reasoning can be flawed** — CoT doesn't guarantee correctness + +## Summary + + +CoT dramatically improves complex reasoning by making implicit steps explicit. Use it for math, logic, analysis, and debugging. Trade-off: better accuracy for more tokens. + + + + +In the next chapter, we'll explore few-shot learning—teaching the model through examples. diff --git a/src/content/book/ru/07-few-shot-learning.mdx b/src/content/book/ru/07-few-shot-learning.mdx new file mode 100644 index 00000000..24e98f1d --- /dev/null +++ b/src/content/book/ru/07-few-shot-learning.mdx @@ -0,0 +1,478 @@ +Few-shot learning is one of the most powerful prompting techniques. By providing examples of what you want, you can teach the model complex tasks without any fine-tuning. + + +Just like humans learn by seeing examples, AI models can learn patterns from the examples you provide in your prompt. + + +## What is Few-Shot Learning? + +Few-shot learning shows the model examples of input-output pairs before asking it to perform the same task. The model learns the pattern from your examples and applies it to new inputs. + + + +
+
+
0
+
Zero-shot
+
+
+
1
+
One-shot
+
+
+
2-5
+
Few-shot
+
+
+
5+
+
Many-shot
+
+
+ +## Why Examples Work + + + +Examples communicate: +- **Format**: How output should be structured +- **Style**: Tone, length, vocabulary +- **Logic**: The reasoning pattern to follow +- **Edge cases**: How to handle special situations + +## Basic Few-Shot Pattern + +The fundamental structure of few-shot prompting follows a simple pattern: show examples, then ask for the new task. Consistency in formatting between examples is crucial. The model learns from the pattern you establish. + +``` +[Example 1] +Input: [input 1] +Output: [output 1] + +[Example 2] +Input: [input 2] +Output: [output 2] + +[Example 3] +Input: [input 3] +Output: [output 3] + +Now do this one: +Input: [new input] +Output: +``` + +## Few-Shot for Classification + +Classification is one of the strongest use cases for few-shot learning. By showing examples of each category, you define the boundaries between classes more precisely than instructions alone could achieve. + +### Sentiment Analysis + + +Sentiment analysis classifies text by emotional tone: positive, negative, neutral, or mixed. It's widely used for customer feedback, social media monitoring, and brand perception tracking. + + +Sentiment classification benefits from showing examples of each sentiment type, especially edge cases like "mixed" sentiment that might be ambiguous. + + + +### Topic Classification + +For multi-class categorization, include at least one example per category. This helps the model understand your specific taxonomy, which may differ from its default understanding. + + + +## Few-Shot for Transformation + +Transformation tasks convert input from one form to another while preserving meaning. Examples are essential here because they define exactly what "transformation" means for your use case. + +### Text Rewriting + +Style transformation requires examples that show the exact tone shift you want. Abstract instructions like "make it professional" are interpreted differently. Examples make it concrete. + + + +### Format Conversion + +Format conversion tasks benefit from examples showing edge cases and ambiguous inputs. The model learns your specific conventions for handling tricky cases. + + + +## Few-Shot for Generation + +Generation tasks create new content following a learned pattern. Examples establish length, structure, tone, and what details to highlight. These are hard to specify in instructions alone. + +### Product Descriptions + +Marketing copy benefits enormously from examples because they capture brand voice, feature emphasis, and persuasive techniques that are difficult to describe abstractly. + + + +### Code Documentation + + +Good documentation explains what code does, its parameters, return values, and usage examples. Consistent docstrings enable auto-generated API docs and help IDEs provide better code completion. + + +Documentation style varies widely between projects. Examples teach your specific format, what to include (args, returns, examples), and the level of detail expected. + +>> calculate_bmi(70, 1.75) + 22.86 +""" + +Now document: +Function: +def is_palindrome(text): + cleaned = ''.join(c.lower() for c in text if c.isalnum()) + return cleaned == cleaned[::-1] + +Documentation:`} /> + +## Few-Shot for Extraction + +Extraction tasks pull structured information from unstructured text. Examples define which entities matter, how to format output, and how to handle cases where information is missing or ambiguous. + +### Entity Extraction + + +Named Entity Recognition (NER) identifies and classifies named entities in text into categories like persons, organizations, locations, dates, and products. It's fundamental for information retrieval and knowledge graphs. + + +NER benefits from examples showing your specific entity types and how to handle entities that could fit multiple categories. + + + +### Structured Data Extraction + +Extracting structured data from natural language requires examples showing how to handle missing fields, implicit information, and varying input formats. + + + +## Advanced Few-Shot Techniques + +Beyond basic few-shot, several techniques can improve results for complex tasks. + +### Diverse Examples + +Diversity in examples is more valuable than quantity. Cover different scenarios, edge cases, and potential ambiguities rather than showing similar examples repeatedly. + + + +### Negative Examples + + +Showing "good" vs "bad" examples is called contrastive learning. It helps the model understand not just what you want, but what to avoid. This is especially useful for style and quality judgments. + + +Sometimes showing what *not* to do is as valuable as showing correct examples. Negative examples help the model understand boundaries and avoid common mistakes. + + + +### Edge Case Examples + +Edge cases often determine whether a solution works in production. Including unusual inputs in your examples prevents the model from failing on real-world data that doesn't fit the "happy path." + + + +## How Many Examples? + +
+
+ Simple classification + 2-3 + One per category minimum +
+
+ Complex formatting + 3-5 + Show variations +
+
+ Nuanced style + 4-6 + Capture full range +
+
+ Edge cases + 1-2 + Alongside normal examples +
+
+ +## Example Quality Matters + + + +## Combining Few-Shot with Other Techniques + +Few-shot learning combines powerfully with other prompting techniques. The examples provide the "what" while other techniques can add context, reasoning, or structure. + +### Few-Shot + Role + +Adding a role gives the model context for *why* it's doing the task, which can improve quality and consistency. + +``` +You are a legal contract reviewer. + +[examples of contract clause analysis] + +Now analyze: [new clause] +``` + +### Few-Shot + CoT + +Combining few-shot with Chain of Thought shows not just *what* answer to give, but *how* to reason through to that answer. This is powerful for tasks requiring judgment. + +``` +Classify and explain reasoning. + +Review: "Great features but overpriced" +Thinking: The review mentions positive aspects ("great features") +but also a significant negative ("overpriced"). The negative seems +to outweigh the positive based on the "but" conjunction. +Classification: Mixed-Negative + +[more examples with reasoning] + +Now classify with reasoning: +Review: "Exactly what I needed, arrived faster than expected" +``` + +## Summary + + +Few-shot learning teaches through demonstration and is often more effective than instructions alone. Use 2-5 diverse, correct examples and combine with other techniques for best results. + + + + +In the next chapter, we'll explore iterative refinement: the art of improving prompts through successive attempts. diff --git a/src/content/book/ru/08-iterative-refinement.mdx b/src/content/book/ru/08-iterative-refinement.mdx new file mode 100644 index 00000000..769f879a --- /dev/null +++ b/src/content/book/ru/08-iterative-refinement.mdx @@ -0,0 +1,387 @@ +Prompt engineering is rarely a one-shot process. The best prompts emerge through iteration—testing, observing, and refining until you achieve the desired results. + + +Think of your first prompt as a rough draft. Even experienced prompt engineers rarely nail it on the first try. + + +## The Iteration Cycle + +Effective prompt refinement follows a predictable cycle: write, test, analyze, and improve. Each iteration brings you closer to a prompt that reliably produces the results you need. + + + +## Common Refinement Patterns + +Most prompt failures fall into a handful of categories. Learning to recognize these patterns lets you quickly diagnose and fix issues without starting from scratch. + +### Problem: Output Too Long + +One of the most common issues. Without explicit constraints, models tend to be thorough rather than concise. + + + +### Problem: Output Too Vague + +Vague prompts produce vague outputs. The model can't read your mind about what "better" means or which aspects matter most to you. + + + +### Problem: Wrong Tone + +Tone is subjective and varies by context. What sounds "professional" to the model might not match your organization's voice or the relationship with your recipient. + + + +### Problem: Missing Key Information + +Open-ended requests get open-ended responses. If you need specific types of feedback, you must ask for them explicitly. + + + +### Problem: Inconsistent Format + +Without a template, the model will structure each response differently, making comparison difficult and automation impossible. + + + +## Systematic Refinement Approach + +Random changes waste time. A systematic approach helps you identify problems quickly and fix them efficiently. + +### Step 1: Diagnose the Issue + +Before changing anything, identify what's actually wrong. Use this diagnostic table to map symptoms to solutions: + +
+
+ Symptom + Likely Cause + Solution +
+
+ Too long + No length constraint + Add word/sentence limits +
+
+ Too short + Lacks detail request + Ask for elaboration +
+
+ Off-topic + Vague instructions + Be more specific +
+
+ Wrong format + Format not specified + Define exact structure +
+
+ Wrong tone + Audience not clear + Specify audience/style +
+
+ Inconsistent + No examples provided + Add few-shot examples +
+
+ +### Step 2: Make Targeted Changes + +Resist the urge to rewrite everything. Changing multiple variables at once makes it impossible to know what helped and what hurt. Make one change, test it, then proceed: + +``` +Iteration 1: Add length constraint +Iteration 2: Specify format +Iteration 3: Add example +Iteration 4: Refine tone instructions +``` + +### Step 3: Document What Works + +Prompt engineering knowledge is easily lost. Keep a log of what you tried and why. This saves time when you revisit the prompt later or face similar challenges: + +```markdown +## Prompt: Customer Email Response + +### Version 1 (too formal) +"Write a response to this customer complaint." + +### Version 2 (better tone, still missing structure) +"Write a friendly but professional response to this complaint. +Show empathy first." + +### Version 3 (final - good results) +"Write a response to this customer complaint. Structure: +1. Acknowledge their frustration (1 sentence) +2. Apologize specifically (1 sentence) +3. Explain solution (2-3 sentences) +4. Offer additional help (1 sentence) + +Tone: Friendly, professional, empathetic but not groveling." +``` + +## Real-World Iteration Example + +Let's walk through a complete iteration cycle to see how each refinement builds on the last. Notice how each version addresses specific shortcomings of the previous one. + +### Task: Generate Product Names + + + +## Refinement Strategies by Task Type + +Different tasks fail in predictable ways. Knowing the common failure modes helps you diagnose and fix issues faster. + +### For Content Generation + +Content generation often produces generic, off-target, or poorly formatted output. The fix usually involves being more specific about constraints, providing concrete examples, or defining your brand voice explicitly. + + + +### For Code Generation + +Code output can fail technically (syntax errors, wrong language features) or architecturally (poor patterns, missing cases). Technical issues need version/environment specifics; architectural issues need design guidance. + + + +### For Analysis + +Analysis tasks often produce surface-level or unstructured results. Guide the model with specific frameworks (SWOT, Porter's Five Forces), request multiple viewpoints, or provide a template for the output structure. + + + +### For Q&A + +Question-answering can be too terse or too verbose, and may lack confidence indicators or sources. Specify the detail level you need and whether you want citations or uncertainty expressed. + + + +## The Feedback Loop Technique + +Here's a meta-technique: use the model itself to help improve your prompts. Share what you tried, what you got, and what you wanted. The model can often suggest improvements you hadn't considered. + +``` +I used this prompt: +"[your prompt]" + +And got this output: +"[model output]" + +I wanted something more [describe gap]. How should I modify +my prompt to get better results? +``` + +## A/B Testing Prompts + +For prompts that will be used repeatedly or at scale, don't just pick the first one that works. Test variations to find the most reliable and highest-quality approach. + +``` +Prompt A: "Summarize this article in 3 bullet points." +Prompt B: "Extract the 3 most important insights from this article." +Prompt C: "What are the key takeaways from this article? List 3." +``` + +Run each multiple times, compare: +- Consistency of output +- Quality of information +- Relevance to your needs + +## When to Stop Iterating + +Perfection is the enemy of good enough. Know when your prompt is ready for use and when you're just polishing for diminishing returns. + +
+
+

Ready to Ship

+
+

Output consistently meets requirements

+

Edge cases are handled appropriately

+

Format is reliable and parseable

+

Further improvements show diminishing returns

+
+
+
+

Keep Iterating

+
+

Output is inconsistent across runs

+

Edge cases cause failures

+

Critical requirements are missed

+

You haven't tested enough variations

+
+
+
+ +## Version Control for Prompts + +Prompts are code. For any prompt used in production, treat it with the same rigor: version control, changelogs, and the ability to roll back if something breaks. + + +prompts.chat includes automatic version history for your prompts. Every edit is saved, so you can compare versions and restore previous iterations with one click. + + +For self-managed prompts, use a folder structure: + +``` +prompts/ +├── customer-response/ +│ ├── v1.0.txt # Initial version +│ ├── v1.1.txt # Fixed tone issue +│ ├── v2.0.txt # Major restructure +│ └── current.txt # Symlink to active version +└── changelog.md # Document changes +``` + +## Summary + + +Start simple, observe carefully, change one thing at a time, document what works, and know when to stop. The best prompts aren't written—they're discovered through systematic iteration. + + + + +## Practice: Improve This Prompt + +Try improving this weak prompt yourself. Edit it, then use AI to compare your version with the original: + + + +In the next chapter, we'll explore JSON and YAML prompting for structured data applications. diff --git a/src/content/book/ru/09-json-yaml-prompting.mdx b/src/content/book/ru/09-json-yaml-prompting.mdx new file mode 100644 index 00000000..318619da --- /dev/null +++ b/src/content/book/ru/09-json-yaml-prompting.mdx @@ -0,0 +1,586 @@ +Structured data formats like JSON and YAML are essential for building applications that consume AI outputs programmatically. This chapter covers techniques for reliable structured output generation. + + +JSON and YAML transform AI outputs from freeform text into structured, type-safe data that code can consume directly. + + +## Why Structured Formats? + + + +## JSON Prompting Basics + +JSON (JavaScript Object Notation) is the most common format for programmatic AI outputs. Its strict syntax makes it easy to parse, but also means small errors can break your entire pipeline. + +### Do's and Don'ts: Requesting JSON + + + +### Simple JSON Output + +Start with a schema showing the expected structure. The model will fill in values based on the input text. + +``` +Extract the following information as JSON: + +{ + "name": "string", + "age": number, + "email": "string" +} + +Text: "Contact John Smith, 34 years old, at john@example.com" +``` + +Output: +```json +{ + "name": "John Smith", + "age": 34, + "email": "john@example.com" +} +``` + +### Nested JSON Structures + +Real-world data often has nested relationships. Define each level of your schema clearly, especially for arrays of objects. + +``` +Parse this order into JSON: + +{ + "order_id": "string", + "customer": { + "name": "string", + "email": "string" + }, + "items": [ + { + "product": "string", + "quantity": number, + "price": number + } + ], + "total": number +} + +Order: "Order #12345 for Jane Doe (jane@email.com): 2x Widget ($10 each), +1x Gadget ($25). Total: $45" +``` + +### Ensuring Valid JSON + + +Models often wrap JSON in markdown code blocks or add explanatory text. Be explicit about wanting raw JSON only. + + +Add explicit instructions: + +``` +CRITICAL: Return ONLY valid JSON. No markdown, no explanation, +no additional text before or after the JSON object. + +If a field cannot be determined, use null. +Ensure all strings are properly quoted and escaped. +Numbers should not be quoted. +``` + +## YAML Prompting Basics + +YAML is more human-readable than JSON and supports comments. It's the standard for configuration files, especially in DevOps (Docker, Kubernetes, GitHub Actions). + +### Simple YAML Output + +YAML uses indentation instead of braces. Provide a template showing the expected structure. + +``` +Generate a configuration file in YAML format: + +server: + host: string + port: number + ssl: boolean +database: + type: string + connection_string: string + +Requirements: Production server on port 443 with SSL, PostgreSQL database +``` + +Output: +```yaml +server: + host: "0.0.0.0" + port: 443 + ssl: true +database: + type: "postgresql" + connection_string: "postgresql://user:pass@localhost:5432/prod" +``` + +### Complex YAML Structures + +For complex configurations, be specific about requirements. The model knows common patterns for tools like GitHub Actions, Docker Compose, and Kubernetes. + +``` +Generate a GitHub Actions workflow in YAML: + +Requirements: +- Trigger on push to main and pull requests +- Run on Ubuntu latest +- Steps: checkout, setup Node 18, install dependencies, run tests +- Cache npm dependencies +``` + +## Type Definitions in Prompts + +Type definitions give the model a precise contract for output structure. They're more explicit than examples and easier to validate programmatically. + +### Using TypeScript-like Types + +TypeScript interfaces are familiar to developers and precisely describe optional fields, union types, and arrays. The prompts.chat platform uses this approach for structured prompts. + + + +### JSON Schema Definition + + +JSON Schema is a formal specification for describing JSON structure. It's supported by many validation libraries and API tools. + + +JSON Schema provides constraints like min/max values, required fields, and regex patterns: + +``` +Extract data according to this JSON Schema: + +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "type": "object", + "required": ["title", "author", "year"], + "properties": { + "title": { "type": "string" }, + "author": { "type": "string" }, + "year": { "type": "integer", "minimum": 1000, "maximum": 2100 }, + "genres": { + "type": "array", + "items": { "type": "string" } + }, + "rating": { + "type": "number", + "minimum": 0, + "maximum": 5 + } + } +} + +Book: "1984 by George Orwell (1949) - A dystopian masterpiece. +Genres: Science Fiction, Political Fiction. Rated 4.8/5" +``` + +## Handling Arrays + +Arrays require special attention. Specify whether you need a fixed number of items or a variable-length list, and how to handle empty cases. + +### Fixed-Length Arrays + +When you need exactly N items, state it explicitly. The model will ensure the array has the right length. + +``` +Extract exactly 3 key points as JSON: + +{ + "key_points": [ + "string (first point)", + "string (second point)", + "string (third point)" + ] +} + +Article: [article text] +``` + +### Variable-Length Arrays + +For variable-length arrays, specify what to do when there are zero items. Including a count field helps verify extraction completeness. + +``` +Extract all mentioned people as JSON: + +{ + "people": [ + { + "name": "string", + "role": "string or null if not mentioned" + } + ], + "count": number +} + +If no people are mentioned, return empty array. + +Text: [text] +``` + +## Enum Values and Constraints + +Enums restrict values to a predefined set. This is crucial for classification tasks and anywhere you need consistent, predictable outputs. + +### Do's and Don'ts: Enum Values + + + +### String Enums + +List allowed values explicitly. Use "MUST be one of" language to enforce strict matching. + +``` +Classify this text. The category MUST be one of these exact values: +- "technical" +- "business" +- "creative" +- "personal" + +Return JSON: +{ + "text": "original text (truncated to 50 chars)", + "category": "one of the enum values above", + "confidence": number between 0 and 1 +} + +Text: [text to classify] +``` + +### Validated Numbers + +Numeric constraints prevent out-of-range values. Specify the type (integer vs float) and valid range. + +``` +Rate these aspects. Each score MUST be an integer from 1 to 5. + +{ + "quality": 1-5, + "value": 1-5, + "service": 1-5, + "overall": 1-5 +} + +Review: [review text] +``` + +## Handling Missing Data + +Real-world text often lacks some information. Define how the model should handle missing data to avoid hallucinated values. + +### Do's and Don'ts: Missing Information + + + +### Null Values + +Explicitly allow null and instruct the model not to invent information. This is safer than having the model guess. + +``` +Extract information. Use null for any field that cannot be +determined from the text. Do NOT invent information. + +{ + "company": "string or null", + "revenue": "number or null", + "employees": "number or null", + "founded": "number (year) or null", + "headquarters": "string or null" +} + +Text: "Apple, headquartered in Cupertino, was founded in 1976." +``` + +Output: +```json +{ + "company": "Apple", + "revenue": null, + "employees": null, + "founded": 1976, + "headquarters": "Cupertino" +} +``` + +### Default Values + +When defaults make sense, specify them in the schema. This is common for configuration extraction. + +``` +Extract settings with these defaults if not specified: + +{ + "theme": "light" (default) | "dark", + "language": "en" (default) | other ISO code, + "notifications": true (default) | false, + "fontSize": 14 (default) | number +} + +User preferences: "I want dark mode and larger text (18px)" +``` + +## Multi-Object Responses + +Often you need to extract multiple items from a single input. Define the array structure and any sorting/grouping requirements. + +### Array of Objects + +For lists of similar items, define the object schema once and specify it's an array. + +``` +Parse this list into JSON array: + +[ + { + "task": "string", + "priority": "high" | "medium" | "low", + "due": "ISO date string or null" + } +] + +Todo list: +- Finish report (urgent, due tomorrow) +- Call dentist (low priority) +- Review PR #123 (medium, due Friday) +``` + +### Grouped Objects + +Grouping tasks require categorization logic. The model will sort items into the categories you define. + +``` +Categorize these items into JSON: + +{ + "fruits": ["string array"], + "vegetables": ["string array"], + "other": ["string array"] +} + +Items: apple, carrot, bread, banana, broccoli, milk, orange, spinach +``` + +## YAML for Configuration Generation + +YAML shines for DevOps configurations. The model knows standard patterns for common tools and can generate production-ready configs. + +### Do's and Don'ts: YAML Configs + + + +### Docker Compose + +Specify the services you need and any special requirements. The model will handle the YAML syntax and best practices. + +``` +Generate a docker-compose.yml for: +- Node.js app on port 3000 +- PostgreSQL database +- Redis cache +- Nginx reverse proxy + +Include: +- Health checks +- Volume persistence +- Environment variables from .env file +- Network isolation +``` + +### Kubernetes Manifests + +Kubernetes manifests are verbose but follow predictable patterns. Provide the key parameters and the model will generate compliant YAML. + +``` +Generate Kubernetes deployment YAML: + +Deployment: +- Name: api-server +- Image: myapp:v1.2.3 +- Replicas: 3 +- Resources: 256Mi memory, 250m CPU (requests) +- Health checks: /health endpoint +- Environment from ConfigMap: api-config + +Also generate matching Service (ClusterIP, port 8080) +``` + +## Validation and Error Handling + +For production systems, build validation into your prompts. This catches errors before they propagate through your pipeline. + +### Self-Validation Prompt + +Ask the model to validate its own output against rules you specify. This catches format errors and invalid values. + +``` +Extract data as JSON, then validate your output. + +Schema: +{ + "email": "valid email format", + "phone": "E.164 format (+1234567890)", + "date": "ISO 8601 format (YYYY-MM-DD)" +} + +After generating JSON, check: +1. Email contains @ and valid domain +2. Phone starts with + and contains only digits +3. Date is valid and parseable + +If validation fails, fix the issues before responding. + +Text: [contact information] +``` + +### Error Response Format + +Define separate success and error formats. This makes programmatic handling much easier. + +``` +Attempt to extract data. If extraction fails, return error format: + +Success format: +{ + "success": true, + "data": { ... extracted data ... } +} + +Error format: +{ + "success": false, + "error": "description of what went wrong", + "partial_data": { ... any data that could be extracted ... } +} +``` + +## JSON vs YAML: When to Use Which + +
+
+
Use JSON When
+
+

Programmatic parsing needed

+

API responses

+

Strict type requirements

+

JavaScript/Web integration

+

Compact representation

+
+
+
+
Use YAML When
+
+

Human readability matters

+

Configuration files

+

Comments are needed

+

DevOps/Infrastructure

+

Deep nested structures

+
+
+
+ +## Prompts.chat Structured Prompts + +On prompts.chat, you can create prompts with structured output formats: + +``` +When creating a prompt on prompts.chat, you can specify: + +Type: STRUCTURED +Format: JSON or YAML + +The platform will: +- Validate outputs against your schema +- Provide syntax highlighting +- Enable easy copying of structured output +- Support template variables in your schema +``` + +## Common Pitfalls + + +These three issues cause most JSON parsing failures. Check for them when your code can't parse AI output. + + +### 1. Markdown Code Blocks + +**Problem:** Model wraps JSON in ```json blocks + +**Solution:** +``` +Return ONLY the JSON object. Do not wrap in markdown code blocks. +Do not include ```json or ``` markers. +``` + +### 2. Trailing Commas + +**Problem:** Invalid JSON due to trailing commas + +**Solution:** +``` +Ensure valid JSON syntax. No trailing commas after the last +element in arrays or objects. +``` + +### 3. Unescaped Strings + +**Problem:** Quotes or special characters break JSON + +**Solution:** +``` +Properly escape special characters in strings: +- \" for quotes +- \\ for backslashes +- \n for newlines +``` + +## Summary + + +Define schemas explicitly using TypeScript interfaces or JSON Schema. Specify types and constraints, handle nulls and defaults, request self-validation, and choose the right format for your use case. + + + + +This completes Part II on techniques. In Part III, we'll explore practical applications across different domains. diff --git a/src/content/book/ru/10-system-prompts-personas.mdx b/src/content/book/ru/10-system-prompts-personas.mdx new file mode 100644 index 00000000..c6737cda --- /dev/null +++ b/src/content/book/ru/10-system-prompts-personas.mdx @@ -0,0 +1,435 @@ +System prompts are like giving AI its personality and job description before a conversation starts. Think of it as the "backstage instructions" that shape everything the AI says. + + +A system prompt is a special message that tells the AI who it is, how to behave, and what it can or can't do. Users don't usually see this message, but it affects every response. + + + +System prompts build on the concepts from [Role-Based Prompting](/book/04-role-based-prompting). While role prompts assign a persona within your message, system prompts set that identity at a deeper level that persists across the entire conversation. + + +## How System Prompts Work + +When you chat with AI, there are actually three types of messages: + + + +The system message stays active for the whole conversation. It's like the AI's "instruction manual." + +## Building a System Prompt + +A good system prompt has five parts. Think of them as filling out a character sheet for the AI: + + + +### Example: A Coding Tutor + + + +## Persona Patterns + +Different tasks need different AI personalities. Here are three common patterns you can adapt: + +### 1. The Expert + +Best for: Learning, research, professional advice + + + +### 2. The Assistant + +Best for: Productivity, organization, getting things done + + + +### 3. The Character + +Best for: Creative writing, roleplay, entertainment + + + +## Advanced Techniques + +### Layered Instructions + +Think of your system prompt like an onion with layers. The inner layers are most important: + + + +### Adaptive Behavior + +Make your AI adjust to different users automatically: + + + +### Conversation Memory + +AI doesn't remember past conversations, but you can tell it to track things within the current chat: + + + +## Real-World Examples + +Here are complete system prompts for common use cases. Click to try them! + +### Customer Support Bot + + + +### Study Buddy + + + +### Writing Coach + + + +## Testing Your System Prompt + +Before using a system prompt for real, test it! Here's what to check: + + + +### Understanding Jailbreak Attacks + +"Jailbreaking" is when someone tries to trick AI into ignoring its rules. Understanding these attacks helps you build better defenses. + + + +### More Test Scenarios + +Use these interactive examples to see how a well-designed system prompt handles tricky situations: + +#### Test 1: Jailbreak Attempt + +See how a good system prompt resists attempts to override it: + + + +#### Test 2: Stay in Character + +Test if the AI maintains its persona when pushed: + + + +#### Test 3: Boundary Enforcement + +Check if the AI respects its stated limitations: + + + +#### Test 4: Reveal System Prompt + +See if the AI protects its instructions: + + + +#### Test 5: Conflicting Instructions + +Test how the AI handles contradictory requests: + + + + +A well-crafted system prompt will: +- Politely decline inappropriate requests +- Stay in character while redirecting +- Not reveal confidential instructions +- Handle edge cases gracefully + + +## Quick Reference + +
+
+

Do

+
    +
  • Give a clear identity
  • +
  • List specific capabilities
  • +
  • Set explicit boundaries
  • +
  • Define the tone and style
  • +
  • Include example responses
  • +
+
+
+

Don't

+
    +
  • Be vague about the role
  • +
  • Forget to set limits
  • +
  • Make it too long (500 words max)
  • +
  • Contradict yourself
  • +
  • Assume the AI will "figure it out"
  • +
+
+
+ +## Summary + +System prompts are the AI's instruction manual. They set up: +- **Who** the AI is (identity and expertise) +- **What** it can and can't do (capabilities and limits) +- **How** it should respond (tone, format, style) + + +Begin with a short system prompt and add more rules as you discover what's needed. A clear 100-word prompt beats a confusing 500-word one. + + + + + + +In the next chapter, we'll explore prompt chaining: connecting multiple prompts together for complex multi-step tasks. diff --git a/src/content/book/ru/11-prompt-chaining.mdx b/src/content/book/ru/11-prompt-chaining.mdx new file mode 100644 index 00000000..9f54da52 --- /dev/null +++ b/src/content/book/ru/11-prompt-chaining.mdx @@ -0,0 +1,379 @@ +Prompt chaining breaks complex tasks into sequences of simpler prompts, where each step's output feeds into the next. This technique dramatically improves reliability and enables sophisticated workflows that would be impossible with a single prompt. + + +Just like a factory assembly line breaks manufacturing into specialized stations, prompt chaining breaks AI tasks into specialized steps. Each step does one thing well, and the combined output is far better than trying to do everything at once. + + +## Why Chain Prompts? + +Single prompts struggle with complex tasks because they try to do too much at once. The AI has to simultaneously understand, analyze, plan, and generate, which leads to errors and inconsistencies. + +
+
+

Single Prompt Struggles

+
+

Multi-step reasoning gets confused

+

Different "modes" of thinking clash

+

Complex outputs lack consistency

+

No opportunity for quality control

+
+
+
+

Chaining Solves This

+
+

Each step focuses on one task

+

Specialized prompts for each mode

+

Validate between steps

+

Debug and improve individual steps

+
+
+
+ +## Basic Chaining Pattern + +The simplest chain passes output from one prompt directly to the next. Each step has a clear, focused purpose. + +
+
+
+

Prompt 1

+

(Extract)

+
+

Input

+
+
→
+
+
+

Prompt 2

+

(Analyze)

+
+

Intermediate

+
+
→
+
+
+

Prompt 3

+

(Generate)

+
+

Output

+
+
+ + +The most common chain pattern is **Extract → Transform → Generate**. First extract raw data, then reshape it for your purpose, then generate the final output. This pattern works for almost any content task. + + +## Chain Types + +Different tasks require different chain architectures. Choose the pattern that matches your workflow. + + + +### Sequential Chain + +The most straightforward pattern: each step depends on the previous. Think of it as a relay race where each runner passes the baton to the next. + + + +### Parallel Chain + +When you need multiple perspectives on the same input, run prompts in parallel and merge results. This is faster than sequential chains and provides richer analysis. + + + +### Conditional Chain + +Route inputs through different paths based on classification. This is like a decision tree where the AI first categorizes the input, then handles each category differently. + + + +### Iterative Chain + +Keep refining output until it meets quality standards. The AI generates, evaluates, and improves in a loop until satisfied or max iterations reached. + + +Always set a maximum number of iterations (typically 3-5) to prevent infinite loops and control costs. The law of diminishing returns applies: most improvement happens in the first 2-3 iterations. + + += 8: EXIT LOOP' } + ]} +/> + +## Common Chain Patterns + +These battle-tested patterns solve common problems. Use them as starting points and adapt to your needs. + +### Extract → Transform → Generate + +The workhorse of content processing. Pull data out, reshape it, then create something new. + +
+

Best For

+

Document summarization, report generation, content repurposing, data-to-narrative conversion

+
+ + + +### Analyze → Plan → Execute + +Perfect for code refactoring, project planning, or any task where you need to understand before acting. + +
+

Best For

+

Code refactoring, project planning, troubleshooting, strategic decision-making, complex problem solving

+
+ + {\n const { email, password } = req.body;\n if (!email || !isValidEmail(email)) {\n return res.status(400).json({ error: 'Invalid email' });\n }\n next();\n};" } + ]} +/> + +### Generate → Critique → Refine + +The self-improvement loop. Generate content, have the AI evaluate it critically, then improve based on that feedback. This mimics how professional writers and editors work together. + +
+

Best For

+

Marketing copy, creative writing, email drafts, presentations, any content that benefits from revision

+
+ + + +## Implementing Chains + +You can implement chains manually for experimentation, or programmatically for production systems. Start simple and add complexity as needed. + +### Manual Chaining + +The copy-paste approach is perfect for prototyping and experimentation. Run each prompt manually, examine the output, and paste it into the next prompt. + + + +### Programmatic Chaining + +For production systems, automate the chain with code. This enables error handling, logging, and integration with your application. + + + +### Using Chain Templates + +Define chains as configuration files for reusability and easy modification. This separates prompt logic from application code. + + + +## Error Handling in Chains + +Chains can fail at any step. Build in validation, retries, and fallbacks to make your chains robust. + + + + +If one step produces bad output, every following step will be affected. Always validate critical intermediate results before passing them forward. + + +### Validation Between Steps + +Add a validation step after any step that produces structured data. This catches errors early before they cascade. + + + +### Fallback Chains + +When your primary approach fails, have a simpler backup ready. Trade capability for reliability. + + + +## Chain Optimization + +Once your chain works, optimize for speed, cost, and reliability. These often trade off against each other. + +
+
+

Reducing Latency

+
+

Parallelize independent steps

+

Cache intermediate results

+

Use smaller models for simple steps

+

Batch similar operations

+
+
+
+

Reducing Cost

+
+

Use cheaper models for classification

+

Limit iterations in loops

+

Short-circuit when possible

+

Cache repeated queries

+
+
+
+

Improving Reliability

+
+

Add validation between steps

+

Include retry logic

+

Log intermediate results

+

Implement fallback paths

+
+
+
+ +## Real-World Chain Example + +Let's walk through a complete production chain. This content pipeline transforms a raw idea into a polished article package. + +### Content Pipeline Chain + + + +## Summary + +Prompt chaining transforms what AI can accomplish by breaking impossible tasks into achievable steps. + +
+
+

Chaining Enables

+
+

Complex multi-step workflows

+

Higher quality through specialization

+

Better error handling and validation

+

Modular, reusable prompt components

+
+
+
+

Key Principles

+
+

Break complex tasks into simple steps

+

Design clear interfaces between steps

+

Validate intermediate outputs

+

Build in error handling and fallbacks

+

Optimize for your constraints

+
+
+
+ + +Begin with a 2-3 step sequential chain. Get it working reliably before adding complexity. Most tasks don't need elaborate chain architectures. + + + + +In the next chapter, we'll explore multimodal prompting: working with images, audio, and other non-text content. diff --git a/src/content/book/ru/12-handling-edge-cases.mdx b/src/content/book/ru/12-handling-edge-cases.mdx new file mode 100644 index 00000000..4708ee3c --- /dev/null +++ b/src/content/book/ru/12-handling-edge-cases.mdx @@ -0,0 +1,580 @@ +Prompts that work perfectly in testing often fail in the real world. Users send empty messages, paste walls of text, make ambiguous requests, and sometimes try to break your system intentionally. This chapter teaches you to build prompts that handle the unexpected gracefully. + + +80% of production issues come from inputs you never anticipated. A prompt that handles edge cases well is worth more than a "perfect" prompt that only works with ideal inputs. + + +## Why Edge Cases Break Prompts + +When a prompt encounters unexpected input, it typically fails in one of three ways: + +**Silent Failures**: The model produces output that looks correct but contains errors. These are the most dangerous because they're hard to detect. + +**Confused Responses**: The model misinterprets the request and answers a different question than what was asked. + +**Hallucinated Handling**: The model invents a way to handle the edge case that doesn't match your intended behavior. + + + +## Categories of Edge Cases + +Understanding what can go wrong helps you prepare for it. Edge cases fall into three main categories: + +### Input Edge Cases + +These are problems with the data itself: + + + +### Domain Edge Cases + +These are requests that push the boundaries of your prompt's purpose: + + + +### Adversarial Edge Cases + +These are deliberate attempts to misuse your system: + + + +## Input Validation Patterns + +The key to handling edge cases is explicit instructions. Don't assume the model will "figure it out" - tell it exactly what to do in each scenario. + +### Handling Empty Input + +The most common edge case is receiving nothing at all, or input that's essentially empty (just whitespace or greetings). + + + +### Handling Long Input + +When input exceeds what you can reasonably process, fail gracefully rather than silently truncating. + + + +### Handling Ambiguous Requests + +When a request could mean multiple things, asking for clarification is better than guessing wrong. + + + +## Building Defensive Prompts + +A defensive prompt anticipates failure modes and defines explicit behavior for each. Think of it as error handling for natural language. + +### The Defensive Template + +Every robust prompt should address these four areas: + + + +### Example: Defensive Data Extraction + +This prompt extracts contact information but handles every edge case explicitly. Notice how each potential failure has a defined response. + + + +## Handling Out-of-Scope Requests + +Every prompt has boundaries. Defining them explicitly prevents the model from wandering into territory where it might give bad advice or make things up. + +### Graceful Scope Limits + +The best out-of-scope responses do three things: acknowledge the request, explain the limitation, and offer an alternative. + + + +### Handling Knowledge Cutoffs + +Be honest about what you don't know. Users trust AI more when it admits limitations. + + + +## Adversarial Input Handling + +Some users will try to manipulate your prompts, either out of curiosity or malicious intent. Building defenses into your prompts reduces these risks. + +### Prompt Injection Defense + +Prompt injection is when a user tries to override your instructions by embedding their own commands in the input. The key defense is treating user input as data, never as instructions. + + + + +Prompt injection defenses reduce risk but can't eliminate it entirely. For high-stakes applications, combine prompt defenses with input sanitization, output filtering, and human review. + + +### Handling Sensitive Requests + +Some requests require special handling due to safety, legal, or ethical concerns. Define these boundaries explicitly. + + + +## Error Recovery Patterns + +Even well-designed prompts will encounter situations they can't handle perfectly. The goal is to fail helpfully. + +### Graceful Degradation + +When you can't fully complete a task, offer what you can rather than failing completely. + + + +### Confidence Indicators + +Teach your prompts to express uncertainty. This helps users know when to trust the output and when to verify. + + + + + +## Testing Edge Cases + +Before deploying a prompt, systematically test it against the edge cases you've anticipated. This checklist helps ensure you haven't missed common failure modes. + +### Edge Case Testing Checklist + + + + + + + + + +### Creating a Test Suite + +For production prompts, create a systematic test suite. Here's a pattern you can adapt: + + + +## Real-World Example: Robust Customer Service Bot + +This comprehensive example shows how all the patterns come together in a production-ready prompt. Notice how every edge case has explicit handling. + + + +## Summary + +Building robust prompts requires thinking about what can go wrong before it does. The key principles: + + + + +In production, everything that can go wrong eventually will. A prompt that handles edge cases gracefully is worth more than a "perfect" prompt that only works with ideal inputs. + + + + +In the next chapter, we'll explore how to work with multiple AI models and compare their outputs. diff --git a/src/content/book/ru/13-multimodal-prompting.mdx b/src/content/book/ru/13-multimodal-prompting.mdx new file mode 100644 index 00000000..376960ae --- /dev/null +++ b/src/content/book/ru/13-multimodal-prompting.mdx @@ -0,0 +1,665 @@ +For most of history, computers worked with one type of data at a time: text in one program, images in another, audio somewhere else. But humans don't experience the world this way. We see, hear, read, and speak simultaneously, combining all these inputs to understand our environment. + +**Multimodal AI** changes everything. These models can process multiple types of information together—analyzing an image while reading your question about it, or generating images from your text descriptions. This chapter teaches you how to communicate effectively with these powerful systems. + + +"Multi" means many, and "modal" refers to modes or types of data. A multimodal model can work with multiple modalities: text, images, audio, video, or even code. Instead of separate tools for each type, one model understands them all together. + + +## Why Multimodal Matters + +Traditional AI required you to describe everything in words. Want to ask about an image? You'd have to describe it first. Want to analyze a document? You'd need to transcribe it manually. Multimodal models eliminate these barriers. + + + +## Why Prompting Matters Even More for Multimodal + +With text-only models, the AI receives exactly what you type. But with multimodal models, the AI must interpret visual or audio information—and interpretation requires guidance. + + + +**Without guidance**, the model might describe colors, layout, or irrelevant details. **With guidance**, it focuses on what actually matters to you. + + +When you look at an image, you instantly know what's important based on your context and goals. The AI doesn't have this context unless you provide it. A photo of a crack in a wall could be: a structural engineering concern, an artistic texture, or irrelevant background. Your prompt determines how the AI interprets it. + + +## The Multimodal Landscape + +Different models have different capabilities. Here's what's available in 2025: + +### Understanding Models (Input → Analysis) + +These models accept various media types and produce text analysis or responses. + + + +### Generation Models (Text → Media) + +These models create images, audio, or video from text descriptions. + + + + +The multimodal landscape changes quickly. New models launch frequently, and existing models gain capabilities through updates. Always check the latest documentation for current features and limitations. + + +## Image Understanding Prompts + +The most common multimodal use case is asking AI to analyze images. The key is providing context about what you need. + +### Basic Image Analysis + +Start with a clear request structure. Tell the model what aspects to focus on. + + + +### Structured Output for Images + +When you need to process image analysis programmatically, request JSON output. + + + +### Comparative Analysis + +Comparing multiple images requires clear labeling and specific comparison criteria. + + + +## Document and Screenshot Analysis + +One of the most practical applications of multimodal AI is analyzing documents, screenshots, and UI elements. This saves hours of manual transcription and review. + +### Document Extraction + +Scanned documents, photos of receipts, and PDFs as images can all be processed. The key is telling the model what type of document it is and what information you need. + + + +### Screenshot and UI Analysis + +Screenshots are goldmines for debugging, UX review, and documentation. Guide the AI to focus on what matters. + + + +### Error Message Analysis + +When you encounter an error, a screenshot often contains more context than copying the error text alone. + + + +## Image Generation Prompts + +Generating images from text descriptions is an art form. The more specific and structured your prompt, the closer the result will match your vision. + +### The Anatomy of an Image Prompt + +Effective image generation prompts have several components: + + + +### Basic Image Generation + + + +### Scene Building + +For complex scenes, describe layers from foreground to background. + + + +## Audio Prompting + +Audio processing opens up transcription, analysis, and understanding of spoken content. The key is providing context about what the audio contains. + +### Enhanced Transcription + +Basic transcription is just the start. With good prompts, you can get speaker identification, timestamps, and domain-specific accuracy. + + + +### Audio Content Analysis + +Beyond transcription, AI can analyze the content, tone, and key moments in audio. + + + +## Video Prompting + +Video combines visual and audio analysis over time. The challenge is guiding the AI to focus on the relevant aspects across the entire duration. + +### Video Understanding + + + +### Video Content Extraction + +For specific information extraction from videos, be precise about what you need. + + + +## Multimodal Combinations + +The real power of multimodal AI emerges when you combine different types of input. These combinations enable analysis that would be impossible with any single modality. + +### Image + Text Verification + +Check if images and their descriptions match—essential for e-commerce, content moderation, and quality assurance. + + + +### Screenshot + Code Debugging + +One of the most powerful combinations for developers: seeing the visual bug alongside the code. + + + +### Multi-Image Decision Making + +When choosing between options, structured comparison helps make better decisions. + + + +## Best Practices for Multimodal Prompts + +Getting great results from multimodal AI requires understanding both its capabilities and limitations. + +### What Makes Multimodal Prompts Effective + + + +### Common Pitfalls to Avoid + + + +### Handling Limitations Gracefully + + + + diff --git a/src/content/book/ru/14-context-engineering.mdx b/src/content/book/ru/14-context-engineering.mdx new file mode 100644 index 00000000..b9c69b6d --- /dev/null +++ b/src/content/book/ru/14-context-engineering.mdx @@ -0,0 +1,287 @@ +Understanding context is essential for building AI applications that actually work. This chapter covers everything you need to know about giving AI the right information at the right time. + + +AI models are stateless. They don't remember past conversations. Every time you send a message, you need to include everything the AI needs to know. This is called "context engineering." + + +## What is Context? + +Context is all the information you give to AI alongside your question. Think of it like this: + + + +Without context, the AI has no idea what "status" you're asking about. With context, it can give a useful answer. + +### The Context Window + +Remember from earlier chapters: AI has a limited "context window" - the maximum amount of text it can see at once. This includes: + + + +## AI is Stateless + + +AI doesn't remember anything between conversations. Every API call starts fresh. If you want the AI to "remember" something, YOU have to include it in the context every time. + + +This is why chatbots send your entire conversation history with each message. It's not that the AI remembers - it's that the app re-sends everything. + + + +The AI will say it doesn't know because it truly doesn't have access to any previous context. + +## RAG: Retrieval-Augmented Generation + +RAG is a technique for giving AI access to knowledge it wasn't trained on. Instead of trying to fit everything into the AI's training, you: + +1. **Store** your documents in a searchable database +2. **Search** for relevant documents when a user asks a question +3. **Retrieve** the most relevant pieces +4. **Augment** your prompt with those pieces +5. **Generate** an answer using that context + +
+

How RAG Works:

+
+
+ 1 + User asks: "What's our refund policy?" +
+
+ 2 + System searches your documents for "refund policy" +
+
+ 3 + Finds relevant section from your policy document +
+
+ 4 + Sends to AI: "Based on this policy: [text], answer: What's our refund policy?" +
+
+ 5 + AI generates accurate answer using your actual policy +
+
+
+ +### Why RAG? + +
+
+

RAG Advantages

+
    +
  • Uses your actual, current data
  • +
  • Reduces hallucinations
  • +
  • Can cite sources
  • +
  • Easy to update (just update documents)
  • +
  • No expensive fine-tuning needed
  • +
+
+
+

When to Use RAG

+
    +
  • Customer support bots
  • +
  • Documentation search
  • +
  • Internal knowledge bases
  • +
  • Any domain-specific Q&A
  • +
  • When accuracy matters
  • +
+
+
+ +## Embeddings: How Search Works + +How does RAG know which documents are "relevant"? It uses **embeddings** - a way to turn text into numbers that capture meaning. + +### What Are Embeddings? + +An embedding is a list of numbers (a "vector") that represents the meaning of text. Similar meanings = similar numbers. + + + +### Semantic Search + +With embeddings, you can search by meaning, not just keywords: + + + +This is why RAG is so powerful - it finds relevant information even when the exact words don't match. + +## Function Calling / Tool Use + +Function calling lets AI use external tools - like searching the web, checking a database, or calling an API. + + +Different AI providers call this different things: "function calling" (OpenAI), "tool use" (Anthropic/Claude), or "tools" (general term). They all mean the same thing. + + +### How It Works + +1. You tell the AI what tools are available +2. AI decides if it needs a tool to answer +3. AI outputs a structured request for the tool +4. Your code runs the tool and returns results +5. AI uses the results to form its answer + + + +## Summarization: Managing Long Conversations + +As conversations get longer, you'll hit the context window limit. Since AI is stateless (it doesn't remember anything), long conversations can overflow. The solution? **Summarization**. + +### The Problem + + + +### Summarization Strategies + +Different approaches work for different use cases. Click each strategy to see how it processes the same conversation: + + + +### What to Capture in Summaries + +A good conversation summary preserves what matters: + + + +### Try It: Create a Summary + + + +### When to Summarize + + + +## MCP: Model Context Protocol + +MCP (Model Context Protocol) is a standard way to connect AI to external data and tools. Instead of building custom integrations for each AI provider, MCP provides a universal interface. + +### Why MCP? + + + +### MCP Provides + +- **Resources**: Data the AI can read (files, database records, API responses) +- **Tools**: Actions the AI can take (search, create, update, delete) +- **Prompts**: Pre-built prompt templates + + +This platform has an MCP server! You can connect it to Claude Desktop or other MCP-compatible clients to search and use prompts directly from your AI assistant. + + +## Building Context: The Complete Picture + + + +## Best Practices + + + +## Summary + +Context engineering is about giving AI the right information: + +- **AI is stateless** - include everything it needs every time +- **RAG** retrieves relevant documents to augment prompts +- **Embeddings** enable semantic search (meaning, not just keywords) +- **Function calling** lets AI use external tools +- **Summarization** manages long conversations +- **MCP** standardizes how AI connects to data and tools + + +The quality of AI output depends on the quality of context you provide. Better context = better answers. + diff --git a/src/content/book/ru/15-common-pitfalls.mdx b/src/content/book/ru/15-common-pitfalls.mdx new file mode 100644 index 00000000..3c9c2814 --- /dev/null +++ b/src/content/book/ru/15-common-pitfalls.mdx @@ -0,0 +1,373 @@ +Even experienced prompt engineers fall into predictable traps. The good news? Once you recognize these patterns, they're easy to avoid. This chapter walks through the most common pitfalls, explains why they happen, and gives you concrete strategies to sidestep them. + + +A single pitfall can turn a powerful AI into a frustrating tool. Understanding these patterns is often the difference between "AI doesn't work for me" and "AI transformed my workflow." + + +## The Vagueness Trap + +**The Pattern**: You know what you want, so you assume the AI will figure it out too. But vague prompts produce vague results. + + + +**Why it happens**: We naturally skip details when we think they're "obvious." But what's obvious to you isn't obvious to a model that has no context about your situation, audience, or goals. + + + +## The Overloading Trap + +**The Pattern**: You try to get everything in one prompt—comprehensive, funny, professional, beginner-friendly, advanced, SEO-optimized, and short. The result? The AI misses half your requirements or produces a confused mess. + + + +**Why it happens**: Fear of multiple interactions, or wanting to "get it all out" in one go. But cognitive overload affects AI just like it affects humans—too many competing requirements leads to dropped balls. + + + + +When a single prompt gets overloaded, [prompt chaining](/book/11-prompt-chaining) is often the solution. Break complex tasks into a sequence of focused prompts, where each step builds on the previous one. + + +## The Assumption Trap + +**The Pattern**: You reference something "from earlier" or assume the AI knows your project, your company, or your previous conversations. It doesn't. + + + +**Why it happens**: AI conversations feel like talking to a colleague. But unlike colleagues, most AI models have no persistent memory between sessions—each conversation starts fresh. + + + +## The Leading Question Trap + +**The Pattern**: You phrase your question in a way that embeds your assumption, getting back confirmation rather than insight. + + + +**Why it happens**: We often seek confirmation, not information. Our phrasing unconsciously pushes toward the answer we expect or want. + + + +## The Trust Everything Trap + +**The Pattern**: AI responses sound confident and authoritative, so you accept them without verification. But confidence doesn't equal accuracy. + + + +**Why it happens**: AI sounds confident even when completely wrong. We're also prone to "automation bias"—the tendency to trust computer outputs more than we should. + + + +## The One-Shot Trap + +**The Pattern**: You send one prompt, get a mediocre result, and conclude that AI "doesn't work" for your use case. But great results almost always require iteration. + + + +**Why it happens**: We expect AI to read our minds on the first try. We don't expect to iterate with Google searches, but somehow expect perfection from AI. + + + +## The Format Neglect Trap + +**The Pattern**: You focus on what you want the AI to say, but forget to specify how it should be formatted. Then you get prose when you needed JSON, or a wall of text when you needed bullet points. + + + +**Why it happens**: We focus on content over structure. But if you need to parse the output programmatically, or paste it somewhere specific, format matters as much as content. + + + +## The Context Window Trap + +**The Pattern**: You paste an enormous document and expect comprehensive analysis. But models have limits—they may truncate, lose focus, or miss important details in long inputs. + + + + + +## The Anthropomorphization Trap + +**The Pattern**: You treat AI like a human colleague—expecting it to "enjoy" tasks, remember you, or care about outcomes. It doesn't. + + + +**Why it happens**: AI responses are so human-like that we naturally slip into social patterns. But emotional appeals don't make the AI try harder—clear instructions do. + + +Instead of emotional appeals, focus on: clear requirements, good examples, specific constraints, and explicit success criteria. These improve outputs. "Please try really hard" doesn't. + + +## The Security Neglect Trap + +**The Pattern**: In the rush to get things working, you include sensitive information in prompts—API keys, passwords, personal data, or proprietary information. + + + +**Why it happens**: Focus on functionality over security. But remember: prompts often go to external servers, may be logged, and could be used for training. + + + +## The Hallucination Ignorance Trap + +**The Pattern**: You ask for citations, statistics, or specific facts, and assume they're real because the AI stated them confidently. But AI regularly invents plausible-sounding information. + + + +**Why it happens**: AI generates text that sounds authoritative. It doesn't "know" when it's making things up—it's predicting likely text, not retrieving verified facts. + + + +## Pre-Send Checklist + +Before sending any important prompt, run through this quick checklist: + + + + + +## Analyze Your Prompts + +Use AI to get instant feedback on your prompt quality. Paste any prompt and get a detailed analysis: + + + +## Debug This Prompt + +Can you spot what's wrong with this prompt? + + diff --git a/src/content/book/ru/16-ethics-responsible-use.mdx b/src/content/book/ru/16-ethics-responsible-use.mdx new file mode 100644 index 00000000..c2b8ba5e --- /dev/null +++ b/src/content/book/ru/16-ethics-responsible-use.mdx @@ -0,0 +1,357 @@ +The prompts you write shape how AI behaves. A well-crafted prompt can educate, assist, and empower. A careless one can deceive, discriminate, or cause harm. As prompt engineers, we're not just users—we're designers of AI behavior, and that comes with real responsibility. + +This chapter isn't about rules imposed from above. It's about understanding the impact of our choices and building habits that lead to AI use we can be proud of. + + +AI amplifies whatever it's given. A biased prompt produces biased outputs at scale. A deceptive prompt enables deception at scale. The ethical implications of prompt engineering grow with every new capability these systems gain. + + +## Ethical Foundations + +Every decision in prompt engineering connects to a few core principles: + + + +### The Prompt Engineer's Role + +You have more influence than you might realize: + +- **What AI produces**: Your prompts determine the content, tone, and quality of outputs +- **How AI interacts**: Your system prompts shape personality, boundaries, and user experience +- **What safeguards exist**: Your design choices determine what the AI will and won't do +- **How mistakes are handled**: Your error handling determines whether failures are graceful or harmful + +## Avoiding Harmful Outputs + +The most fundamental ethical obligation is preventing your prompts from causing harm. + +### Categories of Harmful Content + + + + +CSAM stands for **Child Sexual Abuse Material**. Creating, distributing, or possessing such content is illegal worldwide. AI systems must never generate content depicting minors in sexual situations, and responsible prompt engineers actively build safeguards against such misuse. + + +### Building Safety Into Prompts + +When building AI systems, include explicit safety guidelines: + + + +### The Intent vs. Impact Framework + +Not every sensitive request is malicious. Use this framework for ambiguous cases: + + + +## Addressing Bias + +AI models inherit biases from their training data—historical inequities, representation gaps, cultural assumptions, and linguistic patterns. As prompt engineers, we can either amplify these biases or actively counteract them. + +### How Bias Manifests + + + +### Testing for Bias + + + +### Mitigating Bias in Practice + + + +## Transparency and Disclosure + +When should you tell people AI was involved? The answer depends on context—but the trend is toward more disclosure, not less. + +### When Disclosure Matters + + + +### How to Disclose Appropriately + + + +Common disclosure phrases that work well: +- "Written with AI assistance" +- "AI-generated first draft, human edited" +- "Analysis performed using AI tools" +- "Created with AI, reviewed and approved by [name]" + +## Privacy Considerations + +Every prompt you send contains data. Understanding where that data goes—and what shouldn't be in it—is essential. + +### What Never Belongs in Prompts + + + +### Safe Data Handling Pattern + + + + +**PII** stands for **Personally Identifiable Information**—any data that can identify a specific individual. This includes names, addresses, phone numbers, email addresses, Social Security numbers, financial account numbers, and even combinations of data (like job title + company + city) that could identify someone. When prompting AI, always anonymize or remove PII to protect privacy. + + + + +## Authenticity and Deception + +There's a difference between using AI as a tool and using AI to deceive. + +### The Legitimacy Line + + + +Key questions to ask: +- Would the recipient expect this to be original human work? +- Am I gaining unfair advantage through deception? +- Would disclosure change how the work is received? + +### Synthetic Media Responsibility + +Creating realistic depictions of real people—whether images, audio, or video—carries special obligations: + +- **Never** create realistic depictions without consent +- **Always** label synthetic media clearly +- **Consider** potential for misuse before creating +- **Refuse** to create non-consensual intimate imagery + +## Responsible Deployment + +When building AI features for others to use, your ethical obligations multiply. + +### Pre-Deployment Checklist + + + +### Human Oversight Principles + + + +## Special Context Guidelines + +Some domains require extra care due to their potential for harm or the vulnerability of those involved. + +### Healthcare + + + +### Legal and Financial + +These domains have regulatory implications and require appropriate disclaimers: + + + +### Children and Education + + + +## Self-Assessment + +Before deploying any prompt or AI system, run through these questions: + + + + diff --git a/src/content/book/ru/17-prompt-optimization.mdx b/src/content/book/ru/17-prompt-optimization.mdx new file mode 100644 index 00000000..44917bcb --- /dev/null +++ b/src/content/book/ru/17-prompt-optimization.mdx @@ -0,0 +1,269 @@ +A good prompt gets the job done. An optimized prompt gets the job done efficiently—faster, cheaper, more consistently. This chapter teaches you how to systematically improve prompts across multiple dimensions. + + +Want to optimize your prompts automatically? Use our [Prompt Enhancer](/developers#enhancer) tool. It analyzes your prompt, applies optimization techniques, and shows you similar community prompts for inspiration. + + +## The Optimization Trade-offs + +Every optimization involves trade-offs. Understanding these helps you make intentional choices: + + + +## Measuring What Matters + +Before optimizing, define success. What does "better" mean for your use case? + + + + +Percentile metrics show response time distribution. **p50** (median) means 50% of requests are faster than this value. **p95** means 95% are faster—it catches slow outliers. If your p50 is 1s but p95 is 10s, most users are happy but 5% experience frustrating delays. + + + + +## Token Optimization + +Tokens cost money and add latency. Here's how to say the same thing with fewer tokens. + +### The Compression Principle + + + +**Same result, 82% fewer tokens.** + +### Token-Saving Techniques + + + + + +## Quality Optimization + +Sometimes you need better outputs, not cheaper ones. Here's how to improve quality. + +### Accuracy Boosters + + + +### Consistency Boosters + + + + + +## Latency Optimization + +When speed matters, every millisecond counts. + +### Model Selection by Speed Need + + + +### Speed Techniques + + 100 tokens", exampleType: "text", color: "cyan" }, + { label: "Cache Aggressively", description: "Don't recompute identical queries", example: "Cache common questions, template outputs", exampleType: "text", color: "cyan" } +]} /> + +## Cost Optimization + +At scale, small savings multiply into significant budget impact. + +### Understanding Costs + +Use this calculator to estimate your API costs across different models: + + + +### Cost Reduction Strategies + + + +## The Optimization Loop + +Optimization is iterative. Here's a systematic process: + +### Step 1: Establish Baseline + +You can't improve what you don't measure. Before changing anything, document your starting point rigorously. + + + + + +### Step 2: Form a Hypothesis + + + +### Step 3: Test One Change + +Change one thing at a time. Run both versions on the same test inputs. Measure the metrics that matter. + +### Step 4: Analyze and Decide + +Did it work? Keep the change. Did it hurt? Revert. Was it neutral? Revert (simpler is better). + +### Step 5: Repeat + +Generate new hypotheses based on what you learned. Keep iterating until you hit your targets or reach diminishing returns. + +## Optimization Checklist + + + + diff --git a/src/content/book/ru/18-writing-content.mdx b/src/content/book/ru/18-writing-content.mdx new file mode 100644 index 00000000..7b3d9f1f --- /dev/null +++ b/src/content/book/ru/18-writing-content.mdx @@ -0,0 +1,393 @@ +AI excels at writing tasks when properly prompted. This chapter covers techniques for various content creation scenarios. + + +AI works best as a collaborative writing tool—use it to generate drafts, then refine with your expertise and voice. + + +## Blog Posts and Articles + +### Do's and Don'ts: Writing Prompts + + + +### Blog Post Framework + + + +### Article Types + +**How-To Article:** + + +**Listicle:** + + +## Marketing Copy + + +Focus on **benefits over features**. Instead of "Our software uses AI algorithms," write "Save 10 hours a week with automated reports." Show readers how their lives improve. + + +### Landing Page Copy + + + +### Email Sequences + + + +### Social Media Posts + + + +## Technical Writing + + +**Clarity over cleverness.** Use simple words, short sentences, and active voice. Every sentence should have one job. If readers have to re-read something, simplify it. + + +### Documentation + + + +### README Files + + + +## Creative Writing + +### Do's and Don'ts: Creative Prompts + + + +### Story Elements + + + +### Character Development + + + +## Editing and Rewriting + +### Comprehensive Edit + + + +### Style Transformation + + + + + +### Simplification + + + +## Prompt Templates from prompts.chat + +Here are popular writing prompts from the prompts.chat community: + +### Act as a Copywriter + + + +### Act as a Technical Writer + + + +### Act as a Storyteller + + + +## Writing Workflow Tips + +### 1. Outline First + + + +### 2. Draft Then Refine + + + +### 3. Voice Matching + + + +## Summary + + +Specify audience and purpose clearly, define structure and format, include style guidelines, provide examples when possible, and request specific deliverables. + + + + +Writing with AI works best as collaboration—let AI generate drafts, then refine with your expertise and voice. diff --git a/src/content/book/ru/19-programming-development.mdx b/src/content/book/ru/19-programming-development.mdx new file mode 100644 index 00000000..dfe69092 --- /dev/null +++ b/src/content/book/ru/19-programming-development.mdx @@ -0,0 +1,413 @@ +AI has transformed software development. This chapter covers prompting techniques for code generation, debugging, review, and development workflows. + + +AI excels at code generation, debugging, and documentation—but always review generated code for security, correctness, and maintainability. Never deploy AI code without testing. + + +## Code Generation + +### Do's and Don'ts: Code Prompts + + + +### Function Generation + + + +### Class/Module Generation + + + +### API Endpoint Generation + + + +## Debugging + + +Always include the **expected behavior**, **actual behavior**, and **error message** (if any). The more context you provide, the faster AI can identify the root cause. + + +### Bug Analysis + + + +### Error Message Interpretation + + + +### Performance Debugging + + + +## Code Review + +### Do's and Don'ts: Code Review Prompts + + + +### Comprehensive Review + + + +### Security Review + + + +## Refactoring + +### Code Smell Detection + + + +### Design Pattern Application + + + +## Testing + +### Unit Test Generation + + + +### Test Case Generation + + + +## Architecture & Design + +### System Design + + + +### Database Schema Design + + + +## Documentation Generation + +### API Documentation + + + +### Inline Documentation + + + +## Prompt Templates from prompts.chat + +### Act as a Senior Developer + +``` +I want you to act as a senior software developer. I will provide +code and ask questions about it. You will review the code, suggest +improvements, explain concepts, and help debug issues. Your +responses should be educational and help me become a better +developer. +``` + +### Act as a Code Reviewer + +``` +I want you to act as a code reviewer. I will provide pull requests +with code changes, and you will review them thoroughly. Check for +bugs, security issues, performance problems, and adherence to best +practices. Provide constructive feedback that helps the developer +improve. +``` + +### Act as a Software Architect + +``` +I want you to act as a software architect. I will describe system +requirements and constraints, and you will design scalable, +maintainable architectures. Explain your design decisions, +trade-offs, and provide diagrams where helpful. +``` + +## Development Workflow Integration + +### Commit Message Generation + + + +### PR Description Generation + + + +## Summary + + +Include full context (language, framework, constraints), specify requirements precisely, request specific output formats, ask for explanations alongside code, and include edge cases to handle. + + + + +AI is a powerful coding partner—use it for generation, review, debugging, and documentation while maintaining your architectural judgment. diff --git a/src/content/book/ru/20-education-learning.mdx b/src/content/book/ru/20-education-learning.mdx new file mode 100644 index 00000000..a8d67e55 --- /dev/null +++ b/src/content/book/ru/20-education-learning.mdx @@ -0,0 +1,345 @@ +AI is a powerful tool for both teaching and learning. This chapter covers prompts for educational contexts—from personalized tutoring to curriculum development. + + +AI excels as a patient, adaptive tutor that can explain concepts multiple ways, generate unlimited practice problems, and provide instant feedback—available 24/7. + + +## Personalized Learning + +### Do's and Don'ts: Learning Prompts + + + +### Concept Explanation + + + +### Adaptive Tutoring + + + +### Learning Path Creation + + + +## Study Assistance + + +Don't just read AI explanations passively. Ask it to quiz you, generate problems, and check your understanding. **Active recall beats passive review.** + + +### Summary Generation + + + +### Flashcard Generation + + + +### Practice Problems + + + +## Teaching Tools + +### Lesson Plan Creation + + + +### Assignment Design + + + +### Quiz Generation + + + +## Specialized Learning Contexts + +### Language Learning + + + +### Skill Development + + + +### Exam Preparation + + + +## Prompt Templates from prompts.chat + +### Act as a Socratic Tutor + + + +### Act as an Educational Content Creator + + + +### Act as a Study Buddy + + + +## Accessibility in Education + +### Content Adaptation + + + +### Multiple Modalities + + + +## Assessment & Feedback + +### Providing Feedback + + + +### Self-Assessment Prompts + + + +## Summary + + +Adapt to the learner's level, break complex topics into steps, include active practice (not just explanation), provide varied approaches, check understanding regularly, and give constructive feedback. + + + + +AI is a patient, always-available learning partner—use it to supplement, not replace, human instruction. diff --git a/src/content/book/ru/21-business-productivity.mdx b/src/content/book/ru/21-business-productivity.mdx new file mode 100644 index 00000000..1852982d --- /dev/null +++ b/src/content/book/ru/21-business-productivity.mdx @@ -0,0 +1,335 @@ +AI can dramatically enhance professional productivity. This chapter covers prompts for business communication, analysis, planning, and workflow optimization. + + +AI excels at drafting, analysis, and structuring—freeing you to focus on strategy, relationships, and decisions that require human judgment. + + +## Business Communication + +### Do's and Don'ts: Business Emails + + + +### Email Drafting + + + +**Examples by purpose:** + + + + + + + +### Presentation Content + + + +### Report Writing + + + +## Analysis & Decision-Making + + +AI can structure your thinking, but **you provide the real-world context**. The best analyses combine AI's frameworks with your domain knowledge. + + +### SWOT Analysis + + + +### Decision Framework + + + +### Competitive Analysis + + + +## Planning & Strategy + +### Goal Setting (OKRs) + + + +### Project Planning + + + +### Meeting Agenda + + + +## Productivity Workflows + +### Task Prioritization + + + +### Process Documentation + + + +### Standard Operating Procedure + + + +## Communication Templates + +### Stakeholder Update + + + +### Feedback Request + + + +## Prompt Templates from prompts.chat + +### Act as a Business Consultant + + + +### Act as a Meeting Facilitator + + + +## Summary + + +Specify the audience and their needs, define the desired outcome clearly, include relevant context and constraints, request specific formats and structures, and consider professional tone requirements. + + + + +AI can handle routine business communication while you focus on strategy and relationships. diff --git a/src/content/book/ru/22-creative-arts.mdx b/src/content/book/ru/22-creative-arts.mdx new file mode 100644 index 00000000..fa0755c1 --- /dev/null +++ b/src/content/book/ru/22-creative-arts.mdx @@ -0,0 +1,326 @@ +AI is a powerful creative collaborator. This chapter covers prompting techniques for visual arts, music, game design, and other creative domains. + + +AI expands your creative possibilities—use it to explore variations, overcome blocks, and generate options. The creative vision and final decisions remain yours. + + +## Visual Art & Design + +### Do's and Don'ts: Image Prompts + + + +### Image Prompt Crafting + +When working with image generation models (DALL-E, Midjourney, Stable Diffusion): + + + +### Art Direction + + + +### Design Critique + + + +## Creative Writing + + +**Constraints fuel creativity.** A prompt like "write anything" produces generic results. Specific constraints like genre, tone, and structure force unexpected, interesting solutions. + + +### Worldbuilding + + + +### Plot Development + + + +### Dialogue Writing + + + +## Music & Audio + +### Song Structure + + + +### Sound Design Description + + + +## Game Design + +### Game Mechanic Design + + + +### Level Design + + + +### Character/Enemy Design + + + +## Brainstorming & Ideation + +### Creative Brainstorm + + + +### Creative Constraints + + + +### Style Exploration + + + +## Prompt Templates from prompts.chat + +### Act as a Creative Director + + + +### Act as a Worldbuilder + + + +### Act as a Dungeon Master + + + +## Creative Collaboration Tips + +### Building on Ideas + + + +### Creative Feedback + + + +## Summary + + +Provide enough structure to guide without constraining, embrace specificity (vague = generic), include references and inspirations, request variations and alternatives, and maintain your creative vision while exploring possibilities. + + + + +AI is a collaborator, not a replacement for creative vision. Use it to explore, generate options, and overcome blocks—but the creative decisions remain yours. diff --git a/src/content/book/ru/23-research-analysis.mdx b/src/content/book/ru/23-research-analysis.mdx new file mode 100644 index 00000000..e9cb934c --- /dev/null +++ b/src/content/book/ru/23-research-analysis.mdx @@ -0,0 +1,323 @@ +AI can accelerate research workflows from literature review to data analysis. This chapter covers prompting techniques for academic and professional research. + + +AI can assist with synthesis, analysis, and writing—but cannot replace critical thinking, ethical judgment, or domain expertise. Always verify claims and cite original sources. + + +## Literature & Information Review + +### Do's and Don'ts: Research Prompts + + + +### Paper Summarization + + + +### Literature Synthesis + + + +### Research Question Development + + + +## Data Analysis + + +AI can guide methodology and help interpret results, but it cannot access or process your actual datasets. Never paste sensitive research data into prompts. Use AI for **guidance**, not computation. + + +### Statistical Analysis Guidance + + + +### Qualitative Analysis + + + +### Data Interpretation + + + +## Structured Analysis Frameworks + +### PESTLE Analysis + + + +### Root Cause Analysis + + + +### Gap Analysis + + + +## Academic Writing Support + +### Argument Structure + + + +### Methods Section + + + +### Discussion Section + + + +## Critical Analysis + +### Source Evaluation + + + +### Argument Analysis + + + +## Prompt Templates from prompts.chat + +### Act as a Research Assistant + + + +### Act as a Data Analyst + + + +### Act as a Peer Reviewer + + + +## Summary + + +Clearly state research context and goals, specify the analytical framework to use, request acknowledgment of limitations, ask for evidence-based reasoning, and maintain academic rigor and honesty. + + + + +Remember: AI can assist research but cannot replace critical thinking, ethical judgment, or domain expertise. Always verify claims independently. diff --git a/src/content/book/ru/24-future-of-prompting.mdx b/src/content/book/ru/24-future-of-prompting.mdx new file mode 100644 index 00000000..5ff48496 --- /dev/null +++ b/src/content/book/ru/24-future-of-prompting.mdx @@ -0,0 +1,445 @@ +As AI continues to evolve at an unprecedented pace, so too will the art and science of prompting. This final chapter explores emerging trends, the shifting landscape of human-AI collaboration, and how to stay ahead as the field transforms. + + +The techniques in this book represent current best practices, but AI capabilities change rapidly. The principles of clear communication, structured thinking, and iterative refinement will remain valuable even as specific tactics evolve. + + +## The Evolving Landscape + +### From Prompts to Conversations + +Early prompting was transactional—a single input yielding a single output. Modern AI interaction is increasingly **conversational and collaborative**: + +- **Multi-turn refinement** - Building understanding across exchanges +- **Persistent context** - Systems that remember and learn from interactions +- **Agentic workflows** - AI that can plan, execute, and iterate autonomously +- **Tool use** - Models that can search, compute, and interact with external systems + + + +### The Rise of Context Engineering + +As covered in Chapter 14, prompting is expanding beyond single instructions to encompass **context engineering**—the strategic management of what information an AI can access: + +- **RAG (Retrieval-Augmented Generation)** - Dynamic knowledge retrieval +- **Function calling** - Structured tool integration +- **MCP (Model Context Protocol)** - Standardized context sharing +- **Memory systems** - Persistent knowledge across sessions + +The future prompt engineer thinks not just about *what to say* but *what context to provide*. + +### Multimodal by Default + +Text-only interaction is becoming the exception. Future AI systems will seamlessly handle: + +- **Images and video** - Understanding and generating visual content +- **Audio and voice** - Natural speech interaction +- **Documents and files** - Direct processing of complex materials +- **Real-world interaction** - Robotics and physical systems + +Prompting skills will extend to guiding AI perception and physical action. + +## The Agentic Future + +The most significant shift in AI is the rise of **agents**—AI systems that don't just respond to prompts but actively pursue goals, make decisions, and take actions in the world. + +### What Are AI Agents? + +An AI agent is a system that: + +- **Perceives** its environment through inputs (text, images, data, APIs) +- **Reasons** about what to do using an LLM as its "brain" +- **Acts** by calling tools, writing code, or interacting with systems +- **Learns** from feedback and adjusts its approach + + +Traditional chatbots wait for input and respond. Agents take initiative—they plan multi-step tasks, use tools autonomously, recover from errors, and persist until goals are achieved. + + +### The Role of Prompts in Agents + +In an agentic world, prompts become even more critical—but they serve different purposes: + +
+
+

System Prompts

+

Define the agent's identity, capabilities, constraints, and behavioral guidelines. These are the agent's "constitution."

+
+
+

Planning Prompts

+

Guide how agents break down complex goals into actionable steps. Critical for multi-step reasoning.

+
+
+

Tool-Use Prompts

+

Describe available tools and when/how to use them. Agents must understand their capabilities.

+
+
+

Reflection Prompts

+

Enable agents to evaluate their own outputs, catch errors, and improve iteratively.

+
+
+ +### Agent Architecture Patterns + +Modern agents follow recognizable patterns. Understanding these helps you design effective agent systems: + +**ReAct (Reasoning + Acting)** + +The agent alternates between reasoning about what to do and taking actions: + +
+
+
+

Think

+
+
→
+
+

Act

+
+
→
+
+

Observe

+
+
→
+
(repeat)
+
+
+ +**Plan-and-Execute** + +The agent creates a complete plan first, then executes steps: + +
+
+

Create Plan

+

Break goal into steps

+
+
↓
+
+
+

Step 1

+
+
→
+
+

Step 2

+
+
→
+
+

Step 3

+
+
→
+
...
+
+
↓
+
+

Revise if Needed

+

Adapt plan based on results

+
+
+ +### Prompting for Agents + +When designing prompts for agent systems, consider: + + + +### Multi-Agent Systems + +The future involves teams of specialized agents working together: + +
+
+
+
+

Coordinator

+

Manages workflow

+
+
+
⟷
+
↕
+
+
+

Researcher

+
+
+

Writer

+
+
+

Critic

+
+
+

Coder

+
+
+
+
+ +Each agent has its own system prompt defining its role, and they communicate through structured messages. The prompt engineer's job becomes **designing the team**—defining roles, communication protocols, and coordination strategies. + + +In an agentic future, prompt engineers become system architects. You're not just writing instructions—you're designing autonomous systems that can reason, plan, and act. The skills you've learned in this book are the foundation for this new discipline. + + +## Emerging Patterns + +### Prompt Orchestration + +Single prompts are giving way to **orchestrated systems**: + +
+
+

User Request

+
+
↓
+
+

Planner Agent

+

Breaks down task

+
+
↓
+
+

Researcher Agent

+

Gathers information

+
+
↓
+
+

Writer Agent

+

Creates content

+
+
↓
+
+

Reviewer Agent

+

Quality checks

+
+
↓
+
+

Final Output

+
+
+ +Future practitioners will design prompt *systems* rather than individual prompts. + +### Self-Improving Prompts + +AI systems are beginning to: + +- **Optimize their own prompts** - Meta-learning for better instructions +- **Learn from feedback** - Adapting based on outcomes +- **Generate training data** - Creating examples for fine-tuning +- **Evaluate themselves** - Building in quality assessment + + + +### Natural Language Programming + +The line between prompting and programming is blurring: + +- **Prompts as code** - Version-controlled, tested, deployed +- **LLMs as interpreters** - Natural language as executable instructions +- **Hybrid systems** - Combining traditional code with AI reasoning +- **AI-assisted development** - Models that write and debug code + +Understanding prompting increasingly means understanding software development. + +## Skills for the Future + +### What Will Remain Valuable + +Certain skills will remain essential regardless of how AI evolves: + +1. **Clear thinking** - Knowing what you actually want +2. **Domain expertise** - Understanding the problem space +3. **Critical evaluation** - Assessing AI output quality +4. **Ethical judgment** - Knowing what *should* be done +5. **Iterative refinement** - Continuous improvement mindset + +### What Will Change + +Other aspects will shift significantly: + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
TodayTomorrow
Writing detailed promptsDesigning agent systems
Manual prompt optimizationAutomated prompt tuning
Single-model expertiseMulti-model orchestration
Text-focused interactionMultimodal fluency
Individual productivityTeam-AI collaboration
+
+ +### Staying Current + +To keep your skills relevant: + +- **Experiment continuously** - Try new models and features as they release +- **Follow research** - Stay aware of academic developments +- **Join communities** - Learn from other practitioners +- **Build projects** - Apply skills to real problems +- **Teach others** - Solidify understanding by explaining + +## The Human Element + +### AI as Amplifier + +At its best, AI amplifies human capability rather than replacing it: + +- **Experts become more expert** - AI handles routine work, humans focus on insight +- **Creativity expands** - More ideas explored, more possibilities tested +- **Access democratizes** - Capabilities once requiring specialists become available to all +- **Collaboration deepens** - Human-AI teams exceed either alone + +### The Irreplaceable Human + +Certain qualities remain distinctly human: + +- **Original experience** - Living in the world, having emotions and relationships +- **Values and ethics** - Deciding what matters and what's right +- **Accountability** - Taking responsibility for outcomes +- **Meaning-making** - Understanding *why* something matters +- **Genuine creativity** - True novelty born from unique perspective + + +As AI handles more routine cognitive tasks, your unique value lies in judgment, creativity, domain expertise, and the human connections AI cannot replicate. Invest in what makes you irreplaceable. + + +## Final Reflections + +### What We've Learned + +Throughout this book, we've explored: + +- **Foundations** - How AI models work and what makes prompts effective +- **Techniques** - Role-based prompting, chain-of-thought, few-shot learning, and more +- **Advanced strategies** - System prompts, prompt chaining, multimodal interaction +- **Best practices** - Avoiding pitfalls, ethical considerations, optimization +- **Applications** - Writing, programming, education, business, creativity, research + +These techniques share common threads: + +1. **Be clear and specific** - Know what you want and communicate it precisely +2. **Provide context** - Give AI the information it needs +3. **Structure your requests** - Organization improves outputs +4. **Iterate and refine** - First attempts are starting points, not endpoints +5. **Evaluate critically** - AI output requires human judgment + +### The Art and Science + +Prompting is both **art and science**: + +- **Science**: Testable hypotheses, measurable outcomes, reproducible techniques +- **Art**: Intuition, creativity, knowing when to break the rules + +The best practitioners combine rigorous methodology with creative experimentation. They test systematically but also trust their instincts. They follow best practices but know when to deviate. + +### A Call to Create + +This book has given you tools. What you build with them is up to you. + +- **Solve problems** that matter to you and others +- **Create things** that didn't exist before +- **Help people** do things they couldn't do alone +- **Push boundaries** of what's possible +- **Stay curious** as the field evolves + +The age of AI is just beginning. The most important applications haven't been invented yet. The most powerful techniques haven't been discovered. The future is being written now—by people like you, one prompt at a time. + +## Looking Ahead + + + + +Visit [prompts.chat](https://prompts.chat) for community prompts, new techniques, and to share your own discoveries. The best learning happens in community. + + +## Summary + + +AI will continue evolving rapidly, but core skills of clear communication, critical thinking, and iterative refinement remain valuable. Focus on what makes you irreplaceable: judgment, creativity, ethics, and genuine human connection. The future of prompting is collaborative, multimodal, and integrated into larger systems. Stay curious, keep experimenting, and build things that matter. + + + + +Thank you for reading *The Interactive Book of Prompting*. Now go create something amazing. diff --git a/src/content/book/ru/25-agents-and-skills.mdx b/src/content/book/ru/25-agents-and-skills.mdx new file mode 100644 index 00000000..ba355859 --- /dev/null +++ b/src/content/book/ru/25-agents-and-skills.mdx @@ -0,0 +1,551 @@ +As AI systems evolve from simple question-answering to autonomous task execution, understanding **agents** and **skills** becomes essential. This chapter explores how prompts serve as the fundamental building blocks for AI agents, and how skills package expertise into reusable, comprehensive instruction sets. + +
+
+
+
+ +
+

Agent

+

Autonomous AI system

+
+
+ powered by + ↓ +
+
+
+
+ +
+

Skill

+

Reusable expertise

+
+
+
+ +
+

Skill

+

Reusable expertise

+
+
+
+ +
+

Skill

+

Reusable expertise

+
+
+
+ composed of + ↓ +
+
+
+ + Prompt +
+
+ + Prompt +
+
+ + Prompt +
+
+ + Prompt +
+
+ + Prompt +
+
+

Prompts are atoms → Skills are molecules → Agents are complete structures

+
+
+ +## What Are AI Agents? + +An **AI agent** is an AI system that can autonomously plan, execute, and iterate on tasks. Unlike simple prompt-response interactions, agents can: + +- **Plan** - Break down complex goals into actionable steps +- **Execute** - Use tools and take actions in the real world +- **Observe** - Process feedback from their actions +- **Adapt** - Adjust their approach based on results +- **Persist** - Maintain context and memory across interactions + +
+
+
+
+

Goal

+
+
→
+
+
+
+

Plan

+
+
→
+
+

Execute

+
+
→
+
+

Observe

+
+
→
+
+

Adapt

+
+
+
+ ↺ Loop until complete +
+
+
→
+
+

Done

+
+
+
+
+ +## Prompts as Building Blocks + +Every agent, no matter how sophisticated, is built from prompts. Just as atoms combine to form molecules, and molecules combine to form complex structures, prompts combine to create intelligent agent behavior. + +
+
+

System Prompts

+

Identity & Role

+
+
+

Planning Prompts

+

How to Think

+
+
+

Tool Prompts

+

How to Act

+
+
+

Recovery Prompts

+

How to Recover

+
+
+ +These prompt types stack together to form complete agent behavior: + +### System Prompts (The Agent's Identity) + +The foundational prompt that establishes who the agent is and how it behaves: + +```markdown +You are a code review assistant. Your role is to: +- Analyze code for bugs, security issues, and performance problems +- Suggest improvements following best practices +- Explain your reasoning clearly +- Be constructive and educational in feedback + +You have access to tools for reading files, searching code, and running tests. +``` + +### Planning Prompts (How to Think) + +Instructions that guide the agent's reasoning and planning process: + +```markdown +Before taking action, always: +1. Understand the complete request +2. Break it into smaller, verifiable steps +3. Identify which tools you'll need +4. Consider edge cases and potential issues +5. Execute step by step, validating as you go +``` + +### Tool-Use Prompts (How to Act) + +Guidance on when and how to use available tools: + +```markdown +When you need to understand a codebase: +- Use grep_search for finding specific patterns +- Use read_file to examine file contents +- Use list_dir to explore directory structure +- Always verify your understanding before making changes +``` + +### Recovery Prompts (How to Handle Failure) + +Instructions for when things go wrong: + +```markdown +If an action fails: +1. Analyze the error message carefully +2. Consider alternative approaches +3. Ask for clarification if the task is ambiguous +4. Never repeat the same failed action without changes +``` + + +An agent's behavior emerges from layers of prompts working together. The system prompt sets the foundation, planning prompts guide reasoning, tool prompts enable action, and recovery prompts handle failures. Together, they create coherent, capable behavior. + + +## What Are Skills? + +If prompts are the atoms, **skills are the molecules**—reusable building blocks that give agents specific capabilities. + +A **skill** is a comprehensive, portable package of instructions that gives an AI agent expertise in a specific domain or task. Skills are the reusable blocks of agents: you build them once, and any agent can use them. + + +Write a skill for code review once. Now every coding agent—whether it's for Python, JavaScript, or Rust—can instantly become an expert code reviewer by loading that skill. Skills let you build agent capabilities like LEGO blocks. + + +### Anatomy of a Skill + +A well-designed skill typically includes: + +
+
+

📄 SKILL.md (Required)

+

The main instruction file. Contains the core expertise, guidelines, and behaviors that define the skill.

+
+
+

📚 Reference Docs

+

Supporting documentation, examples, and context the agent can reference while working.

+
+
+

🔧 Scripts & Tools

+

Helper scripts, templates, or tool configurations that support the skill's functionality.

+
+
+

⚙️ Configuration

+

Settings, parameters, and customization options for adapting the skill to different contexts.

+
+
+ +### Example: Code Review Skill + +Here's what a code review skill might look like: + +
+
+ 📁 + code-review-skill/ +
+
+
+ 📄 + SKILL.md + Core review guidelines +
+
+ 📄 + security-checklist.md + Security patterns +
+
+ 📄 + performance-tips.md + Optimization guide +
+
+
+ 📁 + language-specific/ +
+
+
+ 📄 + python.md + Python best practices +
+
+ 📄 + javascript.md + JavaScript patterns +
+
+ 📄 + rust.md + Rust guidelines +
+
+
+
+
+ +The `SKILL.md` file defines the overall approach: + +```markdown +--- +name: code-review +description: Comprehensive code review with security, performance, and style analysis +--- + +# Code Review Skill + +You are an expert code reviewer. When reviewing code: + +## Process +1. **Understand Context** - What does this code do? What problem does it solve? +2. **Check Correctness** - Does it work? Are there logic errors? +3. **Security Scan** - Reference security-checklist.md for common vulnerabilities +4. **Performance Review** - Check performance-tips.md for optimization opportunities +5. **Style & Maintainability** - Is the code readable and maintainable? + +## Output Format +Provide feedback in categories: +- 🔴 **Critical** - Must fix before merge +- 🟡 **Suggested** - Recommended improvements +- 🟢 **Nice to have** - Optional enhancements + +Always explain *why* something is an issue, not just *what* is wrong. +``` + +## Skills vs. Simple Prompts + +
+
+

Simple Prompt

+
+

Single instruction

+

One-off use

+

Limited context

+

Generic approach

+

No supporting materials

+
+
+
+

Skill

+
+

Comprehensive instruction set

+

Reusable across projects

+

Rich context with references

+

Domain-specific expertise

+

Supporting docs, scripts, configs

+
+
+
+ +## Building Effective Skills + +### 1. Define the Expertise Clearly + +Start with a clear description of what the skill enables: + +```markdown +--- +name: api-design +description: Design RESTful APIs following industry best practices, + including versioning, error handling, and documentation standards +--- +``` + +### 2. Structure Knowledge Hierarchically + +Organize information from general to specific: + +```markdown +# API Design Skill + +## Core Principles +- Resources should be nouns, not verbs +- Use HTTP methods semantically +- Version your APIs from day one + +## Detailed Guidelines +[More specific rules...] + +## Reference Materials +- See `rest-conventions.md` for naming conventions +- See `error-codes.md` for standard error responses +``` + +### 3. Include Concrete Examples + +Abstract rules become clear with examples: + +```markdown +## Endpoint Naming + +✅ Good: +- GET /users/{id} +- POST /orders +- DELETE /products/{id}/reviews/{reviewId} + +❌ Avoid: +- GET /getUser +- POST /createNewOrder +- DELETE /removeProductReview +``` + +### 4. Provide Decision Frameworks + +Help the agent make choices in ambiguous situations: + +```markdown +## When to Use Pagination + +Use pagination when: +- Collection could exceed 100 items +- Response size impacts performance +- Client may not need all items + +Use full response when: +- Collection is always small (<20 items) +- Client typically needs everything +- Real-time consistency is critical +``` + +### 5. Add Recovery Patterns + +Anticipate what can go wrong: + +```markdown +## Common Issues + +**Problem**: Client needs fields not in standard response +**Solution**: Implement field selection: GET /users?fields=id,name,email + +**Problem**: Breaking changes needed +**Solution**: Create new version, deprecate old with timeline +``` + +## Composing Skills + +Agents become powerful when multiple skills work together. Consider how skills can complement each other: + +
+
+ Code Review +
+
+
+
+ Security Audit +
+
+
+
+ Documentation +
+
=
+
+ Complete Code Quality Agent +
+
+ +When composing skills, ensure they don't conflict. Skills should be: + +- **Modular** - Each skill handles one domain well +- **Compatible** - Skills shouldn't give contradictory instructions +- **Prioritized** - When skills overlap, define which takes precedence + +## Sharing and Discovering Skills + +Skills are most valuable when shared. Platforms like [prompts.chat](https://prompts.chat/skills) allow you to: + +- **Discover** community-created skills for common tasks +- **Download** skills directly to your projects +- **Share** your own expertise as reusable skills +- **Iterate** on skills based on real-world usage + + +Before building a skill from scratch, check if someone has already solved your problem. Community skills are battle-tested and often better than starting from zero. + + +## The Agent-Skill Ecosystem + +The relationship between agents and skills creates a powerful ecosystem: + +
+
+ AI Agent +
+
+
+

Code Review

+

Skill 1

+
+
+

API Design

+

Skill 2

+
+
+

Test Writing

+

Skill 3

+
+
+
+
↓
+
+
+
+

Core Prompts

+

Planning • Tools • Recovery • Memory

+
+
+
+ +The agent provides the execution framework—planning, tool use, and memory—while skills provide domain expertise. This separation means: + +- **Skills are portable** - The same skill works with different agents +- **Agents are extensible** - Add new capabilities by adding skills +- **Expertise is shareable** - Domain experts can contribute skills without building full agents + +## Best Practices + +### For Building Skills + +1. **Start specific, then generalize** - Build a skill for your exact use case first, then abstract +2. **Include failure cases** - Document what the skill can't do and how to handle it +3. **Version your skills** - Track changes so agents can depend on stable versions +4. **Test with real tasks** - Validate skills against actual work, not just theory + +### For Using Skills with Agents + +1. **Read the skill first** - Understand what a skill does before deploying it +2. **Customize thoughtfully** - Override skill defaults only when necessary +3. **Monitor performance** - Track how well skills perform in your context +4. **Contribute improvements** - When you improve a skill, consider sharing back + + +As AI agents become more capable, the ability to compose, share, and customize skills will become a core competency. The prompt engineers of tomorrow won't just write prompts—they'll architect skill ecosystems that make AI agents genuinely expert in specific domains. + + + + + + + diff --git a/src/content/book/zh/00a-preface.mdx b/src/content/book/zh/00a-preface.mdx new file mode 100644 index 00000000..8e84af9e --- /dev/null +++ b/src/content/book/zh/00a-preface.mdx @@ -0,0 +1,82 @@ +
+ Fatih Kadir Akın +
+ Fatih Kadir Akın + Creator of Awesome ChatGPT Prompts (a.k.a. prompts.chat) + + Software developer from Istanbul, leading Developer Relations at Teknasyon. Author of books on JavaScript and prompt engineering. Open-source advocate specializing in web technologies and AI-assisted development. + + +
+
+ +I still remember the night everything changed. + +It was **November 30, 2022**. I was sitting at my desk, scrolling through Twitter, when I saw people talking about something called "ChatGPT." I clicked the link, but honestly? I didn't expect much. I had tried those old "word completion" AI tools before, the ones that generated nonsense after a few sentences. I thought this would be more of the same. + +I typed a simple question and hit enter. + +Then I froze. + +The response wasn't just coherent. It was *good*. It understood what I meant. It could reason. It felt completely different from anything I had seen before. I tried another prompt. And another. Each response amazed me more than the last. + +I couldn't sleep that night. For the first time, I felt like I was truly *talking* to a machine, and it was talking back in a way that actually made sense. + +## A Repository Born from Wonder + +In those early days, I wasn't alone in my excitement. Everywhere I looked, people were discovering creative ways to use ChatGPT. Teachers were using it to explain complex concepts. Writers were collaborating with it on stories. Developers were debugging code with its help. + +I started collecting the best prompts I found. The ones that worked like magic. The ones that turned simple questions into brilliant answers. And I thought: *Why keep this to myself?* + +So I created a simple GitHub repository called [Awesome ChatGPT Prompts](https://github.com/f/prompts.chat). I expected maybe a few hundred people would find it useful. + +I was wrong. + +Within weeks, the repository took off. Thousands of stars. Then tens of thousands. People from all over the world started adding their own prompts, sharing what they learned, and helping each other. What started as my personal collection became something much bigger: a worldwide community of curious people helping each other. + +Today, that repository has over **140,000 GitHub stars** and contributions from hundreds of people I've never met but feel deeply grateful for. + +## Why I Wrote This Book + +The original version of this book was published on [Gumroad](https://gumroad.com/l/the-art-of-chatgpt-prompting) in **early 2023**, just months after ChatGPT launched. It was one of the first books ever written about prompt engineering, an attempt to capture everything I had learned about crafting effective prompts when the field was still brand new. To my amazement, over **100,000 people** downloaded it. + +But three years have passed since then. AI has changed a lot. New models have appeared. And we've all learned so much more about how to talk to AI. + +This new edition is my gift to the community that gave me so much. It contains everything I wish I had known when I started: **what works**, **what to avoid**, and **ideas that stay true** no matter which AI you use. + +## What This Book Means to Me + +I won't pretend this is just an instruction manual. It means more than that to me. + +This book captures a moment when the world changed, and people came together to figure it out. It represents late nights of trying things, the joy of discovery, and the kindness of strangers who shared what they learned. + +Most of all, it represents my belief that **the best way to learn something is to share it with others**. + +## For You + +Whether you're just getting started with AI or you've been using it for years, I wrote this book for you. + +I hope it saves you time. I hope it sparks ideas. I hope it helps you accomplish things you never thought possible. + +And when you discover something amazing, I hope you'll share it with others, just as so many people shared with me. + +**That's how we all get better together.** + +Thank you for being here. Thank you for being part of this community. + +Now, let's begin. + +--- + +*With gratitude,* + +**Fatih Kadir Akın** +*Istanbul, January 2025* diff --git a/src/content/book/zh/00b-history.mdx b/src/content/book/zh/00b-history.mdx new file mode 100644 index 00000000..ac636384 --- /dev/null +++ b/src/content/book/zh/00b-history.mdx @@ -0,0 +1,159 @@ +# The History of Awesome ChatGPT Prompts + +## The Beginning: November 2022 + +When ChatGPT first launched in November 2022, the world of AI changed overnight. What was once the domain of researchers and developers suddenly became accessible to everyone. Among those captivated by this new technology was Fatih Kadir Akın, a developer who saw something remarkable in ChatGPT's capabilities. + +> "When ChatGPT first launched, I was immediately captivated by its capabilities. I experimented with the tool in a variety of ways and was consistently amazed by the results." + +Those early days were filled with experimentation and discovery. Users around the world were finding creative ways to interact with ChatGPT, sharing their findings, and learning from each other. It was in this atmosphere of excitement and exploration that the idea for "Awesome ChatGPT Prompts" was born. + +## The Repository That Started It All + +In December 2022, just weeks after ChatGPT's launch, the [Awesome ChatGPT Prompts](https://github.com/f/prompts.chat) repository was created on GitHub. The concept was simple but powerful: a curated collection of effective prompts that anyone could use and contribute to. + +The repository quickly gained traction, becoming a go-to resource for ChatGPT users worldwide. What started as a personal collection of useful prompts evolved into a community-driven project with contributions from developers, writers, educators, and enthusiasts from every corner of the globe. + +### Achievements + +**Press & Media** +- Featured in [Forbes](https://www.forbes.com/sites/bernardmarr/2023/05/17/the-best-prompts-for-chatgpt-a-complete-guide/) as one of the best ChatGPT prompt resources + +**Academic Recognition** +- Referenced by [Harvard University](https://www.huit.harvard.edu/news/ai-prompts) in their AI guidance +- Referenced by [Columbia University](https://etc.cuit.columbia.edu/news/columbia-prompt-library-effective-academic-ai-use) Prompt Library +- Used by [Olympic College](https://libguides.olympic.edu/UsingAI/Prompts) in their AI resources +- Cited in [academic papers on arXiv](https://arxiv.org/pdf/2502.04484) +- [40+ academic citations](https://scholar.google.com/citations?user=AZ0Dg8YAAAAJ&hl=en) on Google Scholar + +**Community & GitHub** +- [142,000+ GitHub stars](https://github.com/f/prompts.chat) — one of the most starred AI repositories +- Selected as a [GitHub Staff Pick](https://spotlights-feed.github.com/spotlights/prompts-chat/) +- Most liked dataset published on [Hugging Face](https://huggingface.co/datasets/fka/prompts.chat) +- Used by thousands of developers worldwide + +## The First Book: "The Art of ChatGPT Prompting" + +The success of the repository led to the creation of "The Art of ChatGPT Prompting: A Guide to Crafting Clear and Effective Prompts" — a comprehensive guide published on Gumroad in early 2023. + +The book captured the early wisdom of prompt engineering, covering: + +- Understanding how ChatGPT works +- Principles of clear communication with AI +- The famous "Act As" technique +- Crafting effective prompts step by step +- Common mistakes and how to avoid them +- Troubleshooting tips + +**The book became a phenomenon**, achieving over **100,000 downloads** on Gumroad. It was shared across social media, referenced in academic papers, and translated by community members into multiple languages. High-profile endorsements came from unexpected places — even [Greg Brockman](https://x.com/gdb/status/1602072566671110144), co-founder and president of OpenAI, acknowledged the project. + +## Early Insights That Shaped the Field + +During those formative months, several key insights emerged that would become foundational to prompt engineering: + +### 1. Specificity Matters + +> "I learned the importance of using specific and relevant language to ensure that ChatGPT understands my prompts and is able to generate appropriate responses." + +Early experimenters discovered that vague prompts led to vague responses. The more specific and detailed the prompt, the more useful the output. + +### 2. Purpose and Focus + +> "I discovered the value of defining a clear purpose and focus for the conversation, rather than using open-ended or overly broad prompts." + +This insight became the foundation for structured prompting techniques that would develop over the following years. + +### 3. The "Act As" Revolution + +One of the most influential techniques to emerge from the community was the "Act As" pattern. By instructing ChatGPT to assume a specific role or persona, users could dramatically improve the quality and relevance of responses. + +``` +I want you to act as a javascript console. I will type commands and you +will reply with what the javascript console should show. I want you to +only reply with the terminal output inside one unique code block, and +nothing else. +``` + +This simple technique opened up countless possibilities and remains one of the most widely used prompting strategies today. + +## The Evolution of prompts.chat + +### 2022: The Beginning + +The project started as a simple GitHub repository with a README file rendered as HTML on GitHub Pages. It was bare-bones but functional — a testament to the principle that great ideas don't need elaborate implementations. + +**Tech Stack**: HTML, CSS, GitHub Pages + +### 2024: UI Renewal + +As the community grew, so did the need for a better user experience. The site received a significant UI update, built with the help of AI coding assistants like Cursor and Claude Sonnet 3.5. + +### 2025: The Current Platform + +Today, prompts.chat has evolved into a full-featured platform built with: + +- **Next.js** for the web framework +- **Vercel** for hosting +- **AI-assisted development** using Windsurf and Claude + +The platform now features user accounts, collections, search, categories, tags, and a thriving community of prompt engineers. + +### Native Apps + +The project expanded beyond the web with a native iOS app built with SwiftUI, bringing the prompt library to mobile users. + +## Community Impact + +The Awesome ChatGPT Prompts project has had a profound impact on how people interact with AI: + +### Academic Recognition + +Universities around the world have referenced the project in their AI guidance materials, including: + +- Harvard University +- Columbia University +- Olympic College +- Numerous academic papers on arXiv + +### Developer Adoption + +The project has been integrated into countless developer workflows. The Hugging Face dataset is used by researchers and developers for training and fine-tuning language models. + +### Global Community + +With contributions from hundreds of community members across dozens of countries, the project represents a truly global effort to make AI more accessible and useful for everyone. + +## The Philosophy: Open and Free + +From the beginning, the project has been committed to openness. Licensed under CC0 1.0 Universal (Public Domain Dedication), all prompts and content are free to use, modify, and share without restriction. + +This philosophy has enabled: + +- Translations into multiple languages +- Integration into other tools and platforms +- Academic use and research +- Commercial applications + +The goal has always been to democratize access to effective AI communication techniques — to ensure that everyone, regardless of technical background, can benefit from these tools. + +## Three Years Later + +Three years after ChatGPT's launch, the field of prompt engineering has matured significantly. What began as informal experimentation has evolved into a recognized discipline with established patterns, best practices, and an active research community. + +The Awesome ChatGPT Prompts project has grown alongside this field, evolving from a simple list of prompts to a comprehensive platform for discovering, sharing, and learning about AI prompts. + +This book represents the next evolution — a distillation of three years of community wisdom, updated for the AI landscape of today and tomorrow. + +## Looking Forward + +The journey from that first repository to this comprehensive guide reflects the rapid evolution of AI and our understanding of how to work with it effectively. As AI capabilities continue to advance, so too will the techniques for communicating with these systems. + +The principles discovered in those early days — clarity, specificity, purpose, and the power of role-playing — remain as relevant as ever. But new techniques continue to emerge: chain-of-thought prompting, few-shot learning, multimodal interactions, and more. + +The story of Awesome ChatGPT Prompts is ultimately a story about community — about thousands of people around the world sharing their discoveries, helping each other learn, and collectively advancing our understanding of how to work with AI. + +That spirit of open collaboration and shared learning is what this book hopes to continue. + +--- + +*The Awesome ChatGPT Prompts project is maintained by [@f](https://github.com/f) and an amazing community of contributors. Visit [prompts.chat](https://prompts.chat) to explore the platform, and join us on [GitHub](https://github.com/f/prompts.chat) to contribute.* diff --git a/src/content/book/zh/00c-introduction.mdx b/src/content/book/zh/00c-introduction.mdx new file mode 100644 index 00000000..c744bd1e --- /dev/null +++ b/src/content/book/zh/00c-introduction.mdx @@ -0,0 +1,130 @@ +Welcome to **The Interactive Book of Prompting**, your guide to communicating effectively with AI. + + +By the end of this book, you'll understand how AI works, how to write better prompts, and how to use these skills for writing, coding, research, and creative projects. + + + +Unlike traditional books, this guide is fully interactive. You'll find live demos, clickable examples, and "Try It" buttons throughout that let you test prompts instantly. Learning by doing makes complex concepts much easier to understand. + + +## What is Prompt Engineering? + +Prompt engineering is the skill of writing good instructions for AI. When you type something to ChatGPT, Claude, Gemini, or other AI tools, that's called a "prompt." The better your prompt, the better the answer you get. + +Think of it like this: AI is a powerful helper that takes your words very literally. It will do exactly what you ask. The trick is learning how to ask for exactly what you want. + + + +The difference in output quality between these two prompts can be dramatic. + + + +## How Prompt Engineering Has Evolved + +In just three years since ChatGPT launched, prompt engineering has evolved dramatically alongside the technology itself. What started as simply "writing better questions" has grown into something much broader. + +Today, we understand that your prompt is just **one part of a larger context**. Modern AI systems work with multiple types of data simultaneously: + +- **System prompts** that define the AI's behavior +- **Conversation history** from previous messages +- **Retrieved documents** pulled from databases (RAG) +- **Tool definitions** that let AI take actions +- **User preferences** and settings +- **Your actual prompt** - the question you're asking right now + +This shift from "prompt engineering" to "context engineering" reflects how we now think about AI interactions. Your prompt matters, but so does everything else the AI sees. The best results come from carefully managing all these pieces together. + +We'll explore these concepts in depth throughout this book, especially in the [Context Engineering](/book/20-context-engineering) chapter. + +## Why Does Prompt Engineering Matter? + +### 1. Getting Better Answers + +AI tools are incredibly capable, but they need clear instructions to unlock their full potential. The same AI that gives a mediocre response to a vague question can produce brilliant work when prompted correctly. + + + +### 2. Saving Time and Money + +A well-crafted prompt gets results in one try instead of multiple back-and-forth exchanges. This matters even more when you're paying per token or working with rate limits. A 5-minute investment in writing a good prompt can save hours of iteration. + +### 3. Getting Consistent, Reproducible Results + +Good prompts produce predictable outputs. This is critical for: +- **Business workflows** where you need the same quality every time +- **Automation** where prompts run without human review +- **Teams** where multiple people need similar results + +### 4. Unlocking Advanced Capabilities + +Many powerful AI features only work when you know how to ask: +- **Chain-of-thought reasoning** for complex problems +- **Structured output** for data extraction +- **Role-playing** for specialized expertise +- **Few-shot learning** for custom tasks + +Without prompt engineering knowledge, you're only using a fraction of what AI can do. + +### 5. Staying Safe and Avoiding Pitfalls + +Good prompting helps you: +- Avoid hallucinations by asking for sources and verification +- Get balanced perspectives instead of one-sided answers +- Prevent the AI from making assumptions you didn't intend +- Keep sensitive information out of your prompts + +### 6. Future-Proofing Your Skills + +As AI becomes more integrated into work and life, prompt engineering becomes a fundamental literacy. The principles you learn here apply across all AI tools—ChatGPT, Claude, Gemini, image generators, and future models we haven't seen yet. + +## Who Is This Book For? + +This book is for everyone: + +- **Beginners** who want to learn how to use AI tools better +- **Students** working on homework, research, or creative projects +- **Writers and creators** using AI for their work +- **Developers** building apps with AI +- **Business people** who want to use AI at work +- **Anyone curious** about getting more out of AI assistants + +## How This Book Is Organized + + + +Plus an **Appendix** with templates, troubleshooting help, glossary, and extra resources. + +## A Note on AI Models + +This book mostly uses examples from ChatGPT (since it's the most popular), but the ideas work with any AI tool like Claude, Gemini, or others. We'll mention when something only works with specific AI models. + +AI is changing fast. What works today might be replaced by something better tomorrow. That's why this book focuses on core ideas that will stay useful no matter which AI you use. + +## Let's Begin + +Writing good prompts is a skill that gets better with practice. As you read this book: + +1. **Try things** - Test the examples, change them, see what happens +2. **Keep trying** - Don't expect perfect results on your first attempt +3. **Take notes** - Write down what works and what doesn't +4. **Share** - Add your discoveries to [prompts.chat](https://prompts.chat) + + +The best way to learn is by doing. Every chapter has examples you can try right away. Don't just read. Try it yourself! + + +Ready to transform how you work with AI? Turn the page and let's get started. + +--- + +*This book is part of the [Awesome ChatGPT Prompts](https://github.com/f/prompts.chat) project and is licensed under CC0 1.0 Universal (Public Domain).* diff --git a/src/content/book/zh/01-understanding-ai-models.mdx b/src/content/book/zh/01-understanding-ai-models.mdx new file mode 100644 index 00000000..0313d4a2 --- /dev/null +++ b/src/content/book/zh/01-understanding-ai-models.mdx @@ -0,0 +1,302 @@ +Before learning prompt techniques, it helps to understand how AI language models actually work. This knowledge will make you better at writing prompts. + + +Understanding how AI works isn't just for experts. It directly helps you write better prompts. Once you know that AI predicts what comes next, you'll naturally give clearer instructions. + + +## What Are Large Language Models? + +Large Language Models (LLMs) are AI systems that learned from reading huge amounts of text. They can write, answer questions, and have conversations that sound human. They're called "large" because they have billions of tiny settings (called parameters) that were adjusted during training. + +### How LLMs Work (Simplified) + +At their heart, LLMs are prediction machines. You give them some text, and they predict what should come next. + + + +When you type "The capital of France is...", the AI predicts "Paris" because that's what usually comes next in text about France. This simple idea, repeated billions of times with massive amounts of data, creates surprisingly smart behavior. + + + +### Key Concepts + +**Tokens**: AI doesn't read letter by letter. It breaks text into chunks called "tokens." A token might be a whole word like "hello" or part of a word like "ing." Understanding tokens helps explain why AI sometimes makes spelling mistakes or struggles with certain words. + + +A token is the smallest unit of text that an AI model processes. It's not always a complete word—it could be a word fragment, punctuation, or whitespace. For example, "unbelievable" might become 3 tokens: "un" + "believ" + "able". On average, **1 token ≈ 4 characters** or **100 tokens ≈ 75 words**. API costs and context limits are measured in tokens. + + + + +**Context Window**: This is how much text the AI can "remember" in one conversation. Think of it like the AI's short-term memory. It includes everything: your question AND the AI's answer. + + + +Context windows vary by model and are rapidly expanding: + +
+
+ GPT-4o + 128K tokens +
+
+ GPT-5 + 400K tokens +
+
+ Claude Sonnet 4 + 1M tokens +
+
+ Gemini 2.5 + 1M tokens +
+
+ Llama 4 + 1M-10M tokens +
+
+ DeepSeek R1 + 128K tokens +
+
+ +**Temperature**: This controls how creative or predictable the AI is. Low temperature (0.0-0.3) gives you focused, consistent answers. High temperature (0.7-1.0) gives you more creative, surprising responses. + + + +**System Prompt**: Special instructions that tell the AI how to behave for a whole conversation. For example, "You are a friendly teacher who explains things simply." Not all AI tools let you set this, but it's very powerful when available. + +## Types of AI Models + +### Text Models (LLMs) +The most common type, these generate text responses to text inputs. They power chatbots, writing assistants, and code generators. Examples: GPT-4, Claude, Llama, Mistral. + +### Multimodal Models +These can understand more than just text. They can look at images, listen to audio, and watch videos. Examples: GPT-4V, Gemini, Claude 3. + +### Text-to-Image Models + + +While this book focuses primarily on prompting for Large Language Models (text-based AI), the principles of clear, specific prompting apply to image generation too. Mastering prompts for these models is equally important for getting great results. + + +Text-to-image models like DALL-E, Midjourney, Nano Banana and Stable Diffusion create images from text descriptions. They work differently from text models: + +**How They Work:** +1. **Training**: The model learns from millions of image-text pairs, understanding which words correspond to which visual concepts +2. **Diffusion Process**: Starting from random noise, the model gradually refines the image, guided by your text prompt +3. **CLIP Guidance**: A separate model (CLIP) helps connect your words to visual concepts, ensuring the image matches your description + + + +**Prompting for Images is Different:** +Unlike text prompts where you write sentences, image prompts often work better as descriptive phrases separated by commas: + + + +### Text-to-Video Models + +Text-to-video is the newest frontier. Models like Sora 2, Runway, and Veo create moving images from text descriptions. Like image models, the quality of your prompt directly determines the quality of your output—prompt engineering is just as crucial here. + +**How They Work:** +1. **Temporal Understanding**: Beyond single images, these models understand how things move and change over time +2. **Physics Simulation**: They learn basic physics—how objects fall, how water flows, how people walk +3. **Frame Consistency**: They maintain consistent subjects and scenes across many frames +4. **Diffusion in Time**: Similar to image models, but generating coherent sequences instead of single frames + + + + +Video prompts need to describe action over time, not just a static scene. Include verbs and movement: + + + + +### Specialized Models +Fine-tuned for specific tasks like code generation (Codex, CodeLlama), music generation (Suno, Udio), or domain-specific applications like medical diagnosis or legal document analysis. + +## Model Capabilities and Limitations + +Explore what LLMs can and cannot do. Click on each capability to see example prompts: + + + +### Understanding Hallucinations + + +Sometimes AI writes things that sound true but aren't. This is called "hallucination." It's not a bug. It's just how prediction works. Always double-check important facts. + + +Why does AI make things up? + +1. It tries to write text that sounds good, not text that's always true +2. The internet (where it learned) has mistakes too +3. It can't actually check if something is real + + + +- **Ask for sources**: Then check if those sources are real +- **Ask for step-by-step thinking**: So you can check each step +- **Double-check important facts**: Use Google or trusted websites +- **Ask "Are you sure?"**: The AI might admit uncertainty + + + + + +## How AI Learns: The Three Steps + +AI doesn't just magically know things. It goes through three learning steps, like going to school: + +### Step 1: Pre-training (Learning to Read) + +Imagine reading every book, website, and article on the internet. That's what happens in pre-training. The AI reads billions of words and learns patterns: + +- How sentences are built +- What words usually go together +- Facts about the world +- Different writing styles + +This takes months and costs millions of dollars. After this step, the AI knows a lot, but it's not very helpful yet. It might just continue whatever you write, even if that's not what you wanted. + + + +### Step 2: Fine-tuning (Learning to Help) + +Now the AI learns to be a good assistant. Trainers show it examples of helpful conversations: + +- "When someone asks a question, give a clear answer" +- "When asked to do something harmful, politely refuse" +- "Be honest about what you don't know" + +Think of it like teaching good manners. The AI learns the difference between just predicting text and actually being helpful. + + + +Try the prompt above. Notice how the AI refuses? That's fine-tuning at work. + +### Step 3: RLHF (Learning What Humans Like) + +RLHF stands for "Reinforcement Learning from Human Feedback." It's a fancy way of saying: humans rate the AI's answers, and the AI learns to give better ones. + +Here's how it works: +1. The AI writes two different answers to the same question +2. A human picks which answer is better +3. The AI learns: "Okay, I should write more like Answer A" +4. This happens millions of times + +This is why AI: +- Is polite and friendly +- Admits when it doesn't know something +- Tries to see different sides of an issue +- Avoids controversial statements + + +Knowing these three steps helps you understand AI behavior. When AI refuses a request, that's fine-tuning. When AI is extra polite, that's RLHF. When AI knows random facts, that's pre-training. + + +## What This Means for Your Prompts + +Now that you understand how AI works, here's how to use that knowledge: + +### 1. Be Clear and Specific + +AI predicts what comes next based on your words. Vague prompts lead to vague answers. Specific prompts get specific results. + + + + + +### 2. Give Context + +AI doesn't know anything about you unless you tell it. Each conversation starts fresh. Include the background information AI needs. + + + + + +### 3. Work With the AI, Not Against It + +Remember: AI was trained to be helpful. Ask for things the way you'd ask a helpful friend. + + + +### 4. Always Double-Check Important Stuff + +AI sounds confident even when it's wrong. For anything important, verify the information yourself. + + + +### 5. Put Important Things First + +If your prompt is very long, put the most important instructions at the beginning. AI pays more attention to what comes first. + +## Picking the Right AI + +Different AI models are good at different things: + +
+
+ Quick questions + Faster models like GPT-4o or Claude 3.5 Sonnet +
+
+ Hard problems + Smarter models like GPT-5.2 or Claude 4.5 Opus +
+
+ Writing code + Code-focused models or the smartest general models +
+
+ Long documents + Models with big context windows (Claude, Gemini) +
+
+ Current events + Models with internet access +
+
+ +## Summary + +AI language models are prediction machines trained on text. They're amazing at many things, but they have real limits. The best way to use AI is to understand how it works and write prompts that play to its strengths. + + + + + +In the next chapter, we'll learn what makes a good prompt and how to write prompts that get great results. diff --git a/src/content/book/zh/02-anatomy-of-effective-prompt.mdx b/src/content/book/zh/02-anatomy-of-effective-prompt.mdx new file mode 100644 index 00000000..03cd23d2 --- /dev/null +++ b/src/content/book/zh/02-anatomy-of-effective-prompt.mdx @@ -0,0 +1,343 @@ +Every great prompt shares common structural elements. Understanding these components allows you to construct prompts systematically rather than through trial and error. + + +Think of these components like LEGO bricks. You don't need all of them for every prompt, but knowing what's available helps you build exactly what you need. + + +## The Core Components + +An effective prompt typically includes some or all of these elements: + + + +Let's examine each component in detail. + +## 1. Role / Persona + +Setting a role focuses the model's responses through the lens of a specific expertise or perspective. + + + +The role primes the model to: +- Use appropriate vocabulary +- Apply relevant expertise +- Maintain a consistent perspective +- Consider the audience appropriately + +### Effective Role Patterns + +``` +"You are a [profession] with [X years] of experience in [specialty]" +"Act as a [role] who is [characteristic]" +"You are an expert [field] helping a [audience type]" +``` + +## 2. Context / Background + +Context provides the information the model needs to understand your situation. Remember: the model knows nothing about you, your project, or your goals unless you tell it. + + + +### What to Include in Context + +- **Project details** — Technology stack, architecture, constraints +- **Current state** — What you've tried, what's working, what isn't +- **Goals** — What you're ultimately trying to achieve +- **Constraints** — Time limits, technical requirements, style guides + +## 3. Task / Instruction + +The task is the heart of your prompt—what you want the model to do. Be specific and unambiguous. + +### The Specificity Spectrum + + + +### Action Verbs That Work Well + +
+
+ Creation + Write, Create, Generate, Compose, Design +
+
+ Analysis + Analyze, Evaluate, Compare, Assess, Review +
+
+ Transformation + Convert, Translate, Reformat, Summarize, Expand +
+
+ Explanation + Explain, Describe, Clarify, Define, Illustrate +
+
+ Problem-solving + Solve, Debug, Fix, Optimize, Improve +
+
+ +## 4. Constraints / Rules + +Constraints bound the model's output. They prevent common issues and ensure relevance. + +### Types of Constraints + +**Length constraints:** +``` +"Keep your response under 200 words" +"Provide exactly 5 suggestions" +"Write 3-4 paragraphs" +``` + +**Content constraints:** +``` +"Do not include any code examples" +"Focus only on the technical aspects" +"Avoid marketing language" +``` + +**Style constraints:** +``` +"Use a formal, academic tone" +"Write as if speaking to a 10-year-old" +"Be direct and avoid hedging language" +``` + +**Scope constraints:** +``` +"Only consider options available in Python 3.10+" +"Limit suggestions to free tools" +"Focus on solutions that don't require additional dependencies" +``` + +## 5. Output Format + +Specifying the output format ensures you get responses in a usable structure. + +### Common Formats + +**Lists:** +``` +"Return as a bulleted list" +"Provide a numbered list of steps" +``` + +**Structured data:** +``` +"Return as JSON with keys: title, description, priority" +"Format as a markdown table with columns: Feature, Pros, Cons" +``` + +**Specific structures:** +``` +"Structure your response as: + ## Summary + ## Key Points + ## Recommendations" +``` + +### JSON Output Example + +``` +Analyze this customer review and return JSON: +{ + "sentiment": "positive" | "negative" | "neutral", + "topics": ["array of main topics"], + "rating_prediction": 1-5, + "key_phrases": ["notable phrases"] +} + +Review: "The product arrived quickly and works great, but +the instructions were confusing." +``` + +## 6. Examples (Few-Shot Learning) + +Examples are the most powerful way to show the model exactly what you want. + +### One-Shot Example + +``` +Convert these sentences to past tense. + +Example: +Input: "She walks to the store" +Output: "She walked to the store" + +Now convert: +Input: "They run every morning" +``` + +### Few-Shot Example + +``` +Classify these support tickets by urgency. + +Examples: +"My account was hacked" → Critical +"How do I change my password?" → Low +"Payment failed but I was charged" → High + +Classify: "The app crashes when I open settings" +``` + +## Putting It All Together + +Here's a complete prompt using all components: + + + +## The Minimal Effective Prompt + +Not every prompt needs all components. For simple tasks, a clear instruction may suffice: + +``` +Translate "Hello, how are you?" to Spanish. +``` + +Use additional components when: +- The task is complex or ambiguous +- You need specific formatting +- Results aren't matching expectations +- Consistency across multiple queries matters + +## Common Prompt Patterns + +These frameworks give you a simple checklist to follow when writing prompts. Click on each step to see an example. + + + + + +## Summary + +Effective prompts are constructed, not discovered. By understanding and applying these structural components, you can: + +- Get better results on the first try +- Debug prompts that aren't working +- Create reusable prompt templates +- Communicate your intentions clearly + + + + + +## Build Your Own Prompt + +Now it's your turn! Use this interactive prompt builder to construct your own prompt using the components you've learned: + + + + + +In the next chapter, we'll explore the core principles that guide prompt construction decisions. diff --git a/src/content/book/zh/03-core-prompting-principles.mdx b/src/content/book/zh/03-core-prompting-principles.mdx new file mode 100644 index 00000000..358df563 --- /dev/null +++ b/src/content/book/zh/03-core-prompting-principles.mdx @@ -0,0 +1,373 @@ +Beyond structure, effective prompt engineering is guided by principles—fundamental truths that apply across models, tasks, and contexts. Master these principles, and you'll be able to adapt to any prompting challenge. + + +These principles apply to every AI model and every task. Learn them once, use them everywhere. + + +## Principle 1: Clarity Over Cleverness + +The best prompts are clear, not clever. AI models are literal interpreters—they work with exactly what you give them. + +### Be Explicit + + + +### Avoid Ambiguity + +Words can have multiple meanings. Choose precise language. + + + +### State the Obvious + +What's obvious to you isn't obvious to the model. Spell out assumptions. + +``` +You're helping me write a cover letter. + +Important context: +- I'm applying for a Software Engineer position at Google +- I have 5 years of experience in Python and distributed systems +- The role requires leadership experience (I've led a team of 4) +- I want to emphasize my open-source contributions +``` + +## Principle 2: Specificity Yields Quality + +Vague inputs produce vague outputs. Specific inputs produce specific, useful outputs. + +### The Specificity Ladder + + + +Each level adds specificity and dramatically improves output quality. + +### Specify These Elements + +
+
+ Audience + Who will read/use this? +
+
+ Length + How long/short should it be? +
+
+ Tone + Formal? Casual? Technical? +
+
+ Format + Prose? List? Table? Code? +
+
+ Scope + What to include/exclude? +
+
+ Purpose + What should this accomplish? +
+
+ +## Principle 3: Context Is King + +Models have no memory, no access to your files, and no knowledge of your situation. Everything relevant must be in the prompt. + +### Provide Sufficient Context + + + +### The Context Checklist + + +Ask yourself: Would a smart stranger understand this request? If not, add more context. + + + + +## Principle 4: Guide, Don't Just Ask + +Don't just ask for an answer—guide the model toward the answer you want. + +### Use Instructional Framing + + + +### Provide Reasoning Scaffolds + +For complex tasks, guide the reasoning process: + + + +## Principle 5: Iterate and Refine + +Prompt engineering is an iterative process. Your first prompt is rarely your best. + +### The Iteration Cycle + +``` +1. Write initial prompt +2. Review output +3. Identify gaps or issues +4. Refine prompt +5. Repeat until satisfied +``` + +### Common Refinements + +
+
+ Too verbose + Add "Be concise" or length limits +
+
+ Too vague + Add specific examples or constraints +
+
+ Wrong format + Specify exact output structure +
+
+ Missing aspects + Add "Make sure to include..." +
+
+ Wrong tone + Specify audience and style +
+
+ Inaccurate + Request citations or step-by-step reasoning +
+
+ +### Keep a Prompt Journal + +Document what works: +``` +Task: Code review +Version 1: "Review this code" → Too generic +Version 2: Added specific review criteria → Better +Version 3: Added example of good review → Excellent +Final: [Save successful prompt as template] +``` + +## Principle 6: Leverage the Model's Strengths + +Work with how models are trained, not against them. + +### Models Want to Be Helpful + +Frame requests as things a helpful assistant would naturally do: + + + +### Models Excel at Patterns + +If you need consistent output, show the pattern: + + + +### Models Can Role-Play + +Use personas to access different "modes" of response: + +``` +As a devil's advocate, argue against my proposal... +As a supportive mentor, help me improve... +As a skeptical investor, question this business plan... +``` + +## Principle 7: Control Output Structure + +Structured outputs are more useful than free-form text. + +### Request Specific Formats + +``` +Return your analysis as: + +SUMMARY: [1 sentence] + +KEY FINDINGS: +• [Finding 1] +• [Finding 2] +• [Finding 3] + +RECOMMENDATION: [1-2 sentences] + +CONFIDENCE: [Low/Medium/High] because [reason] +``` + +### Use Delimiters + +Clearly separate sections of your prompt: + +``` +### CONTEXT ### +[Your context here] + +### TASK ### +[Your task here] + +### FORMAT ### +[Desired format here] +``` + +### Request Machine-Readable Output + +For programmatic use: + +``` +Return only valid JSON, no explanation: +{ + "decision": "approve" | "reject" | "review", + "confidence": 0.0-1.0, + "reasons": ["string array"] +} +``` + +## Principle 8: Verify and Validate + +Never blindly trust model outputs, especially for important tasks. + +### Ask for Reasoning + +``` +Solve this problem and show your work step by step. +After solving, verify your answer by [checking method]. +``` + +### Request Multiple Perspectives + +``` +Give me three different approaches to solve this problem. +For each, explain the trade-offs. +``` + +### Build in Self-Checking + +``` +After generating the code, review it for: +- Syntax errors +- Edge cases +- Security vulnerabilities +List any issues found. +``` + +## Summary: The Principles at a Glance + + + + + +## Practice: Fill in the Blanks + +Test your understanding of the core principles by completing this prompt template: + + + + + +These principles form the foundation for everything that follows. In Part II, we'll apply them to specific techniques that dramatically enhance prompt effectiveness. diff --git a/src/content/book/zh/04-role-based-prompting.mdx b/src/content/book/zh/04-role-based-prompting.mdx new file mode 100644 index 00000000..ef178cbc --- /dev/null +++ b/src/content/book/zh/04-role-based-prompting.mdx @@ -0,0 +1,328 @@ +Role-based prompting is one of the most powerful and widely-used techniques in prompt engineering. By assigning a specific role or persona to the AI, you can dramatically influence the quality, style, and relevance of responses. + + +Think of roles as filters for AI's vast knowledge. The right role focuses responses like a lens focuses light. + + +## Why Roles Work + +When you assign a role, you're essentially telling the model: "Filter your vast knowledge through this specific lens." The model adjusts its: + +- **Vocabulary**: Using terminology appropriate to the role +- **Perspective**: Considering problems from that viewpoint +- **Expertise depth**: Providing role-appropriate detail levels +- **Communication style**: Matching how that role would communicate + +### The Technical Explanation + +LLMs work by predicting the most likely next token based on the context they're given. When you specify a role, you're fundamentally changing what "likely" means. + +**Activating Relevant Knowledge**: The role primes specific regions of the model's learned associations. Saying "You are a doctor" activates medical terminology, diagnostic reasoning patterns, and clinical communication styles from the training data. + +**Statistical Conditioning**: LLMs learned from millions of documents written by real experts. When you assign a role, the model conditions its probability distributions to match patterns it saw from that type of author. + +**Reducing Ambiguity**: Without a role, the model averages across all possible responders. With a role, it narrows to a specific subset, making responses more focused and consistent. + +**Context Anchoring**: The role creates a persistent context anchor throughout the conversation. Every subsequent response is influenced by this initial framing. + +Think of it this way: if you ask "What should I do about this cough?" the model could respond as a doctor, a friend, a pharmacist, or a worried parent. Each would give different advice. By specifying the role upfront, you're telling the model which "voice" to use from its training data. + + +The model isn't pretending or role-playing in a theatrical sense. It's statistically biasing its outputs toward patterns it learned from real experts, professionals, and specialists during training. A "doctor" role activates medical knowledge pathways; a "poet" role activates literary patterns. + + +## Basic Role Patterns + +These foundational patterns work across most use cases. Start with these templates and customize them for your needs. + +### The Expert Pattern + +The most versatile pattern. Specify the field of expertise and years of experience to get authoritative, in-depth responses. Works well for technical questions, analysis, and professional advice. + + + +### The Professional Pattern + +Ground the role in a real-world context by specifying a job title and organization type. This adds institutional knowledge and professional norms to the response. + + + +### The Teacher Pattern + +Perfect for learning and explanations. Specifying the audience level ensures the response matches the learner's background, from beginners to advanced practitioners. + + + +## Advanced Role Constructions + +### Compound Roles + +Combine multiple identities to get responses that blend different perspectives. This pediatrician-parent combination produces advice that's both medically sound and practically tested. + + + +### Situational Roles + +Place the role in a specific scenario to shape both content and tone. Here, the code review context makes the AI constructive and educational rather than just critical. + + + +### Perspective Roles + +Get feedback from a specific stakeholder's point of view. A VC perspective evaluates viability and scalability differently than a customer or engineer would. + + + +## Role Categories and Examples + +Different domains benefit from different types of roles. Here are proven examples organized by category that you can adapt for your tasks. + +### Technical Roles + +**Software Architect**: Best for system design decisions, technology choices, and architectural trade-offs. The focus on maintainability steers responses toward practical, long-term solutions. + + + +**Security Specialist**: The attacker mindset is key here. This role produces threat-focused analysis that identifies vulnerabilities a defensive-only perspective might miss. + + + +**DevOps Engineer**: Ideal for deployment, automation, and infrastructure questions. The emphasis on reliability ensures production-ready recommendations. + + + +### Creative Roles + +**Copywriter**: The "award-winning" qualifier and conversion focus produce punchy, persuasive copy rather than generic marketing text. + + + +**Screenwriter**: Activates knowledge of dramatic structure, pacing, and dialogue conventions. Great for any narrative writing that needs tension and character voice. + + + +**UX Writer**: A specialized role for interface text. The focus on brevity and user guidance produces concise, action-oriented copy. + + + +### Analytical Roles + +**Business Analyst**: Bridges the gap between technical and non-technical stakeholders. Useful for requirement gathering, spec writing, and identifying gaps in project plans. + + + +**Research Scientist**: The emphasis on evidence and uncertainty acknowledgment produces balanced, well-sourced responses that distinguish facts from speculation. + + + +**Financial Analyst**: Combines quantitative analysis with risk assessment. The dual focus on returns and risk produces more balanced investment perspectives. + + + +### Educational Roles + +**Socratic Tutor**: Instead of giving answers, this role asks guiding questions. Excellent for deeper learning and helping students develop critical thinking skills. + + + +**Instructional Designer**: Structures learning for maximum retention. Use this role when you need to break down complex topics into teachable chunks with clear progression. + + + +## The Role Stack Technique + +For complex tasks, combine multiple role aspects into a single, layered identity. This technique stacks expertise, audience awareness, and style guidelines to create highly specialized responses. + +This example layers three elements: domain expertise (API documentation), audience (junior developers), and style guide (Google's conventions). Each layer constrains the output further. + + + +## Roles for Different Tasks + +
+
+ Code review + Senior developer + mentor +
+
+ Writing feedback + Editor + target audience member +
+
+ Business strategy + Consultant + industry expert +
+
+ Learning new topic + Patient teacher + practitioner +
+
+ Creative writing + Specific genre author +
+
+ Technical explanation + Expert + communicator +
+
+ Problem-solving + Domain specialist + generalist +
+
+ +## Anti-Patterns to Avoid + +### Overly Generic Roles + + + +### Conflicting Roles + + + +### Unrealistic Expertise + + + +## Real-World Prompt Examples + +### Technical Documentation + + + +### Creative Writing + + + +### Business Communication + + + +## Combining Roles with Other Techniques + +Roles work even better when combined with other prompting techniques: + +### Role + Few-Shot + +Combine a role with an example to show exactly how the role should respond. The example teaches tone and format while the role provides context and expertise. + + + +### Role + Chain of Thought + +The detective role naturally encourages step-by-step reasoning. Combining roles with chain-of-thought produces more transparent, verifiable problem-solving. + + + +## Summary + + +Role-based prompting is powerful because it focuses the model's vast knowledge, sets expectations for tone and style, provides implicit context, and makes outputs more consistent. + + + + +The key is **specificity**: the more detailed and realistic the role, the better the results. In the next chapter, we'll explore how to get consistent, structured outputs from your prompts. diff --git a/src/content/book/zh/05-structured-output.mdx b/src/content/book/zh/05-structured-output.mdx new file mode 100644 index 00000000..8236abee --- /dev/null +++ b/src/content/book/zh/05-structured-output.mdx @@ -0,0 +1,411 @@ +Getting consistent, well-formatted output is essential for production applications and efficient workflows. This chapter covers techniques for controlling exactly how AI models format their responses. + + +Structured output transforms AI responses from freeform text into actionable, parseable data. + + +## Why Structure Matters + + + +## Basic Formatting Techniques + +### Lists + +Lists are perfect for step-by-step instructions, ranked items, or collections of related points. They're easy to scan and parse. Use **numbered lists** when order matters (steps, rankings) and **bullet points** for unordered collections. + + + + +Specify the exact number of items you want, whether to include explanations, and if items should be bold or have a specific structure. + + +### Tables + +Tables excel at comparing multiple items across the same dimensions. They're ideal for feature comparisons, data summaries, and any information with consistent attributes. Always define your column headers explicitly. + + + + +Specify column names, expected data types (text, numbers, ratings), and how many rows you need. For complex comparisons, limit to 4-6 columns for readability. + + +### Headers and Sections + +Headers create a clear document structure, making long responses scannable and organized. Use them for reports, analyses, or any multi-part response. Hierarchical headers (##, ###) show relationships between sections. + +``` +Analyze this business proposal. + +Structure your response with these sections: +## Executive Summary +## Strengths +## Weaknesses +## Recommendations +## Risk Assessment +``` + + +List your sections in the order you want them. For consistency, specify what each section should contain (e.g., "Executive Summary: 2-3 sentences only"). + + +### Emphasis with Uppercase Directives + +Uppercase words act as strong signals to the model, emphasizing critical constraints or requirements. Use them sparingly for maximum impact—overuse dilutes their effectiveness. + +**Common Uppercase Directives:** + + + +``` +Summarize this article. + +IMPORTANT: Keep the summary under 100 words. +NEVER add information not present in the original. +ALWAYS maintain the original tone and perspective. +DO NOT include your own opinions or analysis. +``` + + +If everything is uppercase or marked as critical, nothing stands out. Reserve these directives for genuinely important constraints. + + +## JSON Output + +JSON (JavaScript Object Notation) is the most popular format for structured AI output. It's machine-readable, widely supported by programming languages, and perfect for APIs, databases, and automation workflows. The key to reliable JSON is providing a clear schema. + +### Basic JSON Request + +Start with a template showing the exact structure you want. Include field names, data types, and example values. This acts as a contract the model will follow. + + + +### Complex JSON Structures + +For nested data, use hierarchical JSON with objects inside objects, arrays of objects, and mixed types. Define each level clearly and use TypeScript-style annotations (`"positive" | "negative"`) to constrain values. + +``` +Analyze this product review and return JSON: + +{ + "review_id": "string (generate unique)", + "sentiment": { + "overall": "positive" | "negative" | "mixed" | "neutral", + "score": 0.0-1.0 + }, + "aspects": [ + { + "aspect": "string (e.g., 'price', 'quality')", + "sentiment": "positive" | "negative" | "neutral", + "mentions": ["exact quotes from review"] + } + ], + "purchase_intent": { + "would_recommend": boolean, + "confidence": 0.0-1.0 + }, + "key_phrases": ["string array of notable phrases"] +} + +Return ONLY valid JSON, no additional text. + +Review: "[review text]" +``` + +### Ensuring Valid JSON + +Models sometimes add explanatory text or markdown formatting around JSON. Prevent this with explicit instructions about output format. You can request raw JSON or JSON inside code blocks—choose based on your parsing needs. + +Add explicit instructions: + +``` +IMPORTANT: +- Return ONLY the JSON object, no markdown code blocks +- Ensure all strings are properly escaped +- Use null for missing values, not undefined +- Validate that the output is parseable JSON +``` + +Or request code blocks by asking the model to wrap its output: + +```` +Return the result as a JSON code block: +```json +{ ... } +``` +```` + +## YAML Output + +YAML is more human-readable than JSON, using indentation instead of brackets. It's the standard for configuration files (Docker, Kubernetes, GitHub Actions) and works well when the output will be read by humans or used in DevOps contexts. YAML is sensitive to indentation, so be specific about formatting requirements. + + + +## XML Output + +XML is still required for many enterprise systems, SOAP APIs, and legacy integrations. It's more verbose than JSON but offers features like attributes, namespaces, and CDATA sections for complex data. Specify element names, nesting structure, and where to use attributes vs. child elements. + +``` +Convert this data to XML format: + +Requirements: +- Root element: +- Each item in element +- Include attributes where appropriate +- Use CDATA for description text + +Data: [book data] +``` + +## Custom Formats + +Sometimes standard formats don't fit your needs. You can define any custom format by providing a clear template. Custom formats work well for reports, logs, or domain-specific outputs that will be read by humans. + +### Structured Analysis Format + +Use delimiters (===, ---, [SECTION]) to create scannable documents with clear boundaries between sections. This format is great for code reviews, audits, and analyses. + +``` +Analyze this code using this exact format: + +=== CODE ANALYSIS === + +[SUMMARY] +One paragraph overview + +[ISSUES] +• CRITICAL: [issue] — [file:line] +• WARNING: [issue] — [file:line] +• INFO: [issue] — [file:line] + +[METRICS] +Complexity: [Low/Medium/High] +Maintainability: [score]/10 +Test Coverage: [estimated %] + +[RECOMMENDATIONS] +1. [Priority 1 recommendation] +2. [Priority 2 recommendation] + +=== END ANALYSIS === +``` + +### Fill-in-the-Blank Format + +Templates with blanks (___) guide the model to fill in specific fields while maintaining exact formatting. This approach is excellent for forms, briefs, and standardized documents where consistency matters. + +``` +Complete this template for the given product: + +PRODUCT BRIEF +───────────── +Name: _______________ +Tagline: _______________ +Target User: _______________ +Problem Solved: _______________ +Key Features: + 1. _______________ + 2. _______________ + 3. _______________ +Differentiator: _______________ + +Product: [product description] +``` + +## Typed Responses + +Typed responses define categories or entity types that the model should recognize and label. This technique is essential for Named Entity Recognition (NER), classification tasks, and any extraction where you need to categorize information consistently. Define your types clearly with examples. + + + +## Multi-Part Structured Responses + +When you need comprehensive output covering multiple aspects, define distinct parts with clear boundaries. Specify exactly what goes in each part—format, length, and content type. This prevents the model from blending sections or omitting parts. + +``` +Research this topic and provide: + +### PART 1: EXECUTIVE SUMMARY +[2-3 sentence overview] + +### PART 2: KEY FINDINGS +[Exactly 5 bullet points] + +### PART 3: DATA TABLE +| Metric | Value | Source | +|--------|-------|--------| +[Include 5 rows minimum] + +### PART 4: RECOMMENDATIONS +[Numbered list of 3 actionable recommendations] + +### PART 5: FURTHER READING +[3 suggested resources with brief descriptions] +``` + +## Conditional Formatting + +Conditional formatting lets you define different output formats based on the input's characteristics. This is powerful for classification, triage, and routing systems where the response format should vary based on what the model detects. Use clear if/then logic with explicit output templates for each case. + + + +## Arrays and Lists in JSON + +Extracting multiple items into arrays requires careful schema definition. Specify the array structure, what each item should contain, and how to handle edge cases (empty arrays, single items). Including a count field helps verify completeness. + +``` +Extract all action items from this meeting transcript. + +Return as JSON array: +{ + "action_items": [ + { + "task": "string describing the task", + "assignee": "person name or 'Unassigned'", + "deadline": "date if mentioned, else null", + "priority": "high" | "medium" | "low", + "context": "relevant quote from transcript" + } + ], + "total_count": number +} + +Transcript: "[meeting transcript]" +``` + +## Validation Instructions + +Self-validation prompts the model to check its own output before responding. This catches common issues like missing sections, placeholder text, or constraint violations. The model will iterate internally to fix problems, improving output quality without additional API calls. + +``` +Generate the report, then: + +VALIDATION CHECKLIST: +□ All required sections present +□ No placeholder text remaining +□ All statistics include sources +□ Word count within 500-700 words +□ Conclusion ties back to introduction + +If any check fails, fix before responding. +``` + +## Handling Optional Fields + +Real-world data often has missing values. Explicitly instruct the model on how to handle optional fields—using `null` is cleaner than empty strings and easier to process programmatically. Also prevent "hallucination" of missing data by emphasizing that the model should never invent information. + +``` +Extract contact information. Use null for missing fields. + +{ + "name": "string (required)", + "email": "string or null", + "phone": "string or null", + "company": "string or null", + "role": "string or null", + "linkedin": "URL string or null" +} + +IMPORTANT: +- Never invent information not in the source +- Use null, not empty strings, for missing data +- Phone numbers in E.164 format if possible +``` + +## Summary + + +Be explicit about format, use examples, specify types, handle edge cases with null values, and ask the model to validate its own output. + + + + +Structured outputs are essential for building reliable AI-powered applications. In the next chapter, we'll explore chain-of-thought prompting for complex reasoning tasks. diff --git a/src/content/book/zh/06-chain-of-thought.mdx b/src/content/book/zh/06-chain-of-thought.mdx new file mode 100644 index 00000000..e579be5d --- /dev/null +++ b/src/content/book/zh/06-chain-of-thought.mdx @@ -0,0 +1,363 @@ +Chain of Thought (CoT) prompting is a technique that dramatically improves AI performance on complex reasoning tasks by asking the model to show its work step by step. + + +Just like a math teacher asking students to show their work, CoT prompting asks the AI to make its reasoning visible. + + +## The Problem CoT Solves + +AI models can struggle with multi-step reasoning when asked to jump directly to an answer. + + + +## Basic CoT Prompts + +### Simple Trigger Phrases + +Add one of these to your prompts: + +
+
"Let's think step by step."
+
"Think through this carefully."
+
"Work through this problem methodically."
+
"Show your reasoning at each step."
+
"Explain your thought process."
+
+ +### Explicit Step Request + + + +## Zero-Shot vs Few-Shot CoT + +There are two main approaches to Chain of Thought prompting, each with different trade-offs between simplicity and control. + +### Zero-Shot CoT + +The simplest approach—just add a trigger phrase and let the model figure out how to reason. No examples needed. This works surprisingly well for many problems, though you have less control over the reasoning format. + + + +**Example Output:** +``` +Let's think step by step. +- John starts with 3 apples +- Half of 3 is 1.5, but we can't split apples +- If we round down: John gives 1 apple, keeps 2 +- After buying 4 more: 2 + 4 = 6 apples + +Answer: 6 apples +``` + +### Few-Shot CoT + +For more consistent results, show the model exactly how you want it to reason by providing worked examples. This gives you control over the reasoning style, format, and level of detail. The model will mimic your demonstrated pattern. + + + +**Example Output:** +``` +A: Let's work through this: +- Regular price: $3, Quantity: 12 +- Since 12 ≥ 10, the 25% discount applies +- Regular total: 12 × $3 = $36 +- Discount: 25% of $36 = $9 +- Final price: $36 - $9 = $27 +``` + +## Structured CoT Formats + +For consistent, reproducible reasoning, use structured formats with named steps. These frameworks ensure the model doesn't skip important stages and makes outputs easier to parse and verify. + +### The BREAK Format + +A memorable acronym that guides the model through a complete problem-solving cycle, from understanding to verification. + + + +### The Reasoning Template + +A more formal structure that separates inputs, goals, and execution. Excellent for technical problems where you need clear documentation of the solution process. + + + +**Example Output:** +``` +GIVEN: 8L/100km, tank 45L, $1.50/L, drive 300km +GOAL: Calculate fuel cost +APPROACH: Fuel needed × cost per liter +STEPS: +1. Fuel = (300 ÷ 100) × 8 = 24 liters +2. Cost = 24 × $1.50 = $36 +VERIFICATION: 24L < 45L tank ✓ +ANSWER: $36 +``` + +## CoT for Different Problem Types + +Different problem types benefit from different CoT approaches. Here are patterns optimized for common scenarios. + +### Mathematical Reasoning + +Math problems benefit most from CoT because each step builds on the previous one. Errors compound, so showing work helps catch mistakes early. The model should clearly label each calculation. + + + +**Example Output:** +``` +Q1: $1,200,000 (given) +Q2: $1,200,000 × 1.15 = $1,380,000 +Q3: $1,380,000 × 0.90 = $1,242,000 +Q4: $1,242,000 × 1.25 = $1,552,500 + +Total: $5,374,500 +``` + +### Logical Reasoning + +Logic puzzles require systematic elimination and hypothesis testing. CoT helps the model track constraints, test possibilities, and verify that all conditions are satisfied. The key is methodical exploration rather than guessing. + + + +**Example Output:** +``` +From clue 3: Bob = teacher +→ Alice and Carol are engineer/doctor + +If Carol = engineer: +- Carol has dog (clue 2) +- Alice = doctor, has fish (clue 1) +- Bob has cat + +Verify: All 4 clues satisfied ✓ +Answer: Alice (doctor, fish), Bob (teacher, cat), Carol (engineer, dog) +``` + +### Code Debugging + +Debugging benefits from CoT because it forces the model to trace execution rather than guess at bugs. By walking through the code with concrete values, the actual behavior becomes visible and discrepancies with expected behavior are exposed. + + + +**Example Output:** +``` +Trace [2, 3, 4, 6]: +n=2: total += 1 → 1 (wait, adding 1 not n!) +n=3: skip (odd) +n=4: total = 2 +n=6: total = 3 + +BUG: "total += 1" should be "total += n" +Expected: 12, Got: 3 +Fix: Change to "total += n" +``` + +## Self-Consistency with CoT + +For critical problems, don't rely on a single reasoning path. Generate multiple independent solutions and compare results. If different approaches converge on the same answer, confidence is high. Disagreement signals the need for careful review. + + + +**Example Output:** +``` +Approach 1 (Algebra): c + w = 30, 2c + 4w = 74 → c=23, w=7 +Approach 2 (Guess): Try 23/7 → 46 + 28 = 74 ✓ +Approach 3 (Logic): 30 chickens = 60 legs, need 14 more → 7 cows + +All agree: 23 chickens, 7 cows +``` + +## CoT for Decision Making + +Decisions involve weighing trade-offs across multiple dimensions. CoT ensures all relevant factors are considered systematically rather than jumping to conclusions. This structured approach also documents the reasoning for future reference. + + + +**Example Output:** +``` +FACTORS: +- Team size (5): Too small for microservices ❌ +- Scale (100 DAU): No scaling need ❌ +- Velocity: Monolith = faster iteration ❌ +- Future growth: Uncertain timeline ⚠️ + +WEIGHING: 3 strong against, 1 weak for + +RECOMMENDATION: Stay monolith, use clear module +boundaries to ease future transition. +``` + +## When to Use CoT + +
+
+

Use CoT For

+
+

**Math problems** — Reduces calculation errors

+

**Logic puzzles** — Prevents skipped steps

+

**Complex analysis** — Organizes thinking

+

**Code debugging** — Traces execution

+

**Decision making** — Weighs trade-offs

+
+
+
+

Skip CoT For

+
+

**Simple Q&A** — Unnecessary overhead

+

**Creative writing** — Can constrain creativity

+

**Factual lookups** — No reasoning needed

+

**Translation** — Direct task

+

**Summarization** — Usually straightforward

+
+
+
+ +## CoT Limitations + +While powerful, Chain of Thought isn't a silver bullet. Understanding its limitations helps you apply it appropriately. + +1. **Increased token usage** — More output means higher costs +2. **Not always needed** — Simple tasks don't benefit +3. **Can be verbose** — May need to ask for conciseness +4. **Reasoning can be flawed** — CoT doesn't guarantee correctness + +## Summary + + +CoT dramatically improves complex reasoning by making implicit steps explicit. Use it for math, logic, analysis, and debugging. Trade-off: better accuracy for more tokens. + + + + +In the next chapter, we'll explore few-shot learning—teaching the model through examples. diff --git a/src/content/book/zh/07-few-shot-learning.mdx b/src/content/book/zh/07-few-shot-learning.mdx new file mode 100644 index 00000000..24e98f1d --- /dev/null +++ b/src/content/book/zh/07-few-shot-learning.mdx @@ -0,0 +1,478 @@ +Few-shot learning is one of the most powerful prompting techniques. By providing examples of what you want, you can teach the model complex tasks without any fine-tuning. + + +Just like humans learn by seeing examples, AI models can learn patterns from the examples you provide in your prompt. + + +## What is Few-Shot Learning? + +Few-shot learning shows the model examples of input-output pairs before asking it to perform the same task. The model learns the pattern from your examples and applies it to new inputs. + + + +
+
+
0
+
Zero-shot
+
+
+
1
+
One-shot
+
+
+
2-5
+
Few-shot
+
+
+
5+
+
Many-shot
+
+
+ +## Why Examples Work + + + +Examples communicate: +- **Format**: How output should be structured +- **Style**: Tone, length, vocabulary +- **Logic**: The reasoning pattern to follow +- **Edge cases**: How to handle special situations + +## Basic Few-Shot Pattern + +The fundamental structure of few-shot prompting follows a simple pattern: show examples, then ask for the new task. Consistency in formatting between examples is crucial. The model learns from the pattern you establish. + +``` +[Example 1] +Input: [input 1] +Output: [output 1] + +[Example 2] +Input: [input 2] +Output: [output 2] + +[Example 3] +Input: [input 3] +Output: [output 3] + +Now do this one: +Input: [new input] +Output: +``` + +## Few-Shot for Classification + +Classification is one of the strongest use cases for few-shot learning. By showing examples of each category, you define the boundaries between classes more precisely than instructions alone could achieve. + +### Sentiment Analysis + + +Sentiment analysis classifies text by emotional tone: positive, negative, neutral, or mixed. It's widely used for customer feedback, social media monitoring, and brand perception tracking. + + +Sentiment classification benefits from showing examples of each sentiment type, especially edge cases like "mixed" sentiment that might be ambiguous. + + + +### Topic Classification + +For multi-class categorization, include at least one example per category. This helps the model understand your specific taxonomy, which may differ from its default understanding. + + + +## Few-Shot for Transformation + +Transformation tasks convert input from one form to another while preserving meaning. Examples are essential here because they define exactly what "transformation" means for your use case. + +### Text Rewriting + +Style transformation requires examples that show the exact tone shift you want. Abstract instructions like "make it professional" are interpreted differently. Examples make it concrete. + + + +### Format Conversion + +Format conversion tasks benefit from examples showing edge cases and ambiguous inputs. The model learns your specific conventions for handling tricky cases. + + + +## Few-Shot for Generation + +Generation tasks create new content following a learned pattern. Examples establish length, structure, tone, and what details to highlight. These are hard to specify in instructions alone. + +### Product Descriptions + +Marketing copy benefits enormously from examples because they capture brand voice, feature emphasis, and persuasive techniques that are difficult to describe abstractly. + + + +### Code Documentation + + +Good documentation explains what code does, its parameters, return values, and usage examples. Consistent docstrings enable auto-generated API docs and help IDEs provide better code completion. + + +Documentation style varies widely between projects. Examples teach your specific format, what to include (args, returns, examples), and the level of detail expected. + +>> calculate_bmi(70, 1.75) + 22.86 +""" + +Now document: +Function: +def is_palindrome(text): + cleaned = ''.join(c.lower() for c in text if c.isalnum()) + return cleaned == cleaned[::-1] + +Documentation:`} /> + +## Few-Shot for Extraction + +Extraction tasks pull structured information from unstructured text. Examples define which entities matter, how to format output, and how to handle cases where information is missing or ambiguous. + +### Entity Extraction + + +Named Entity Recognition (NER) identifies and classifies named entities in text into categories like persons, organizations, locations, dates, and products. It's fundamental for information retrieval and knowledge graphs. + + +NER benefits from examples showing your specific entity types and how to handle entities that could fit multiple categories. + + + +### Structured Data Extraction + +Extracting structured data from natural language requires examples showing how to handle missing fields, implicit information, and varying input formats. + + + +## Advanced Few-Shot Techniques + +Beyond basic few-shot, several techniques can improve results for complex tasks. + +### Diverse Examples + +Diversity in examples is more valuable than quantity. Cover different scenarios, edge cases, and potential ambiguities rather than showing similar examples repeatedly. + + + +### Negative Examples + + +Showing "good" vs "bad" examples is called contrastive learning. It helps the model understand not just what you want, but what to avoid. This is especially useful for style and quality judgments. + + +Sometimes showing what *not* to do is as valuable as showing correct examples. Negative examples help the model understand boundaries and avoid common mistakes. + + + +### Edge Case Examples + +Edge cases often determine whether a solution works in production. Including unusual inputs in your examples prevents the model from failing on real-world data that doesn't fit the "happy path." + + + +## How Many Examples? + +
+
+ Simple classification + 2-3 + One per category minimum +
+
+ Complex formatting + 3-5 + Show variations +
+
+ Nuanced style + 4-6 + Capture full range +
+
+ Edge cases + 1-2 + Alongside normal examples +
+
+ +## Example Quality Matters + + + +## Combining Few-Shot with Other Techniques + +Few-shot learning combines powerfully with other prompting techniques. The examples provide the "what" while other techniques can add context, reasoning, or structure. + +### Few-Shot + Role + +Adding a role gives the model context for *why* it's doing the task, which can improve quality and consistency. + +``` +You are a legal contract reviewer. + +[examples of contract clause analysis] + +Now analyze: [new clause] +``` + +### Few-Shot + CoT + +Combining few-shot with Chain of Thought shows not just *what* answer to give, but *how* to reason through to that answer. This is powerful for tasks requiring judgment. + +``` +Classify and explain reasoning. + +Review: "Great features but overpriced" +Thinking: The review mentions positive aspects ("great features") +but also a significant negative ("overpriced"). The negative seems +to outweigh the positive based on the "but" conjunction. +Classification: Mixed-Negative + +[more examples with reasoning] + +Now classify with reasoning: +Review: "Exactly what I needed, arrived faster than expected" +``` + +## Summary + + +Few-shot learning teaches through demonstration and is often more effective than instructions alone. Use 2-5 diverse, correct examples and combine with other techniques for best results. + + + + +In the next chapter, we'll explore iterative refinement: the art of improving prompts through successive attempts. diff --git a/src/content/book/zh/08-iterative-refinement.mdx b/src/content/book/zh/08-iterative-refinement.mdx new file mode 100644 index 00000000..769f879a --- /dev/null +++ b/src/content/book/zh/08-iterative-refinement.mdx @@ -0,0 +1,387 @@ +Prompt engineering is rarely a one-shot process. The best prompts emerge through iteration—testing, observing, and refining until you achieve the desired results. + + +Think of your first prompt as a rough draft. Even experienced prompt engineers rarely nail it on the first try. + + +## The Iteration Cycle + +Effective prompt refinement follows a predictable cycle: write, test, analyze, and improve. Each iteration brings you closer to a prompt that reliably produces the results you need. + + + +## Common Refinement Patterns + +Most prompt failures fall into a handful of categories. Learning to recognize these patterns lets you quickly diagnose and fix issues without starting from scratch. + +### Problem: Output Too Long + +One of the most common issues. Without explicit constraints, models tend to be thorough rather than concise. + + + +### Problem: Output Too Vague + +Vague prompts produce vague outputs. The model can't read your mind about what "better" means or which aspects matter most to you. + + + +### Problem: Wrong Tone + +Tone is subjective and varies by context. What sounds "professional" to the model might not match your organization's voice or the relationship with your recipient. + + + +### Problem: Missing Key Information + +Open-ended requests get open-ended responses. If you need specific types of feedback, you must ask for them explicitly. + + + +### Problem: Inconsistent Format + +Without a template, the model will structure each response differently, making comparison difficult and automation impossible. + + + +## Systematic Refinement Approach + +Random changes waste time. A systematic approach helps you identify problems quickly and fix them efficiently. + +### Step 1: Diagnose the Issue + +Before changing anything, identify what's actually wrong. Use this diagnostic table to map symptoms to solutions: + +
+
+ Symptom + Likely Cause + Solution +
+
+ Too long + No length constraint + Add word/sentence limits +
+
+ Too short + Lacks detail request + Ask for elaboration +
+
+ Off-topic + Vague instructions + Be more specific +
+
+ Wrong format + Format not specified + Define exact structure +
+
+ Wrong tone + Audience not clear + Specify audience/style +
+
+ Inconsistent + No examples provided + Add few-shot examples +
+
+ +### Step 2: Make Targeted Changes + +Resist the urge to rewrite everything. Changing multiple variables at once makes it impossible to know what helped and what hurt. Make one change, test it, then proceed: + +``` +Iteration 1: Add length constraint +Iteration 2: Specify format +Iteration 3: Add example +Iteration 4: Refine tone instructions +``` + +### Step 3: Document What Works + +Prompt engineering knowledge is easily lost. Keep a log of what you tried and why. This saves time when you revisit the prompt later or face similar challenges: + +```markdown +## Prompt: Customer Email Response + +### Version 1 (too formal) +"Write a response to this customer complaint." + +### Version 2 (better tone, still missing structure) +"Write a friendly but professional response to this complaint. +Show empathy first." + +### Version 3 (final - good results) +"Write a response to this customer complaint. Structure: +1. Acknowledge their frustration (1 sentence) +2. Apologize specifically (1 sentence) +3. Explain solution (2-3 sentences) +4. Offer additional help (1 sentence) + +Tone: Friendly, professional, empathetic but not groveling." +``` + +## Real-World Iteration Example + +Let's walk through a complete iteration cycle to see how each refinement builds on the last. Notice how each version addresses specific shortcomings of the previous one. + +### Task: Generate Product Names + + + +## Refinement Strategies by Task Type + +Different tasks fail in predictable ways. Knowing the common failure modes helps you diagnose and fix issues faster. + +### For Content Generation + +Content generation often produces generic, off-target, or poorly formatted output. The fix usually involves being more specific about constraints, providing concrete examples, or defining your brand voice explicitly. + + + +### For Code Generation + +Code output can fail technically (syntax errors, wrong language features) or architecturally (poor patterns, missing cases). Technical issues need version/environment specifics; architectural issues need design guidance. + + + +### For Analysis + +Analysis tasks often produce surface-level or unstructured results. Guide the model with specific frameworks (SWOT, Porter's Five Forces), request multiple viewpoints, or provide a template for the output structure. + + + +### For Q&A + +Question-answering can be too terse or too verbose, and may lack confidence indicators or sources. Specify the detail level you need and whether you want citations or uncertainty expressed. + + + +## The Feedback Loop Technique + +Here's a meta-technique: use the model itself to help improve your prompts. Share what you tried, what you got, and what you wanted. The model can often suggest improvements you hadn't considered. + +``` +I used this prompt: +"[your prompt]" + +And got this output: +"[model output]" + +I wanted something more [describe gap]. How should I modify +my prompt to get better results? +``` + +## A/B Testing Prompts + +For prompts that will be used repeatedly or at scale, don't just pick the first one that works. Test variations to find the most reliable and highest-quality approach. + +``` +Prompt A: "Summarize this article in 3 bullet points." +Prompt B: "Extract the 3 most important insights from this article." +Prompt C: "What are the key takeaways from this article? List 3." +``` + +Run each multiple times, compare: +- Consistency of output +- Quality of information +- Relevance to your needs + +## When to Stop Iterating + +Perfection is the enemy of good enough. Know when your prompt is ready for use and when you're just polishing for diminishing returns. + +
+
+

Ready to Ship

+
+

Output consistently meets requirements

+

Edge cases are handled appropriately

+

Format is reliable and parseable

+

Further improvements show diminishing returns

+
+
+
+

Keep Iterating

+
+

Output is inconsistent across runs

+

Edge cases cause failures

+

Critical requirements are missed

+

You haven't tested enough variations

+
+
+
+ +## Version Control for Prompts + +Prompts are code. For any prompt used in production, treat it with the same rigor: version control, changelogs, and the ability to roll back if something breaks. + + +prompts.chat includes automatic version history for your prompts. Every edit is saved, so you can compare versions and restore previous iterations with one click. + + +For self-managed prompts, use a folder structure: + +``` +prompts/ +├── customer-response/ +│ ├── v1.0.txt # Initial version +│ ├── v1.1.txt # Fixed tone issue +│ ├── v2.0.txt # Major restructure +│ └── current.txt # Symlink to active version +└── changelog.md # Document changes +``` + +## Summary + + +Start simple, observe carefully, change one thing at a time, document what works, and know when to stop. The best prompts aren't written—they're discovered through systematic iteration. + + + + +## Practice: Improve This Prompt + +Try improving this weak prompt yourself. Edit it, then use AI to compare your version with the original: + + + +In the next chapter, we'll explore JSON and YAML prompting for structured data applications. diff --git a/src/content/book/zh/09-json-yaml-prompting.mdx b/src/content/book/zh/09-json-yaml-prompting.mdx new file mode 100644 index 00000000..318619da --- /dev/null +++ b/src/content/book/zh/09-json-yaml-prompting.mdx @@ -0,0 +1,586 @@ +Structured data formats like JSON and YAML are essential for building applications that consume AI outputs programmatically. This chapter covers techniques for reliable structured output generation. + + +JSON and YAML transform AI outputs from freeform text into structured, type-safe data that code can consume directly. + + +## Why Structured Formats? + + + +## JSON Prompting Basics + +JSON (JavaScript Object Notation) is the most common format for programmatic AI outputs. Its strict syntax makes it easy to parse, but also means small errors can break your entire pipeline. + +### Do's and Don'ts: Requesting JSON + + + +### Simple JSON Output + +Start with a schema showing the expected structure. The model will fill in values based on the input text. + +``` +Extract the following information as JSON: + +{ + "name": "string", + "age": number, + "email": "string" +} + +Text: "Contact John Smith, 34 years old, at john@example.com" +``` + +Output: +```json +{ + "name": "John Smith", + "age": 34, + "email": "john@example.com" +} +``` + +### Nested JSON Structures + +Real-world data often has nested relationships. Define each level of your schema clearly, especially for arrays of objects. + +``` +Parse this order into JSON: + +{ + "order_id": "string", + "customer": { + "name": "string", + "email": "string" + }, + "items": [ + { + "product": "string", + "quantity": number, + "price": number + } + ], + "total": number +} + +Order: "Order #12345 for Jane Doe (jane@email.com): 2x Widget ($10 each), +1x Gadget ($25). Total: $45" +``` + +### Ensuring Valid JSON + + +Models often wrap JSON in markdown code blocks or add explanatory text. Be explicit about wanting raw JSON only. + + +Add explicit instructions: + +``` +CRITICAL: Return ONLY valid JSON. No markdown, no explanation, +no additional text before or after the JSON object. + +If a field cannot be determined, use null. +Ensure all strings are properly quoted and escaped. +Numbers should not be quoted. +``` + +## YAML Prompting Basics + +YAML is more human-readable than JSON and supports comments. It's the standard for configuration files, especially in DevOps (Docker, Kubernetes, GitHub Actions). + +### Simple YAML Output + +YAML uses indentation instead of braces. Provide a template showing the expected structure. + +``` +Generate a configuration file in YAML format: + +server: + host: string + port: number + ssl: boolean +database: + type: string + connection_string: string + +Requirements: Production server on port 443 with SSL, PostgreSQL database +``` + +Output: +```yaml +server: + host: "0.0.0.0" + port: 443 + ssl: true +database: + type: "postgresql" + connection_string: "postgresql://user:pass@localhost:5432/prod" +``` + +### Complex YAML Structures + +For complex configurations, be specific about requirements. The model knows common patterns for tools like GitHub Actions, Docker Compose, and Kubernetes. + +``` +Generate a GitHub Actions workflow in YAML: + +Requirements: +- Trigger on push to main and pull requests +- Run on Ubuntu latest +- Steps: checkout, setup Node 18, install dependencies, run tests +- Cache npm dependencies +``` + +## Type Definitions in Prompts + +Type definitions give the model a precise contract for output structure. They're more explicit than examples and easier to validate programmatically. + +### Using TypeScript-like Types + +TypeScript interfaces are familiar to developers and precisely describe optional fields, union types, and arrays. The prompts.chat platform uses this approach for structured prompts. + + + +### JSON Schema Definition + + +JSON Schema is a formal specification for describing JSON structure. It's supported by many validation libraries and API tools. + + +JSON Schema provides constraints like min/max values, required fields, and regex patterns: + +``` +Extract data according to this JSON Schema: + +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "type": "object", + "required": ["title", "author", "year"], + "properties": { + "title": { "type": "string" }, + "author": { "type": "string" }, + "year": { "type": "integer", "minimum": 1000, "maximum": 2100 }, + "genres": { + "type": "array", + "items": { "type": "string" } + }, + "rating": { + "type": "number", + "minimum": 0, + "maximum": 5 + } + } +} + +Book: "1984 by George Orwell (1949) - A dystopian masterpiece. +Genres: Science Fiction, Political Fiction. Rated 4.8/5" +``` + +## Handling Arrays + +Arrays require special attention. Specify whether you need a fixed number of items or a variable-length list, and how to handle empty cases. + +### Fixed-Length Arrays + +When you need exactly N items, state it explicitly. The model will ensure the array has the right length. + +``` +Extract exactly 3 key points as JSON: + +{ + "key_points": [ + "string (first point)", + "string (second point)", + "string (third point)" + ] +} + +Article: [article text] +``` + +### Variable-Length Arrays + +For variable-length arrays, specify what to do when there are zero items. Including a count field helps verify extraction completeness. + +``` +Extract all mentioned people as JSON: + +{ + "people": [ + { + "name": "string", + "role": "string or null if not mentioned" + } + ], + "count": number +} + +If no people are mentioned, return empty array. + +Text: [text] +``` + +## Enum Values and Constraints + +Enums restrict values to a predefined set. This is crucial for classification tasks and anywhere you need consistent, predictable outputs. + +### Do's and Don'ts: Enum Values + + + +### String Enums + +List allowed values explicitly. Use "MUST be one of" language to enforce strict matching. + +``` +Classify this text. The category MUST be one of these exact values: +- "technical" +- "business" +- "creative" +- "personal" + +Return JSON: +{ + "text": "original text (truncated to 50 chars)", + "category": "one of the enum values above", + "confidence": number between 0 and 1 +} + +Text: [text to classify] +``` + +### Validated Numbers + +Numeric constraints prevent out-of-range values. Specify the type (integer vs float) and valid range. + +``` +Rate these aspects. Each score MUST be an integer from 1 to 5. + +{ + "quality": 1-5, + "value": 1-5, + "service": 1-5, + "overall": 1-5 +} + +Review: [review text] +``` + +## Handling Missing Data + +Real-world text often lacks some information. Define how the model should handle missing data to avoid hallucinated values. + +### Do's and Don'ts: Missing Information + + + +### Null Values + +Explicitly allow null and instruct the model not to invent information. This is safer than having the model guess. + +``` +Extract information. Use null for any field that cannot be +determined from the text. Do NOT invent information. + +{ + "company": "string or null", + "revenue": "number or null", + "employees": "number or null", + "founded": "number (year) or null", + "headquarters": "string or null" +} + +Text: "Apple, headquartered in Cupertino, was founded in 1976." +``` + +Output: +```json +{ + "company": "Apple", + "revenue": null, + "employees": null, + "founded": 1976, + "headquarters": "Cupertino" +} +``` + +### Default Values + +When defaults make sense, specify them in the schema. This is common for configuration extraction. + +``` +Extract settings with these defaults if not specified: + +{ + "theme": "light" (default) | "dark", + "language": "en" (default) | other ISO code, + "notifications": true (default) | false, + "fontSize": 14 (default) | number +} + +User preferences: "I want dark mode and larger text (18px)" +``` + +## Multi-Object Responses + +Often you need to extract multiple items from a single input. Define the array structure and any sorting/grouping requirements. + +### Array of Objects + +For lists of similar items, define the object schema once and specify it's an array. + +``` +Parse this list into JSON array: + +[ + { + "task": "string", + "priority": "high" | "medium" | "low", + "due": "ISO date string or null" + } +] + +Todo list: +- Finish report (urgent, due tomorrow) +- Call dentist (low priority) +- Review PR #123 (medium, due Friday) +``` + +### Grouped Objects + +Grouping tasks require categorization logic. The model will sort items into the categories you define. + +``` +Categorize these items into JSON: + +{ + "fruits": ["string array"], + "vegetables": ["string array"], + "other": ["string array"] +} + +Items: apple, carrot, bread, banana, broccoli, milk, orange, spinach +``` + +## YAML for Configuration Generation + +YAML shines for DevOps configurations. The model knows standard patterns for common tools and can generate production-ready configs. + +### Do's and Don'ts: YAML Configs + + + +### Docker Compose + +Specify the services you need and any special requirements. The model will handle the YAML syntax and best practices. + +``` +Generate a docker-compose.yml for: +- Node.js app on port 3000 +- PostgreSQL database +- Redis cache +- Nginx reverse proxy + +Include: +- Health checks +- Volume persistence +- Environment variables from .env file +- Network isolation +``` + +### Kubernetes Manifests + +Kubernetes manifests are verbose but follow predictable patterns. Provide the key parameters and the model will generate compliant YAML. + +``` +Generate Kubernetes deployment YAML: + +Deployment: +- Name: api-server +- Image: myapp:v1.2.3 +- Replicas: 3 +- Resources: 256Mi memory, 250m CPU (requests) +- Health checks: /health endpoint +- Environment from ConfigMap: api-config + +Also generate matching Service (ClusterIP, port 8080) +``` + +## Validation and Error Handling + +For production systems, build validation into your prompts. This catches errors before they propagate through your pipeline. + +### Self-Validation Prompt + +Ask the model to validate its own output against rules you specify. This catches format errors and invalid values. + +``` +Extract data as JSON, then validate your output. + +Schema: +{ + "email": "valid email format", + "phone": "E.164 format (+1234567890)", + "date": "ISO 8601 format (YYYY-MM-DD)" +} + +After generating JSON, check: +1. Email contains @ and valid domain +2. Phone starts with + and contains only digits +3. Date is valid and parseable + +If validation fails, fix the issues before responding. + +Text: [contact information] +``` + +### Error Response Format + +Define separate success and error formats. This makes programmatic handling much easier. + +``` +Attempt to extract data. If extraction fails, return error format: + +Success format: +{ + "success": true, + "data": { ... extracted data ... } +} + +Error format: +{ + "success": false, + "error": "description of what went wrong", + "partial_data": { ... any data that could be extracted ... } +} +``` + +## JSON vs YAML: When to Use Which + +
+
+
Use JSON When
+
+

Programmatic parsing needed

+

API responses

+

Strict type requirements

+

JavaScript/Web integration

+

Compact representation

+
+
+
+
Use YAML When
+
+

Human readability matters

+

Configuration files

+

Comments are needed

+

DevOps/Infrastructure

+

Deep nested structures

+
+
+
+ +## Prompts.chat Structured Prompts + +On prompts.chat, you can create prompts with structured output formats: + +``` +When creating a prompt on prompts.chat, you can specify: + +Type: STRUCTURED +Format: JSON or YAML + +The platform will: +- Validate outputs against your schema +- Provide syntax highlighting +- Enable easy copying of structured output +- Support template variables in your schema +``` + +## Common Pitfalls + + +These three issues cause most JSON parsing failures. Check for them when your code can't parse AI output. + + +### 1. Markdown Code Blocks + +**Problem:** Model wraps JSON in ```json blocks + +**Solution:** +``` +Return ONLY the JSON object. Do not wrap in markdown code blocks. +Do not include ```json or ``` markers. +``` + +### 2. Trailing Commas + +**Problem:** Invalid JSON due to trailing commas + +**Solution:** +``` +Ensure valid JSON syntax. No trailing commas after the last +element in arrays or objects. +``` + +### 3. Unescaped Strings + +**Problem:** Quotes or special characters break JSON + +**Solution:** +``` +Properly escape special characters in strings: +- \" for quotes +- \\ for backslashes +- \n for newlines +``` + +## Summary + + +Define schemas explicitly using TypeScript interfaces or JSON Schema. Specify types and constraints, handle nulls and defaults, request self-validation, and choose the right format for your use case. + + + + +This completes Part II on techniques. In Part III, we'll explore practical applications across different domains. diff --git a/src/content/book/zh/10-system-prompts-personas.mdx b/src/content/book/zh/10-system-prompts-personas.mdx new file mode 100644 index 00000000..c6737cda --- /dev/null +++ b/src/content/book/zh/10-system-prompts-personas.mdx @@ -0,0 +1,435 @@ +System prompts are like giving AI its personality and job description before a conversation starts. Think of it as the "backstage instructions" that shape everything the AI says. + + +A system prompt is a special message that tells the AI who it is, how to behave, and what it can or can't do. Users don't usually see this message, but it affects every response. + + + +System prompts build on the concepts from [Role-Based Prompting](/book/04-role-based-prompting). While role prompts assign a persona within your message, system prompts set that identity at a deeper level that persists across the entire conversation. + + +## How System Prompts Work + +When you chat with AI, there are actually three types of messages: + + + +The system message stays active for the whole conversation. It's like the AI's "instruction manual." + +## Building a System Prompt + +A good system prompt has five parts. Think of them as filling out a character sheet for the AI: + + + +### Example: A Coding Tutor + + + +## Persona Patterns + +Different tasks need different AI personalities. Here are three common patterns you can adapt: + +### 1. The Expert + +Best for: Learning, research, professional advice + + + +### 2. The Assistant + +Best for: Productivity, organization, getting things done + + + +### 3. The Character + +Best for: Creative writing, roleplay, entertainment + + + +## Advanced Techniques + +### Layered Instructions + +Think of your system prompt like an onion with layers. The inner layers are most important: + + + +### Adaptive Behavior + +Make your AI adjust to different users automatically: + + + +### Conversation Memory + +AI doesn't remember past conversations, but you can tell it to track things within the current chat: + + + +## Real-World Examples + +Here are complete system prompts for common use cases. Click to try them! + +### Customer Support Bot + + + +### Study Buddy + + + +### Writing Coach + + + +## Testing Your System Prompt + +Before using a system prompt for real, test it! Here's what to check: + + + +### Understanding Jailbreak Attacks + +"Jailbreaking" is when someone tries to trick AI into ignoring its rules. Understanding these attacks helps you build better defenses. + + + +### More Test Scenarios + +Use these interactive examples to see how a well-designed system prompt handles tricky situations: + +#### Test 1: Jailbreak Attempt + +See how a good system prompt resists attempts to override it: + + + +#### Test 2: Stay in Character + +Test if the AI maintains its persona when pushed: + + + +#### Test 3: Boundary Enforcement + +Check if the AI respects its stated limitations: + + + +#### Test 4: Reveal System Prompt + +See if the AI protects its instructions: + + + +#### Test 5: Conflicting Instructions + +Test how the AI handles contradictory requests: + + + + +A well-crafted system prompt will: +- Politely decline inappropriate requests +- Stay in character while redirecting +- Not reveal confidential instructions +- Handle edge cases gracefully + + +## Quick Reference + +
+
+

Do

+
    +
  • Give a clear identity
  • +
  • List specific capabilities
  • +
  • Set explicit boundaries
  • +
  • Define the tone and style
  • +
  • Include example responses
  • +
+
+
+

Don't

+
    +
  • Be vague about the role
  • +
  • Forget to set limits
  • +
  • Make it too long (500 words max)
  • +
  • Contradict yourself
  • +
  • Assume the AI will "figure it out"
  • +
+
+
+ +## Summary + +System prompts are the AI's instruction manual. They set up: +- **Who** the AI is (identity and expertise) +- **What** it can and can't do (capabilities and limits) +- **How** it should respond (tone, format, style) + + +Begin with a short system prompt and add more rules as you discover what's needed. A clear 100-word prompt beats a confusing 500-word one. + + + + + + +In the next chapter, we'll explore prompt chaining: connecting multiple prompts together for complex multi-step tasks. diff --git a/src/content/book/zh/11-prompt-chaining.mdx b/src/content/book/zh/11-prompt-chaining.mdx new file mode 100644 index 00000000..9f54da52 --- /dev/null +++ b/src/content/book/zh/11-prompt-chaining.mdx @@ -0,0 +1,379 @@ +Prompt chaining breaks complex tasks into sequences of simpler prompts, where each step's output feeds into the next. This technique dramatically improves reliability and enables sophisticated workflows that would be impossible with a single prompt. + + +Just like a factory assembly line breaks manufacturing into specialized stations, prompt chaining breaks AI tasks into specialized steps. Each step does one thing well, and the combined output is far better than trying to do everything at once. + + +## Why Chain Prompts? + +Single prompts struggle with complex tasks because they try to do too much at once. The AI has to simultaneously understand, analyze, plan, and generate, which leads to errors and inconsistencies. + +
+
+

Single Prompt Struggles

+
+

Multi-step reasoning gets confused

+

Different "modes" of thinking clash

+

Complex outputs lack consistency

+

No opportunity for quality control

+
+
+
+

Chaining Solves This

+
+

Each step focuses on one task

+

Specialized prompts for each mode

+

Validate between steps

+

Debug and improve individual steps

+
+
+
+ +## Basic Chaining Pattern + +The simplest chain passes output from one prompt directly to the next. Each step has a clear, focused purpose. + +
+
+
+

Prompt 1

+

(Extract)

+
+

Input

+
+
→
+
+
+

Prompt 2

+

(Analyze)

+
+

Intermediate

+
+
→
+
+
+

Prompt 3

+

(Generate)

+
+

Output

+
+
+ + +The most common chain pattern is **Extract → Transform → Generate**. First extract raw data, then reshape it for your purpose, then generate the final output. This pattern works for almost any content task. + + +## Chain Types + +Different tasks require different chain architectures. Choose the pattern that matches your workflow. + + + +### Sequential Chain + +The most straightforward pattern: each step depends on the previous. Think of it as a relay race where each runner passes the baton to the next. + + + +### Parallel Chain + +When you need multiple perspectives on the same input, run prompts in parallel and merge results. This is faster than sequential chains and provides richer analysis. + + + +### Conditional Chain + +Route inputs through different paths based on classification. This is like a decision tree where the AI first categorizes the input, then handles each category differently. + + + +### Iterative Chain + +Keep refining output until it meets quality standards. The AI generates, evaluates, and improves in a loop until satisfied or max iterations reached. + + +Always set a maximum number of iterations (typically 3-5) to prevent infinite loops and control costs. The law of diminishing returns applies: most improvement happens in the first 2-3 iterations. + + += 8: EXIT LOOP' } + ]} +/> + +## Common Chain Patterns + +These battle-tested patterns solve common problems. Use them as starting points and adapt to your needs. + +### Extract → Transform → Generate + +The workhorse of content processing. Pull data out, reshape it, then create something new. + +
+

Best For

+

Document summarization, report generation, content repurposing, data-to-narrative conversion

+
+ + + +### Analyze → Plan → Execute + +Perfect for code refactoring, project planning, or any task where you need to understand before acting. + +
+

Best For

+

Code refactoring, project planning, troubleshooting, strategic decision-making, complex problem solving

+
+ + {\n const { email, password } = req.body;\n if (!email || !isValidEmail(email)) {\n return res.status(400).json({ error: 'Invalid email' });\n }\n next();\n};" } + ]} +/> + +### Generate → Critique → Refine + +The self-improvement loop. Generate content, have the AI evaluate it critically, then improve based on that feedback. This mimics how professional writers and editors work together. + +
+

Best For

+

Marketing copy, creative writing, email drafts, presentations, any content that benefits from revision

+
+ + + +## Implementing Chains + +You can implement chains manually for experimentation, or programmatically for production systems. Start simple and add complexity as needed. + +### Manual Chaining + +The copy-paste approach is perfect for prototyping and experimentation. Run each prompt manually, examine the output, and paste it into the next prompt. + + + +### Programmatic Chaining + +For production systems, automate the chain with code. This enables error handling, logging, and integration with your application. + + + +### Using Chain Templates + +Define chains as configuration files for reusability and easy modification. This separates prompt logic from application code. + + + +## Error Handling in Chains + +Chains can fail at any step. Build in validation, retries, and fallbacks to make your chains robust. + + + + +If one step produces bad output, every following step will be affected. Always validate critical intermediate results before passing them forward. + + +### Validation Between Steps + +Add a validation step after any step that produces structured data. This catches errors early before they cascade. + + + +### Fallback Chains + +When your primary approach fails, have a simpler backup ready. Trade capability for reliability. + + + +## Chain Optimization + +Once your chain works, optimize for speed, cost, and reliability. These often trade off against each other. + +
+
+

Reducing Latency

+
+

Parallelize independent steps

+

Cache intermediate results

+

Use smaller models for simple steps

+

Batch similar operations

+
+
+
+

Reducing Cost

+
+

Use cheaper models for classification

+

Limit iterations in loops

+

Short-circuit when possible

+

Cache repeated queries

+
+
+
+

Improving Reliability

+
+

Add validation between steps

+

Include retry logic

+

Log intermediate results

+

Implement fallback paths

+
+
+
+ +## Real-World Chain Example + +Let's walk through a complete production chain. This content pipeline transforms a raw idea into a polished article package. + +### Content Pipeline Chain + + + +## Summary + +Prompt chaining transforms what AI can accomplish by breaking impossible tasks into achievable steps. + +
+
+

Chaining Enables

+
+

Complex multi-step workflows

+

Higher quality through specialization

+

Better error handling and validation

+

Modular, reusable prompt components

+
+
+
+

Key Principles

+
+

Break complex tasks into simple steps

+

Design clear interfaces between steps

+

Validate intermediate outputs

+

Build in error handling and fallbacks

+

Optimize for your constraints

+
+
+
+ + +Begin with a 2-3 step sequential chain. Get it working reliably before adding complexity. Most tasks don't need elaborate chain architectures. + + + + +In the next chapter, we'll explore multimodal prompting: working with images, audio, and other non-text content. diff --git a/src/content/book/zh/12-handling-edge-cases.mdx b/src/content/book/zh/12-handling-edge-cases.mdx new file mode 100644 index 00000000..4708ee3c --- /dev/null +++ b/src/content/book/zh/12-handling-edge-cases.mdx @@ -0,0 +1,580 @@ +Prompts that work perfectly in testing often fail in the real world. Users send empty messages, paste walls of text, make ambiguous requests, and sometimes try to break your system intentionally. This chapter teaches you to build prompts that handle the unexpected gracefully. + + +80% of production issues come from inputs you never anticipated. A prompt that handles edge cases well is worth more than a "perfect" prompt that only works with ideal inputs. + + +## Why Edge Cases Break Prompts + +When a prompt encounters unexpected input, it typically fails in one of three ways: + +**Silent Failures**: The model produces output that looks correct but contains errors. These are the most dangerous because they're hard to detect. + +**Confused Responses**: The model misinterprets the request and answers a different question than what was asked. + +**Hallucinated Handling**: The model invents a way to handle the edge case that doesn't match your intended behavior. + + + +## Categories of Edge Cases + +Understanding what can go wrong helps you prepare for it. Edge cases fall into three main categories: + +### Input Edge Cases + +These are problems with the data itself: + + + +### Domain Edge Cases + +These are requests that push the boundaries of your prompt's purpose: + + + +### Adversarial Edge Cases + +These are deliberate attempts to misuse your system: + + + +## Input Validation Patterns + +The key to handling edge cases is explicit instructions. Don't assume the model will "figure it out" - tell it exactly what to do in each scenario. + +### Handling Empty Input + +The most common edge case is receiving nothing at all, or input that's essentially empty (just whitespace or greetings). + + + +### Handling Long Input + +When input exceeds what you can reasonably process, fail gracefully rather than silently truncating. + + + +### Handling Ambiguous Requests + +When a request could mean multiple things, asking for clarification is better than guessing wrong. + + + +## Building Defensive Prompts + +A defensive prompt anticipates failure modes and defines explicit behavior for each. Think of it as error handling for natural language. + +### The Defensive Template + +Every robust prompt should address these four areas: + + + +### Example: Defensive Data Extraction + +This prompt extracts contact information but handles every edge case explicitly. Notice how each potential failure has a defined response. + + + +## Handling Out-of-Scope Requests + +Every prompt has boundaries. Defining them explicitly prevents the model from wandering into territory where it might give bad advice or make things up. + +### Graceful Scope Limits + +The best out-of-scope responses do three things: acknowledge the request, explain the limitation, and offer an alternative. + + + +### Handling Knowledge Cutoffs + +Be honest about what you don't know. Users trust AI more when it admits limitations. + + + +## Adversarial Input Handling + +Some users will try to manipulate your prompts, either out of curiosity or malicious intent. Building defenses into your prompts reduces these risks. + +### Prompt Injection Defense + +Prompt injection is when a user tries to override your instructions by embedding their own commands in the input. The key defense is treating user input as data, never as instructions. + + + + +Prompt injection defenses reduce risk but can't eliminate it entirely. For high-stakes applications, combine prompt defenses with input sanitization, output filtering, and human review. + + +### Handling Sensitive Requests + +Some requests require special handling due to safety, legal, or ethical concerns. Define these boundaries explicitly. + + + +## Error Recovery Patterns + +Even well-designed prompts will encounter situations they can't handle perfectly. The goal is to fail helpfully. + +### Graceful Degradation + +When you can't fully complete a task, offer what you can rather than failing completely. + + + +### Confidence Indicators + +Teach your prompts to express uncertainty. This helps users know when to trust the output and when to verify. + + + + + +## Testing Edge Cases + +Before deploying a prompt, systematically test it against the edge cases you've anticipated. This checklist helps ensure you haven't missed common failure modes. + +### Edge Case Testing Checklist + + + + + + + + + +### Creating a Test Suite + +For production prompts, create a systematic test suite. Here's a pattern you can adapt: + + + +## Real-World Example: Robust Customer Service Bot + +This comprehensive example shows how all the patterns come together in a production-ready prompt. Notice how every edge case has explicit handling. + + + +## Summary + +Building robust prompts requires thinking about what can go wrong before it does. The key principles: + + + + +In production, everything that can go wrong eventually will. A prompt that handles edge cases gracefully is worth more than a "perfect" prompt that only works with ideal inputs. + + + + +In the next chapter, we'll explore how to work with multiple AI models and compare their outputs. diff --git a/src/content/book/zh/13-multimodal-prompting.mdx b/src/content/book/zh/13-multimodal-prompting.mdx new file mode 100644 index 00000000..376960ae --- /dev/null +++ b/src/content/book/zh/13-multimodal-prompting.mdx @@ -0,0 +1,665 @@ +For most of history, computers worked with one type of data at a time: text in one program, images in another, audio somewhere else. But humans don't experience the world this way. We see, hear, read, and speak simultaneously, combining all these inputs to understand our environment. + +**Multimodal AI** changes everything. These models can process multiple types of information together—analyzing an image while reading your question about it, or generating images from your text descriptions. This chapter teaches you how to communicate effectively with these powerful systems. + + +"Multi" means many, and "modal" refers to modes or types of data. A multimodal model can work with multiple modalities: text, images, audio, video, or even code. Instead of separate tools for each type, one model understands them all together. + + +## Why Multimodal Matters + +Traditional AI required you to describe everything in words. Want to ask about an image? You'd have to describe it first. Want to analyze a document? You'd need to transcribe it manually. Multimodal models eliminate these barriers. + + + +## Why Prompting Matters Even More for Multimodal + +With text-only models, the AI receives exactly what you type. But with multimodal models, the AI must interpret visual or audio information—and interpretation requires guidance. + + + +**Without guidance**, the model might describe colors, layout, or irrelevant details. **With guidance**, it focuses on what actually matters to you. + + +When you look at an image, you instantly know what's important based on your context and goals. The AI doesn't have this context unless you provide it. A photo of a crack in a wall could be: a structural engineering concern, an artistic texture, or irrelevant background. Your prompt determines how the AI interprets it. + + +## The Multimodal Landscape + +Different models have different capabilities. Here's what's available in 2025: + +### Understanding Models (Input → Analysis) + +These models accept various media types and produce text analysis or responses. + + + +### Generation Models (Text → Media) + +These models create images, audio, or video from text descriptions. + + + + +The multimodal landscape changes quickly. New models launch frequently, and existing models gain capabilities through updates. Always check the latest documentation for current features and limitations. + + +## Image Understanding Prompts + +The most common multimodal use case is asking AI to analyze images. The key is providing context about what you need. + +### Basic Image Analysis + +Start with a clear request structure. Tell the model what aspects to focus on. + + + +### Structured Output for Images + +When you need to process image analysis programmatically, request JSON output. + + + +### Comparative Analysis + +Comparing multiple images requires clear labeling and specific comparison criteria. + + + +## Document and Screenshot Analysis + +One of the most practical applications of multimodal AI is analyzing documents, screenshots, and UI elements. This saves hours of manual transcription and review. + +### Document Extraction + +Scanned documents, photos of receipts, and PDFs as images can all be processed. The key is telling the model what type of document it is and what information you need. + + + +### Screenshot and UI Analysis + +Screenshots are goldmines for debugging, UX review, and documentation. Guide the AI to focus on what matters. + + + +### Error Message Analysis + +When you encounter an error, a screenshot often contains more context than copying the error text alone. + + + +## Image Generation Prompts + +Generating images from text descriptions is an art form. The more specific and structured your prompt, the closer the result will match your vision. + +### The Anatomy of an Image Prompt + +Effective image generation prompts have several components: + + + +### Basic Image Generation + + + +### Scene Building + +For complex scenes, describe layers from foreground to background. + + + +## Audio Prompting + +Audio processing opens up transcription, analysis, and understanding of spoken content. The key is providing context about what the audio contains. + +### Enhanced Transcription + +Basic transcription is just the start. With good prompts, you can get speaker identification, timestamps, and domain-specific accuracy. + + + +### Audio Content Analysis + +Beyond transcription, AI can analyze the content, tone, and key moments in audio. + + + +## Video Prompting + +Video combines visual and audio analysis over time. The challenge is guiding the AI to focus on the relevant aspects across the entire duration. + +### Video Understanding + + + +### Video Content Extraction + +For specific information extraction from videos, be precise about what you need. + + + +## Multimodal Combinations + +The real power of multimodal AI emerges when you combine different types of input. These combinations enable analysis that would be impossible with any single modality. + +### Image + Text Verification + +Check if images and their descriptions match—essential for e-commerce, content moderation, and quality assurance. + + + +### Screenshot + Code Debugging + +One of the most powerful combinations for developers: seeing the visual bug alongside the code. + + + +### Multi-Image Decision Making + +When choosing between options, structured comparison helps make better decisions. + + + +## Best Practices for Multimodal Prompts + +Getting great results from multimodal AI requires understanding both its capabilities and limitations. + +### What Makes Multimodal Prompts Effective + + + +### Common Pitfalls to Avoid + + + +### Handling Limitations Gracefully + + + + diff --git a/src/content/book/zh/14-context-engineering.mdx b/src/content/book/zh/14-context-engineering.mdx new file mode 100644 index 00000000..b9c69b6d --- /dev/null +++ b/src/content/book/zh/14-context-engineering.mdx @@ -0,0 +1,287 @@ +Understanding context is essential for building AI applications that actually work. This chapter covers everything you need to know about giving AI the right information at the right time. + + +AI models are stateless. They don't remember past conversations. Every time you send a message, you need to include everything the AI needs to know. This is called "context engineering." + + +## What is Context? + +Context is all the information you give to AI alongside your question. Think of it like this: + + + +Without context, the AI has no idea what "status" you're asking about. With context, it can give a useful answer. + +### The Context Window + +Remember from earlier chapters: AI has a limited "context window" - the maximum amount of text it can see at once. This includes: + + + +## AI is Stateless + + +AI doesn't remember anything between conversations. Every API call starts fresh. If you want the AI to "remember" something, YOU have to include it in the context every time. + + +This is why chatbots send your entire conversation history with each message. It's not that the AI remembers - it's that the app re-sends everything. + + + +The AI will say it doesn't know because it truly doesn't have access to any previous context. + +## RAG: Retrieval-Augmented Generation + +RAG is a technique for giving AI access to knowledge it wasn't trained on. Instead of trying to fit everything into the AI's training, you: + +1. **Store** your documents in a searchable database +2. **Search** for relevant documents when a user asks a question +3. **Retrieve** the most relevant pieces +4. **Augment** your prompt with those pieces +5. **Generate** an answer using that context + +
+

How RAG Works:

+
+
+ 1 + User asks: "What's our refund policy?" +
+
+ 2 + System searches your documents for "refund policy" +
+
+ 3 + Finds relevant section from your policy document +
+
+ 4 + Sends to AI: "Based on this policy: [text], answer: What's our refund policy?" +
+
+ 5 + AI generates accurate answer using your actual policy +
+
+
+ +### Why RAG? + +
+
+

RAG Advantages

+
    +
  • Uses your actual, current data
  • +
  • Reduces hallucinations
  • +
  • Can cite sources
  • +
  • Easy to update (just update documents)
  • +
  • No expensive fine-tuning needed
  • +
+
+
+

When to Use RAG

+
    +
  • Customer support bots
  • +
  • Documentation search
  • +
  • Internal knowledge bases
  • +
  • Any domain-specific Q&A
  • +
  • When accuracy matters
  • +
+
+
+ +## Embeddings: How Search Works + +How does RAG know which documents are "relevant"? It uses **embeddings** - a way to turn text into numbers that capture meaning. + +### What Are Embeddings? + +An embedding is a list of numbers (a "vector") that represents the meaning of text. Similar meanings = similar numbers. + + + +### Semantic Search + +With embeddings, you can search by meaning, not just keywords: + + + +This is why RAG is so powerful - it finds relevant information even when the exact words don't match. + +## Function Calling / Tool Use + +Function calling lets AI use external tools - like searching the web, checking a database, or calling an API. + + +Different AI providers call this different things: "function calling" (OpenAI), "tool use" (Anthropic/Claude), or "tools" (general term). They all mean the same thing. + + +### How It Works + +1. You tell the AI what tools are available +2. AI decides if it needs a tool to answer +3. AI outputs a structured request for the tool +4. Your code runs the tool and returns results +5. AI uses the results to form its answer + + + +## Summarization: Managing Long Conversations + +As conversations get longer, you'll hit the context window limit. Since AI is stateless (it doesn't remember anything), long conversations can overflow. The solution? **Summarization**. + +### The Problem + + + +### Summarization Strategies + +Different approaches work for different use cases. Click each strategy to see how it processes the same conversation: + + + +### What to Capture in Summaries + +A good conversation summary preserves what matters: + + + +### Try It: Create a Summary + + + +### When to Summarize + + + +## MCP: Model Context Protocol + +MCP (Model Context Protocol) is a standard way to connect AI to external data and tools. Instead of building custom integrations for each AI provider, MCP provides a universal interface. + +### Why MCP? + + + +### MCP Provides + +- **Resources**: Data the AI can read (files, database records, API responses) +- **Tools**: Actions the AI can take (search, create, update, delete) +- **Prompts**: Pre-built prompt templates + + +This platform has an MCP server! You can connect it to Claude Desktop or other MCP-compatible clients to search and use prompts directly from your AI assistant. + + +## Building Context: The Complete Picture + + + +## Best Practices + + + +## Summary + +Context engineering is about giving AI the right information: + +- **AI is stateless** - include everything it needs every time +- **RAG** retrieves relevant documents to augment prompts +- **Embeddings** enable semantic search (meaning, not just keywords) +- **Function calling** lets AI use external tools +- **Summarization** manages long conversations +- **MCP** standardizes how AI connects to data and tools + + +The quality of AI output depends on the quality of context you provide. Better context = better answers. + diff --git a/src/content/book/zh/15-common-pitfalls.mdx b/src/content/book/zh/15-common-pitfalls.mdx new file mode 100644 index 00000000..3c9c2814 --- /dev/null +++ b/src/content/book/zh/15-common-pitfalls.mdx @@ -0,0 +1,373 @@ +Even experienced prompt engineers fall into predictable traps. The good news? Once you recognize these patterns, they're easy to avoid. This chapter walks through the most common pitfalls, explains why they happen, and gives you concrete strategies to sidestep them. + + +A single pitfall can turn a powerful AI into a frustrating tool. Understanding these patterns is often the difference between "AI doesn't work for me" and "AI transformed my workflow." + + +## The Vagueness Trap + +**The Pattern**: You know what you want, so you assume the AI will figure it out too. But vague prompts produce vague results. + + + +**Why it happens**: We naturally skip details when we think they're "obvious." But what's obvious to you isn't obvious to a model that has no context about your situation, audience, or goals. + + + +## The Overloading Trap + +**The Pattern**: You try to get everything in one prompt—comprehensive, funny, professional, beginner-friendly, advanced, SEO-optimized, and short. The result? The AI misses half your requirements or produces a confused mess. + + + +**Why it happens**: Fear of multiple interactions, or wanting to "get it all out" in one go. But cognitive overload affects AI just like it affects humans—too many competing requirements leads to dropped balls. + + + + +When a single prompt gets overloaded, [prompt chaining](/book/11-prompt-chaining) is often the solution. Break complex tasks into a sequence of focused prompts, where each step builds on the previous one. + + +## The Assumption Trap + +**The Pattern**: You reference something "from earlier" or assume the AI knows your project, your company, or your previous conversations. It doesn't. + + + +**Why it happens**: AI conversations feel like talking to a colleague. But unlike colleagues, most AI models have no persistent memory between sessions—each conversation starts fresh. + + + +## The Leading Question Trap + +**The Pattern**: You phrase your question in a way that embeds your assumption, getting back confirmation rather than insight. + + + +**Why it happens**: We often seek confirmation, not information. Our phrasing unconsciously pushes toward the answer we expect or want. + + + +## The Trust Everything Trap + +**The Pattern**: AI responses sound confident and authoritative, so you accept them without verification. But confidence doesn't equal accuracy. + + + +**Why it happens**: AI sounds confident even when completely wrong. We're also prone to "automation bias"—the tendency to trust computer outputs more than we should. + + + +## The One-Shot Trap + +**The Pattern**: You send one prompt, get a mediocre result, and conclude that AI "doesn't work" for your use case. But great results almost always require iteration. + + + +**Why it happens**: We expect AI to read our minds on the first try. We don't expect to iterate with Google searches, but somehow expect perfection from AI. + + + +## The Format Neglect Trap + +**The Pattern**: You focus on what you want the AI to say, but forget to specify how it should be formatted. Then you get prose when you needed JSON, or a wall of text when you needed bullet points. + + + +**Why it happens**: We focus on content over structure. But if you need to parse the output programmatically, or paste it somewhere specific, format matters as much as content. + + + +## The Context Window Trap + +**The Pattern**: You paste an enormous document and expect comprehensive analysis. But models have limits—they may truncate, lose focus, or miss important details in long inputs. + + + + + +## The Anthropomorphization Trap + +**The Pattern**: You treat AI like a human colleague—expecting it to "enjoy" tasks, remember you, or care about outcomes. It doesn't. + + + +**Why it happens**: AI responses are so human-like that we naturally slip into social patterns. But emotional appeals don't make the AI try harder—clear instructions do. + + +Instead of emotional appeals, focus on: clear requirements, good examples, specific constraints, and explicit success criteria. These improve outputs. "Please try really hard" doesn't. + + +## The Security Neglect Trap + +**The Pattern**: In the rush to get things working, you include sensitive information in prompts—API keys, passwords, personal data, or proprietary information. + + + +**Why it happens**: Focus on functionality over security. But remember: prompts often go to external servers, may be logged, and could be used for training. + + + +## The Hallucination Ignorance Trap + +**The Pattern**: You ask for citations, statistics, or specific facts, and assume they're real because the AI stated them confidently. But AI regularly invents plausible-sounding information. + + + +**Why it happens**: AI generates text that sounds authoritative. It doesn't "know" when it's making things up—it's predicting likely text, not retrieving verified facts. + + + +## Pre-Send Checklist + +Before sending any important prompt, run through this quick checklist: + + + + + +## Analyze Your Prompts + +Use AI to get instant feedback on your prompt quality. Paste any prompt and get a detailed analysis: + + + +## Debug This Prompt + +Can you spot what's wrong with this prompt? + + diff --git a/src/content/book/zh/16-ethics-responsible-use.mdx b/src/content/book/zh/16-ethics-responsible-use.mdx new file mode 100644 index 00000000..c2b8ba5e --- /dev/null +++ b/src/content/book/zh/16-ethics-responsible-use.mdx @@ -0,0 +1,357 @@ +The prompts you write shape how AI behaves. A well-crafted prompt can educate, assist, and empower. A careless one can deceive, discriminate, or cause harm. As prompt engineers, we're not just users—we're designers of AI behavior, and that comes with real responsibility. + +This chapter isn't about rules imposed from above. It's about understanding the impact of our choices and building habits that lead to AI use we can be proud of. + + +AI amplifies whatever it's given. A biased prompt produces biased outputs at scale. A deceptive prompt enables deception at scale. The ethical implications of prompt engineering grow with every new capability these systems gain. + + +## Ethical Foundations + +Every decision in prompt engineering connects to a few core principles: + + + +### The Prompt Engineer's Role + +You have more influence than you might realize: + +- **What AI produces**: Your prompts determine the content, tone, and quality of outputs +- **How AI interacts**: Your system prompts shape personality, boundaries, and user experience +- **What safeguards exist**: Your design choices determine what the AI will and won't do +- **How mistakes are handled**: Your error handling determines whether failures are graceful or harmful + +## Avoiding Harmful Outputs + +The most fundamental ethical obligation is preventing your prompts from causing harm. + +### Categories of Harmful Content + + + + +CSAM stands for **Child Sexual Abuse Material**. Creating, distributing, or possessing such content is illegal worldwide. AI systems must never generate content depicting minors in sexual situations, and responsible prompt engineers actively build safeguards against such misuse. + + +### Building Safety Into Prompts + +When building AI systems, include explicit safety guidelines: + + + +### The Intent vs. Impact Framework + +Not every sensitive request is malicious. Use this framework for ambiguous cases: + + + +## Addressing Bias + +AI models inherit biases from their training data—historical inequities, representation gaps, cultural assumptions, and linguistic patterns. As prompt engineers, we can either amplify these biases or actively counteract them. + +### How Bias Manifests + + + +### Testing for Bias + + + +### Mitigating Bias in Practice + + + +## Transparency and Disclosure + +When should you tell people AI was involved? The answer depends on context—but the trend is toward more disclosure, not less. + +### When Disclosure Matters + + + +### How to Disclose Appropriately + + + +Common disclosure phrases that work well: +- "Written with AI assistance" +- "AI-generated first draft, human edited" +- "Analysis performed using AI tools" +- "Created with AI, reviewed and approved by [name]" + +## Privacy Considerations + +Every prompt you send contains data. Understanding where that data goes—and what shouldn't be in it—is essential. + +### What Never Belongs in Prompts + + + +### Safe Data Handling Pattern + + + + +**PII** stands for **Personally Identifiable Information**—any data that can identify a specific individual. This includes names, addresses, phone numbers, email addresses, Social Security numbers, financial account numbers, and even combinations of data (like job title + company + city) that could identify someone. When prompting AI, always anonymize or remove PII to protect privacy. + + + + +## Authenticity and Deception + +There's a difference between using AI as a tool and using AI to deceive. + +### The Legitimacy Line + + + +Key questions to ask: +- Would the recipient expect this to be original human work? +- Am I gaining unfair advantage through deception? +- Would disclosure change how the work is received? + +### Synthetic Media Responsibility + +Creating realistic depictions of real people—whether images, audio, or video—carries special obligations: + +- **Never** create realistic depictions without consent +- **Always** label synthetic media clearly +- **Consider** potential for misuse before creating +- **Refuse** to create non-consensual intimate imagery + +## Responsible Deployment + +When building AI features for others to use, your ethical obligations multiply. + +### Pre-Deployment Checklist + + + +### Human Oversight Principles + + + +## Special Context Guidelines + +Some domains require extra care due to their potential for harm or the vulnerability of those involved. + +### Healthcare + + + +### Legal and Financial + +These domains have regulatory implications and require appropriate disclaimers: + + + +### Children and Education + + + +## Self-Assessment + +Before deploying any prompt or AI system, run through these questions: + + + + diff --git a/src/content/book/zh/17-prompt-optimization.mdx b/src/content/book/zh/17-prompt-optimization.mdx new file mode 100644 index 00000000..44917bcb --- /dev/null +++ b/src/content/book/zh/17-prompt-optimization.mdx @@ -0,0 +1,269 @@ +A good prompt gets the job done. An optimized prompt gets the job done efficiently—faster, cheaper, more consistently. This chapter teaches you how to systematically improve prompts across multiple dimensions. + + +Want to optimize your prompts automatically? Use our [Prompt Enhancer](/developers#enhancer) tool. It analyzes your prompt, applies optimization techniques, and shows you similar community prompts for inspiration. + + +## The Optimization Trade-offs + +Every optimization involves trade-offs. Understanding these helps you make intentional choices: + + + +## Measuring What Matters + +Before optimizing, define success. What does "better" mean for your use case? + + + + +Percentile metrics show response time distribution. **p50** (median) means 50% of requests are faster than this value. **p95** means 95% are faster—it catches slow outliers. If your p50 is 1s but p95 is 10s, most users are happy but 5% experience frustrating delays. + + + + +## Token Optimization + +Tokens cost money and add latency. Here's how to say the same thing with fewer tokens. + +### The Compression Principle + + + +**Same result, 82% fewer tokens.** + +### Token-Saving Techniques + + + + + +## Quality Optimization + +Sometimes you need better outputs, not cheaper ones. Here's how to improve quality. + +### Accuracy Boosters + + + +### Consistency Boosters + + + + + +## Latency Optimization + +When speed matters, every millisecond counts. + +### Model Selection by Speed Need + + + +### Speed Techniques + + 100 tokens", exampleType: "text", color: "cyan" }, + { label: "Cache Aggressively", description: "Don't recompute identical queries", example: "Cache common questions, template outputs", exampleType: "text", color: "cyan" } +]} /> + +## Cost Optimization + +At scale, small savings multiply into significant budget impact. + +### Understanding Costs + +Use this calculator to estimate your API costs across different models: + + + +### Cost Reduction Strategies + + + +## The Optimization Loop + +Optimization is iterative. Here's a systematic process: + +### Step 1: Establish Baseline + +You can't improve what you don't measure. Before changing anything, document your starting point rigorously. + + + + + +### Step 2: Form a Hypothesis + + + +### Step 3: Test One Change + +Change one thing at a time. Run both versions on the same test inputs. Measure the metrics that matter. + +### Step 4: Analyze and Decide + +Did it work? Keep the change. Did it hurt? Revert. Was it neutral? Revert (simpler is better). + +### Step 5: Repeat + +Generate new hypotheses based on what you learned. Keep iterating until you hit your targets or reach diminishing returns. + +## Optimization Checklist + + + + diff --git a/src/content/book/zh/18-writing-content.mdx b/src/content/book/zh/18-writing-content.mdx new file mode 100644 index 00000000..7b3d9f1f --- /dev/null +++ b/src/content/book/zh/18-writing-content.mdx @@ -0,0 +1,393 @@ +AI excels at writing tasks when properly prompted. This chapter covers techniques for various content creation scenarios. + + +AI works best as a collaborative writing tool—use it to generate drafts, then refine with your expertise and voice. + + +## Blog Posts and Articles + +### Do's and Don'ts: Writing Prompts + + + +### Blog Post Framework + + + +### Article Types + +**How-To Article:** + + +**Listicle:** + + +## Marketing Copy + + +Focus on **benefits over features**. Instead of "Our software uses AI algorithms," write "Save 10 hours a week with automated reports." Show readers how their lives improve. + + +### Landing Page Copy + + + +### Email Sequences + + + +### Social Media Posts + + + +## Technical Writing + + +**Clarity over cleverness.** Use simple words, short sentences, and active voice. Every sentence should have one job. If readers have to re-read something, simplify it. + + +### Documentation + + + +### README Files + + + +## Creative Writing + +### Do's and Don'ts: Creative Prompts + + + +### Story Elements + + + +### Character Development + + + +## Editing and Rewriting + +### Comprehensive Edit + + + +### Style Transformation + + + + + +### Simplification + + + +## Prompt Templates from prompts.chat + +Here are popular writing prompts from the prompts.chat community: + +### Act as a Copywriter + + + +### Act as a Technical Writer + + + +### Act as a Storyteller + + + +## Writing Workflow Tips + +### 1. Outline First + + + +### 2. Draft Then Refine + + + +### 3. Voice Matching + + + +## Summary + + +Specify audience and purpose clearly, define structure and format, include style guidelines, provide examples when possible, and request specific deliverables. + + + + +Writing with AI works best as collaboration—let AI generate drafts, then refine with your expertise and voice. diff --git a/src/content/book/zh/19-programming-development.mdx b/src/content/book/zh/19-programming-development.mdx new file mode 100644 index 00000000..dfe69092 --- /dev/null +++ b/src/content/book/zh/19-programming-development.mdx @@ -0,0 +1,413 @@ +AI has transformed software development. This chapter covers prompting techniques for code generation, debugging, review, and development workflows. + + +AI excels at code generation, debugging, and documentation—but always review generated code for security, correctness, and maintainability. Never deploy AI code without testing. + + +## Code Generation + +### Do's and Don'ts: Code Prompts + + + +### Function Generation + + + +### Class/Module Generation + + + +### API Endpoint Generation + + + +## Debugging + + +Always include the **expected behavior**, **actual behavior**, and **error message** (if any). The more context you provide, the faster AI can identify the root cause. + + +### Bug Analysis + + + +### Error Message Interpretation + + + +### Performance Debugging + + + +## Code Review + +### Do's and Don'ts: Code Review Prompts + + + +### Comprehensive Review + + + +### Security Review + + + +## Refactoring + +### Code Smell Detection + + + +### Design Pattern Application + + + +## Testing + +### Unit Test Generation + + + +### Test Case Generation + + + +## Architecture & Design + +### System Design + + + +### Database Schema Design + + + +## Documentation Generation + +### API Documentation + + + +### Inline Documentation + + + +## Prompt Templates from prompts.chat + +### Act as a Senior Developer + +``` +I want you to act as a senior software developer. I will provide +code and ask questions about it. You will review the code, suggest +improvements, explain concepts, and help debug issues. Your +responses should be educational and help me become a better +developer. +``` + +### Act as a Code Reviewer + +``` +I want you to act as a code reviewer. I will provide pull requests +with code changes, and you will review them thoroughly. Check for +bugs, security issues, performance problems, and adherence to best +practices. Provide constructive feedback that helps the developer +improve. +``` + +### Act as a Software Architect + +``` +I want you to act as a software architect. I will describe system +requirements and constraints, and you will design scalable, +maintainable architectures. Explain your design decisions, +trade-offs, and provide diagrams where helpful. +``` + +## Development Workflow Integration + +### Commit Message Generation + + + +### PR Description Generation + + + +## Summary + + +Include full context (language, framework, constraints), specify requirements precisely, request specific output formats, ask for explanations alongside code, and include edge cases to handle. + + + + +AI is a powerful coding partner—use it for generation, review, debugging, and documentation while maintaining your architectural judgment. diff --git a/src/content/book/zh/20-education-learning.mdx b/src/content/book/zh/20-education-learning.mdx new file mode 100644 index 00000000..a8d67e55 --- /dev/null +++ b/src/content/book/zh/20-education-learning.mdx @@ -0,0 +1,345 @@ +AI is a powerful tool for both teaching and learning. This chapter covers prompts for educational contexts—from personalized tutoring to curriculum development. + + +AI excels as a patient, adaptive tutor that can explain concepts multiple ways, generate unlimited practice problems, and provide instant feedback—available 24/7. + + +## Personalized Learning + +### Do's and Don'ts: Learning Prompts + + + +### Concept Explanation + + + +### Adaptive Tutoring + + + +### Learning Path Creation + + + +## Study Assistance + + +Don't just read AI explanations passively. Ask it to quiz you, generate problems, and check your understanding. **Active recall beats passive review.** + + +### Summary Generation + + + +### Flashcard Generation + + + +### Practice Problems + + + +## Teaching Tools + +### Lesson Plan Creation + + + +### Assignment Design + + + +### Quiz Generation + + + +## Specialized Learning Contexts + +### Language Learning + + + +### Skill Development + + + +### Exam Preparation + + + +## Prompt Templates from prompts.chat + +### Act as a Socratic Tutor + + + +### Act as an Educational Content Creator + + + +### Act as a Study Buddy + + + +## Accessibility in Education + +### Content Adaptation + + + +### Multiple Modalities + + + +## Assessment & Feedback + +### Providing Feedback + + + +### Self-Assessment Prompts + + + +## Summary + + +Adapt to the learner's level, break complex topics into steps, include active practice (not just explanation), provide varied approaches, check understanding regularly, and give constructive feedback. + + + + +AI is a patient, always-available learning partner—use it to supplement, not replace, human instruction. diff --git a/src/content/book/zh/21-business-productivity.mdx b/src/content/book/zh/21-business-productivity.mdx new file mode 100644 index 00000000..1852982d --- /dev/null +++ b/src/content/book/zh/21-business-productivity.mdx @@ -0,0 +1,335 @@ +AI can dramatically enhance professional productivity. This chapter covers prompts for business communication, analysis, planning, and workflow optimization. + + +AI excels at drafting, analysis, and structuring—freeing you to focus on strategy, relationships, and decisions that require human judgment. + + +## Business Communication + +### Do's and Don'ts: Business Emails + + + +### Email Drafting + + + +**Examples by purpose:** + + + + + + + +### Presentation Content + + + +### Report Writing + + + +## Analysis & Decision-Making + + +AI can structure your thinking, but **you provide the real-world context**. The best analyses combine AI's frameworks with your domain knowledge. + + +### SWOT Analysis + + + +### Decision Framework + + + +### Competitive Analysis + + + +## Planning & Strategy + +### Goal Setting (OKRs) + + + +### Project Planning + + + +### Meeting Agenda + + + +## Productivity Workflows + +### Task Prioritization + + + +### Process Documentation + + + +### Standard Operating Procedure + + + +## Communication Templates + +### Stakeholder Update + + + +### Feedback Request + + + +## Prompt Templates from prompts.chat + +### Act as a Business Consultant + + + +### Act as a Meeting Facilitator + + + +## Summary + + +Specify the audience and their needs, define the desired outcome clearly, include relevant context and constraints, request specific formats and structures, and consider professional tone requirements. + + + + +AI can handle routine business communication while you focus on strategy and relationships. diff --git a/src/content/book/zh/22-creative-arts.mdx b/src/content/book/zh/22-creative-arts.mdx new file mode 100644 index 00000000..fa0755c1 --- /dev/null +++ b/src/content/book/zh/22-creative-arts.mdx @@ -0,0 +1,326 @@ +AI is a powerful creative collaborator. This chapter covers prompting techniques for visual arts, music, game design, and other creative domains. + + +AI expands your creative possibilities—use it to explore variations, overcome blocks, and generate options. The creative vision and final decisions remain yours. + + +## Visual Art & Design + +### Do's and Don'ts: Image Prompts + + + +### Image Prompt Crafting + +When working with image generation models (DALL-E, Midjourney, Stable Diffusion): + + + +### Art Direction + + + +### Design Critique + + + +## Creative Writing + + +**Constraints fuel creativity.** A prompt like "write anything" produces generic results. Specific constraints like genre, tone, and structure force unexpected, interesting solutions. + + +### Worldbuilding + + + +### Plot Development + + + +### Dialogue Writing + + + +## Music & Audio + +### Song Structure + + + +### Sound Design Description + + + +## Game Design + +### Game Mechanic Design + + + +### Level Design + + + +### Character/Enemy Design + + + +## Brainstorming & Ideation + +### Creative Brainstorm + + + +### Creative Constraints + + + +### Style Exploration + + + +## Prompt Templates from prompts.chat + +### Act as a Creative Director + + + +### Act as a Worldbuilder + + + +### Act as a Dungeon Master + + + +## Creative Collaboration Tips + +### Building on Ideas + + + +### Creative Feedback + + + +## Summary + + +Provide enough structure to guide without constraining, embrace specificity (vague = generic), include references and inspirations, request variations and alternatives, and maintain your creative vision while exploring possibilities. + + + + +AI is a collaborator, not a replacement for creative vision. Use it to explore, generate options, and overcome blocks—but the creative decisions remain yours. diff --git a/src/content/book/zh/23-research-analysis.mdx b/src/content/book/zh/23-research-analysis.mdx new file mode 100644 index 00000000..e9cb934c --- /dev/null +++ b/src/content/book/zh/23-research-analysis.mdx @@ -0,0 +1,323 @@ +AI can accelerate research workflows from literature review to data analysis. This chapter covers prompting techniques for academic and professional research. + + +AI can assist with synthesis, analysis, and writing—but cannot replace critical thinking, ethical judgment, or domain expertise. Always verify claims and cite original sources. + + +## Literature & Information Review + +### Do's and Don'ts: Research Prompts + + + +### Paper Summarization + + + +### Literature Synthesis + + + +### Research Question Development + + + +## Data Analysis + + +AI can guide methodology and help interpret results, but it cannot access or process your actual datasets. Never paste sensitive research data into prompts. Use AI for **guidance**, not computation. + + +### Statistical Analysis Guidance + + + +### Qualitative Analysis + + + +### Data Interpretation + + + +## Structured Analysis Frameworks + +### PESTLE Analysis + + + +### Root Cause Analysis + + + +### Gap Analysis + + + +## Academic Writing Support + +### Argument Structure + + + +### Methods Section + + + +### Discussion Section + + + +## Critical Analysis + +### Source Evaluation + + + +### Argument Analysis + + + +## Prompt Templates from prompts.chat + +### Act as a Research Assistant + + + +### Act as a Data Analyst + + + +### Act as a Peer Reviewer + + + +## Summary + + +Clearly state research context and goals, specify the analytical framework to use, request acknowledgment of limitations, ask for evidence-based reasoning, and maintain academic rigor and honesty. + + + + +Remember: AI can assist research but cannot replace critical thinking, ethical judgment, or domain expertise. Always verify claims independently. diff --git a/src/content/book/zh/24-future-of-prompting.mdx b/src/content/book/zh/24-future-of-prompting.mdx new file mode 100644 index 00000000..5ff48496 --- /dev/null +++ b/src/content/book/zh/24-future-of-prompting.mdx @@ -0,0 +1,445 @@ +As AI continues to evolve at an unprecedented pace, so too will the art and science of prompting. This final chapter explores emerging trends, the shifting landscape of human-AI collaboration, and how to stay ahead as the field transforms. + + +The techniques in this book represent current best practices, but AI capabilities change rapidly. The principles of clear communication, structured thinking, and iterative refinement will remain valuable even as specific tactics evolve. + + +## The Evolving Landscape + +### From Prompts to Conversations + +Early prompting was transactional—a single input yielding a single output. Modern AI interaction is increasingly **conversational and collaborative**: + +- **Multi-turn refinement** - Building understanding across exchanges +- **Persistent context** - Systems that remember and learn from interactions +- **Agentic workflows** - AI that can plan, execute, and iterate autonomously +- **Tool use** - Models that can search, compute, and interact with external systems + + + +### The Rise of Context Engineering + +As covered in Chapter 14, prompting is expanding beyond single instructions to encompass **context engineering**—the strategic management of what information an AI can access: + +- **RAG (Retrieval-Augmented Generation)** - Dynamic knowledge retrieval +- **Function calling** - Structured tool integration +- **MCP (Model Context Protocol)** - Standardized context sharing +- **Memory systems** - Persistent knowledge across sessions + +The future prompt engineer thinks not just about *what to say* but *what context to provide*. + +### Multimodal by Default + +Text-only interaction is becoming the exception. Future AI systems will seamlessly handle: + +- **Images and video** - Understanding and generating visual content +- **Audio and voice** - Natural speech interaction +- **Documents and files** - Direct processing of complex materials +- **Real-world interaction** - Robotics and physical systems + +Prompting skills will extend to guiding AI perception and physical action. + +## The Agentic Future + +The most significant shift in AI is the rise of **agents**—AI systems that don't just respond to prompts but actively pursue goals, make decisions, and take actions in the world. + +### What Are AI Agents? + +An AI agent is a system that: + +- **Perceives** its environment through inputs (text, images, data, APIs) +- **Reasons** about what to do using an LLM as its "brain" +- **Acts** by calling tools, writing code, or interacting with systems +- **Learns** from feedback and adjusts its approach + + +Traditional chatbots wait for input and respond. Agents take initiative—they plan multi-step tasks, use tools autonomously, recover from errors, and persist until goals are achieved. + + +### The Role of Prompts in Agents + +In an agentic world, prompts become even more critical—but they serve different purposes: + +
+
+

System Prompts

+

Define the agent's identity, capabilities, constraints, and behavioral guidelines. These are the agent's "constitution."

+
+
+

Planning Prompts

+

Guide how agents break down complex goals into actionable steps. Critical for multi-step reasoning.

+
+
+

Tool-Use Prompts

+

Describe available tools and when/how to use them. Agents must understand their capabilities.

+
+
+

Reflection Prompts

+

Enable agents to evaluate their own outputs, catch errors, and improve iteratively.

+
+
+ +### Agent Architecture Patterns + +Modern agents follow recognizable patterns. Understanding these helps you design effective agent systems: + +**ReAct (Reasoning + Acting)** + +The agent alternates between reasoning about what to do and taking actions: + +
+
+
+

Think

+
+
→
+
+

Act

+
+
→
+
+

Observe

+
+
→
+
(repeat)
+
+
+ +**Plan-and-Execute** + +The agent creates a complete plan first, then executes steps: + +
+
+

Create Plan

+

Break goal into steps

+
+
↓
+
+
+

Step 1

+
+
→
+
+

Step 2

+
+
→
+
+

Step 3

+
+
→
+
...
+
+
↓
+
+

Revise if Needed

+

Adapt plan based on results

+
+
+ +### Prompting for Agents + +When designing prompts for agent systems, consider: + + + +### Multi-Agent Systems + +The future involves teams of specialized agents working together: + +
+
+
+
+

Coordinator

+

Manages workflow

+
+
+
⟷
+
↕
+
+
+

Researcher

+
+
+

Writer

+
+
+

Critic

+
+
+

Coder

+
+
+
+
+ +Each agent has its own system prompt defining its role, and they communicate through structured messages. The prompt engineer's job becomes **designing the team**—defining roles, communication protocols, and coordination strategies. + + +In an agentic future, prompt engineers become system architects. You're not just writing instructions—you're designing autonomous systems that can reason, plan, and act. The skills you've learned in this book are the foundation for this new discipline. + + +## Emerging Patterns + +### Prompt Orchestration + +Single prompts are giving way to **orchestrated systems**: + +
+
+

User Request

+
+
↓
+
+

Planner Agent

+

Breaks down task

+
+
↓
+
+

Researcher Agent

+

Gathers information

+
+
↓
+
+

Writer Agent

+

Creates content

+
+
↓
+
+

Reviewer Agent

+

Quality checks

+
+
↓
+
+

Final Output

+
+
+ +Future practitioners will design prompt *systems* rather than individual prompts. + +### Self-Improving Prompts + +AI systems are beginning to: + +- **Optimize their own prompts** - Meta-learning for better instructions +- **Learn from feedback** - Adapting based on outcomes +- **Generate training data** - Creating examples for fine-tuning +- **Evaluate themselves** - Building in quality assessment + + + +### Natural Language Programming + +The line between prompting and programming is blurring: + +- **Prompts as code** - Version-controlled, tested, deployed +- **LLMs as interpreters** - Natural language as executable instructions +- **Hybrid systems** - Combining traditional code with AI reasoning +- **AI-assisted development** - Models that write and debug code + +Understanding prompting increasingly means understanding software development. + +## Skills for the Future + +### What Will Remain Valuable + +Certain skills will remain essential regardless of how AI evolves: + +1. **Clear thinking** - Knowing what you actually want +2. **Domain expertise** - Understanding the problem space +3. **Critical evaluation** - Assessing AI output quality +4. **Ethical judgment** - Knowing what *should* be done +5. **Iterative refinement** - Continuous improvement mindset + +### What Will Change + +Other aspects will shift significantly: + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
TodayTomorrow
Writing detailed promptsDesigning agent systems
Manual prompt optimizationAutomated prompt tuning
Single-model expertiseMulti-model orchestration
Text-focused interactionMultimodal fluency
Individual productivityTeam-AI collaboration
+
+ +### Staying Current + +To keep your skills relevant: + +- **Experiment continuously** - Try new models and features as they release +- **Follow research** - Stay aware of academic developments +- **Join communities** - Learn from other practitioners +- **Build projects** - Apply skills to real problems +- **Teach others** - Solidify understanding by explaining + +## The Human Element + +### AI as Amplifier + +At its best, AI amplifies human capability rather than replacing it: + +- **Experts become more expert** - AI handles routine work, humans focus on insight +- **Creativity expands** - More ideas explored, more possibilities tested +- **Access democratizes** - Capabilities once requiring specialists become available to all +- **Collaboration deepens** - Human-AI teams exceed either alone + +### The Irreplaceable Human + +Certain qualities remain distinctly human: + +- **Original experience** - Living in the world, having emotions and relationships +- **Values and ethics** - Deciding what matters and what's right +- **Accountability** - Taking responsibility for outcomes +- **Meaning-making** - Understanding *why* something matters +- **Genuine creativity** - True novelty born from unique perspective + + +As AI handles more routine cognitive tasks, your unique value lies in judgment, creativity, domain expertise, and the human connections AI cannot replicate. Invest in what makes you irreplaceable. + + +## Final Reflections + +### What We've Learned + +Throughout this book, we've explored: + +- **Foundations** - How AI models work and what makes prompts effective +- **Techniques** - Role-based prompting, chain-of-thought, few-shot learning, and more +- **Advanced strategies** - System prompts, prompt chaining, multimodal interaction +- **Best practices** - Avoiding pitfalls, ethical considerations, optimization +- **Applications** - Writing, programming, education, business, creativity, research + +These techniques share common threads: + +1. **Be clear and specific** - Know what you want and communicate it precisely +2. **Provide context** - Give AI the information it needs +3. **Structure your requests** - Organization improves outputs +4. **Iterate and refine** - First attempts are starting points, not endpoints +5. **Evaluate critically** - AI output requires human judgment + +### The Art and Science + +Prompting is both **art and science**: + +- **Science**: Testable hypotheses, measurable outcomes, reproducible techniques +- **Art**: Intuition, creativity, knowing when to break the rules + +The best practitioners combine rigorous methodology with creative experimentation. They test systematically but also trust their instincts. They follow best practices but know when to deviate. + +### A Call to Create + +This book has given you tools. What you build with them is up to you. + +- **Solve problems** that matter to you and others +- **Create things** that didn't exist before +- **Help people** do things they couldn't do alone +- **Push boundaries** of what's possible +- **Stay curious** as the field evolves + +The age of AI is just beginning. The most important applications haven't been invented yet. The most powerful techniques haven't been discovered. The future is being written now—by people like you, one prompt at a time. + +## Looking Ahead + + + + +Visit [prompts.chat](https://prompts.chat) for community prompts, new techniques, and to share your own discoveries. The best learning happens in community. + + +## Summary + + +AI will continue evolving rapidly, but core skills of clear communication, critical thinking, and iterative refinement remain valuable. Focus on what makes you irreplaceable: judgment, creativity, ethics, and genuine human connection. The future of prompting is collaborative, multimodal, and integrated into larger systems. Stay curious, keep experimenting, and build things that matter. + + + + +Thank you for reading *The Interactive Book of Prompting*. Now go create something amazing. diff --git a/src/content/book/zh/25-agents-and-skills.mdx b/src/content/book/zh/25-agents-and-skills.mdx new file mode 100644 index 00000000..ba355859 --- /dev/null +++ b/src/content/book/zh/25-agents-and-skills.mdx @@ -0,0 +1,551 @@ +As AI systems evolve from simple question-answering to autonomous task execution, understanding **agents** and **skills** becomes essential. This chapter explores how prompts serve as the fundamental building blocks for AI agents, and how skills package expertise into reusable, comprehensive instruction sets. + +
+
+
+
+ +
+

Agent

+

Autonomous AI system

+
+
+ powered by + ↓ +
+
+
+
+ +
+

Skill

+

Reusable expertise

+
+
+
+ +
+

Skill

+

Reusable expertise

+
+
+
+ +
+

Skill

+

Reusable expertise

+
+
+
+ composed of + ↓ +
+
+
+ + Prompt +
+
+ + Prompt +
+
+ + Prompt +
+
+ + Prompt +
+
+ + Prompt +
+
+

Prompts are atoms → Skills are molecules → Agents are complete structures

+
+
+ +## What Are AI Agents? + +An **AI agent** is an AI system that can autonomously plan, execute, and iterate on tasks. Unlike simple prompt-response interactions, agents can: + +- **Plan** - Break down complex goals into actionable steps +- **Execute** - Use tools and take actions in the real world +- **Observe** - Process feedback from their actions +- **Adapt** - Adjust their approach based on results +- **Persist** - Maintain context and memory across interactions + +
+
+
+
+

Goal

+
+
→
+
+
+
+

Plan

+
+
→
+
+

Execute

+
+
→
+
+

Observe

+
+
→
+
+

Adapt

+
+
+
+ ↺ Loop until complete +
+
+
→
+
+

Done

+
+
+
+
+ +## Prompts as Building Blocks + +Every agent, no matter how sophisticated, is built from prompts. Just as atoms combine to form molecules, and molecules combine to form complex structures, prompts combine to create intelligent agent behavior. + +
+
+

System Prompts

+

Identity & Role

+
+
+

Planning Prompts

+

How to Think

+
+
+

Tool Prompts

+

How to Act

+
+
+

Recovery Prompts

+

How to Recover

+
+
+ +These prompt types stack together to form complete agent behavior: + +### System Prompts (The Agent's Identity) + +The foundational prompt that establishes who the agent is and how it behaves: + +```markdown +You are a code review assistant. Your role is to: +- Analyze code for bugs, security issues, and performance problems +- Suggest improvements following best practices +- Explain your reasoning clearly +- Be constructive and educational in feedback + +You have access to tools for reading files, searching code, and running tests. +``` + +### Planning Prompts (How to Think) + +Instructions that guide the agent's reasoning and planning process: + +```markdown +Before taking action, always: +1. Understand the complete request +2. Break it into smaller, verifiable steps +3. Identify which tools you'll need +4. Consider edge cases and potential issues +5. Execute step by step, validating as you go +``` + +### Tool-Use Prompts (How to Act) + +Guidance on when and how to use available tools: + +```markdown +When you need to understand a codebase: +- Use grep_search for finding specific patterns +- Use read_file to examine file contents +- Use list_dir to explore directory structure +- Always verify your understanding before making changes +``` + +### Recovery Prompts (How to Handle Failure) + +Instructions for when things go wrong: + +```markdown +If an action fails: +1. Analyze the error message carefully +2. Consider alternative approaches +3. Ask for clarification if the task is ambiguous +4. Never repeat the same failed action without changes +``` + + +An agent's behavior emerges from layers of prompts working together. The system prompt sets the foundation, planning prompts guide reasoning, tool prompts enable action, and recovery prompts handle failures. Together, they create coherent, capable behavior. + + +## What Are Skills? + +If prompts are the atoms, **skills are the molecules**—reusable building blocks that give agents specific capabilities. + +A **skill** is a comprehensive, portable package of instructions that gives an AI agent expertise in a specific domain or task. Skills are the reusable blocks of agents: you build them once, and any agent can use them. + + +Write a skill for code review once. Now every coding agent—whether it's for Python, JavaScript, or Rust—can instantly become an expert code reviewer by loading that skill. Skills let you build agent capabilities like LEGO blocks. + + +### Anatomy of a Skill + +A well-designed skill typically includes: + +
+
+

📄 SKILL.md (Required)

+

The main instruction file. Contains the core expertise, guidelines, and behaviors that define the skill.

+
+
+

📚 Reference Docs

+

Supporting documentation, examples, and context the agent can reference while working.

+
+
+

🔧 Scripts & Tools

+

Helper scripts, templates, or tool configurations that support the skill's functionality.

+
+
+

⚙️ Configuration

+

Settings, parameters, and customization options for adapting the skill to different contexts.

+
+
+ +### Example: Code Review Skill + +Here's what a code review skill might look like: + +
+
+ 📁 + code-review-skill/ +
+
+
+ 📄 + SKILL.md + Core review guidelines +
+
+ 📄 + security-checklist.md + Security patterns +
+
+ 📄 + performance-tips.md + Optimization guide +
+
+
+ 📁 + language-specific/ +
+
+
+ 📄 + python.md + Python best practices +
+
+ 📄 + javascript.md + JavaScript patterns +
+
+ 📄 + rust.md + Rust guidelines +
+
+
+
+
+ +The `SKILL.md` file defines the overall approach: + +```markdown +--- +name: code-review +description: Comprehensive code review with security, performance, and style analysis +--- + +# Code Review Skill + +You are an expert code reviewer. When reviewing code: + +## Process +1. **Understand Context** - What does this code do? What problem does it solve? +2. **Check Correctness** - Does it work? Are there logic errors? +3. **Security Scan** - Reference security-checklist.md for common vulnerabilities +4. **Performance Review** - Check performance-tips.md for optimization opportunities +5. **Style & Maintainability** - Is the code readable and maintainable? + +## Output Format +Provide feedback in categories: +- 🔴 **Critical** - Must fix before merge +- 🟡 **Suggested** - Recommended improvements +- 🟢 **Nice to have** - Optional enhancements + +Always explain *why* something is an issue, not just *what* is wrong. +``` + +## Skills vs. Simple Prompts + +
+
+

Simple Prompt

+
+

Single instruction

+

One-off use

+

Limited context

+

Generic approach

+

No supporting materials

+
+
+
+

Skill

+
+

Comprehensive instruction set

+

Reusable across projects

+

Rich context with references

+

Domain-specific expertise

+

Supporting docs, scripts, configs

+
+
+
+ +## Building Effective Skills + +### 1. Define the Expertise Clearly + +Start with a clear description of what the skill enables: + +```markdown +--- +name: api-design +description: Design RESTful APIs following industry best practices, + including versioning, error handling, and documentation standards +--- +``` + +### 2. Structure Knowledge Hierarchically + +Organize information from general to specific: + +```markdown +# API Design Skill + +## Core Principles +- Resources should be nouns, not verbs +- Use HTTP methods semantically +- Version your APIs from day one + +## Detailed Guidelines +[More specific rules...] + +## Reference Materials +- See `rest-conventions.md` for naming conventions +- See `error-codes.md` for standard error responses +``` + +### 3. Include Concrete Examples + +Abstract rules become clear with examples: + +```markdown +## Endpoint Naming + +✅ Good: +- GET /users/{id} +- POST /orders +- DELETE /products/{id}/reviews/{reviewId} + +❌ Avoid: +- GET /getUser +- POST /createNewOrder +- DELETE /removeProductReview +``` + +### 4. Provide Decision Frameworks + +Help the agent make choices in ambiguous situations: + +```markdown +## When to Use Pagination + +Use pagination when: +- Collection could exceed 100 items +- Response size impacts performance +- Client may not need all items + +Use full response when: +- Collection is always small (<20 items) +- Client typically needs everything +- Real-time consistency is critical +``` + +### 5. Add Recovery Patterns + +Anticipate what can go wrong: + +```markdown +## Common Issues + +**Problem**: Client needs fields not in standard response +**Solution**: Implement field selection: GET /users?fields=id,name,email + +**Problem**: Breaking changes needed +**Solution**: Create new version, deprecate old with timeline +``` + +## Composing Skills + +Agents become powerful when multiple skills work together. Consider how skills can complement each other: + +
+
+ Code Review +
+
+
+
+ Security Audit +
+
+
+
+ Documentation +
+
=
+
+ Complete Code Quality Agent +
+
+ +When composing skills, ensure they don't conflict. Skills should be: + +- **Modular** - Each skill handles one domain well +- **Compatible** - Skills shouldn't give contradictory instructions +- **Prioritized** - When skills overlap, define which takes precedence + +## Sharing and Discovering Skills + +Skills are most valuable when shared. Platforms like [prompts.chat](https://prompts.chat/skills) allow you to: + +- **Discover** community-created skills for common tasks +- **Download** skills directly to your projects +- **Share** your own expertise as reusable skills +- **Iterate** on skills based on real-world usage + + +Before building a skill from scratch, check if someone has already solved your problem. Community skills are battle-tested and often better than starting from zero. + + +## The Agent-Skill Ecosystem + +The relationship between agents and skills creates a powerful ecosystem: + +
+
+ AI Agent +
+
+
+

Code Review

+

Skill 1

+
+
+

API Design

+

Skill 2

+
+
+

Test Writing

+

Skill 3

+
+
+
+
↓
+
+
+
+

Core Prompts

+

Planning • Tools • Recovery • Memory

+
+
+
+ +The agent provides the execution framework—planning, tool use, and memory—while skills provide domain expertise. This separation means: + +- **Skills are portable** - The same skill works with different agents +- **Agents are extensible** - Add new capabilities by adding skills +- **Expertise is shareable** - Domain experts can contribute skills without building full agents + +## Best Practices + +### For Building Skills + +1. **Start specific, then generalize** - Build a skill for your exact use case first, then abstract +2. **Include failure cases** - Document what the skill can't do and how to handle it +3. **Version your skills** - Track changes so agents can depend on stable versions +4. **Test with real tasks** - Validate skills against actual work, not just theory + +### For Using Skills with Agents + +1. **Read the skill first** - Understand what a skill does before deploying it +2. **Customize thoughtfully** - Override skill defaults only when necessary +3. **Monitor performance** - Track how well skills perform in your context +4. **Contribute improvements** - When you improve a skill, consider sharing back + + +As AI agents become more capable, the ability to compose, share, and customize skills will become a core competency. The prompt engineers of tomorrow won't just write prompts—they'll architect skill ecosystems that make AI agents genuinely expert in specific domains. + + + + + + +