Chapter 9
Human–AI Collaboration
“The best partnerships are those where each party does what they do best—and knows when to step aside.” — Source unknown
In Chapter 1, we introduced four interaction modes for human-AI collaboration: Delegation, Collaboration, Supervision, and Augmentation. We’ve explored AI’s capabilities and limitations in Chapter 4. Now we turn to the practical question: how do you actually work with AI systems day-to-day? Later chapters will examine calibrated trust (Chapter 10) and the future landscape (Chapter 16) in greater depth.
This chapter provides a pragmatic guide to human-AI collaboration—not as abstract theory but as lived practice. We’ll explore the psychological dimensions of working with non-human teammates, develop frameworks for choosing appropriate interaction modes for different tasks, and establish practical techniques for correcting, guiding, and teaching AI systems to produce better results.
The central insight: effective human-AI collaboration is not about treating AI as either a tool or a colleague, but about developing new interaction patterns that leverage AI’s strengths while compensating for its weaknesses. Engineers who master these patterns multiply their effectiveness. Those who default to passive acceptance or blanket rejection miss the opportunity.
::: {=latex} \begin{center} \includegraphics[width=0.95\linewidth]{diagrams/Human_AI_Collaboration.png} \end{center} ::: ::: {=html}

The Psychology of Non-Human Teammates
Why Working with AI Feels Different
Most engineers have extensive experience collaborating with humans. We’ve learned to read social cues, navigate personality differences, build trust, give feedback, and coordinate work. These patterns are deeply ingrained—they’re how teamwork feels.
Working with AI violates many of these patterns, creating cognitive dissonance. The system produces remarkably capable output one moment and embarrassingly wrong output the next. It responds instantly to requests but cannot remember yesterday’s conversation. It matches your coding style perfectly but has no understanding of why that style matters.
This unpredictability creates psychological stress. Research on human-automation interaction identifies several maladaptive responses [@Parasuraman1997]:
Over-trust from capability demonstration. When AI produces impressive results, humans extrapolate to situations where reliability is lower. An engineer sees AI generate clean code for ten straightforward tasks and assumes it will handle complex edge cases equally well. This is automation bias—the tendency to favor suggestions from automated systems even when contradictory evidence exists.
Under-trust from visible failures. Conversely, a single dramatic failure can trigger lasting skepticism. An engineer sees AI generate subtly broken code once and thereafter rejects all AI suggestions, even when they’re correct. This is automation aversion—the tendency to discount automated assistance after observing errors [@Dietvorst2015].
Frustration from inconsistency. Perhaps most challenging is the whiplash between these states. The same AI system that brilliantly debugged yesterday’s issue generates nonsense today. This inconsistency prevents stable mental models from forming, leaving engineers in constant uncertainty about when to trust.
The solution is not to eliminate these reactions—they’re natural responses to working with systems that don’t behave like human teammates. Instead, engineers need new mental models calibrated to AI’s actual characteristics.
The Cognitive Prosthetic Model
A useful mental model: treat AI as a cognitive prosthetic rather than a colleague or tool.
Not a colleague because. Colleagues have continuity—they remember past conversations, understand organizational context, and bring stable personalities. AI has discontinuous memory, lacks organizational embedding, and exhibits no consistent “personality” beyond training patterns.
Not a tool because. Tools are predictable—a hammer works the same way every time. AI is stochastic—the same prompt can yield different outputs. Tools don’t make suggestions; AI does. Tools don’t require interpretation; AI output often does.
A prosthetic because. Prosthetics extend capability in specific dimensions while requiring user skill to operate effectively. A prosthetic limb doesn’t replace natural motor control—it translates intention through learned use. Similarly, AI extends cognitive capability but requires human direction, evaluation, and judgment.
This model has several advantages:
It acknowledges sophisticated capability. Prosthetics are impressive feats of engineering that genuinely enhance function. This prevents under-utilization from treating AI as a trivial tool.
It emphasizes learning curve. No one expects to use a prosthetic effectively immediately. There’s an adaptation period where user and device learn to work together. This prevents frustration when AI collaboration doesn’t feel natural instantly.
It maintains human agency. The prosthetic responds to user intention; it doesn’t have goals of its own. This prevents over-trust from anthropomorphizing AI as having understanding or judgment it lacks.
It suggests customization. Prosthetics work best when fitted to individual users. Similarly, effective AI use requires learning which prompts work, which tasks are appropriate, and how to interpret outputs—a personalized calibration process.
Building Accurate Mental Models
The prosthetic model is one framework. But effective collaboration requires more detailed mental models of what AI actually does.
Mental Model 1: AI as Pattern Matcher
At its core, an LLM is a sophisticated pattern-matching engine. It predicts tokens based on statistical regularities in training data. This model helps explain:
- Why AI is fluent: It has seen millions of examples of fluent text and code
- Why AI hallucinates: Matching patterns doesn’t guarantee truth
- Why AI struggles with novelty: Patterns outside training distribution are harder to match
- Why prompting matters: You’re directing which patterns the model should match
This model prevents mystification—AI isn’t “thinking” in the human sense. It’s finding and applying learned patterns.
Mental Model 2: AI as Probabilistic System
AI outputs are probabilistic, not deterministic. The same prompt can yield different responses due to sampling randomness. This model helps explain:
- Why consistency is imperfect: Stochasticity means variation
- Why regenerating can help: Different samples might yield better results
- Why temperature matters: Higher temperature increases randomness
- Why errors aren’t always reproducible: What failed once might succeed on retry
This model prevents treating AI like deterministic code—expecting identical results from identical inputs.
Mental Model 3: AI as Context-Bounded
AI operates within a context window—typically thousands to millions of tokens. This model helps explain:
- Why conversation history matters: Recent context shapes outputs
- Why AI “forgets”: Information outside the window is inaccessible
- Why summarization helps: Compressing context preserves more information within the window
- Why session management matters: Starting fresh resets context entirely
This model prevents assuming AI has memory like humans—it knows only what’s in the current window.
Mental Model 4: AI as Trained, Not Programmed
Unlike traditional software, AI behavior emerges from training data and objectives, not explicit code. This model helps explain:
- Why biases appear: Training data contains societal biases
- Why certain tasks work well: They’re well-represented in training
- Why fine-tuning helps: Additional training shapes behavior
- Why prompt engineering is necessary: You’re navigating learned associations
This model prevents expecting bug-free behavior—AI doesn’t have bugs in the traditional sense, it has training limitations.
Emotional Regulation in Human-AI Work
Working with AI can be emotionally challenging. The system produces outputs that range from brilliant to baffling, sometimes within the same session. Engineers report frustration, confusion, and occasionally anger when AI fails in ways that seem “stupid” [@Vaccaro2018].
These emotional responses are valid but counterproductive if they prevent effective use. Some strategies for emotional regulation:
Expect imperfection. AI will fail. Build this expectation into your workflow rather than being surprised when it happens. Treat failures as information about system limitations, not as personal affronts.
Separate capability from reliability. AI can do impressive things unreliably. Something that works 80% of the time is genuinely useful—if you verify the other 20%. Don’t reject capabilities because they’re imperfect.
Take breaks from frustration. When AI produces nonsensical outputs repeatedly, step away. Trying to “fix” AI through increasingly frustrated prompts rarely works. Return with fresh perspective and different framing.
Maintain appropriate skepticism. As we’ll explore in Chapter 10, calibrated trust means neither blind acceptance nor blanket rejection. Skepticism protects against over-trust without preventing utilization.
Remember the alternative. Even imperfect AI assistance is often faster than working alone. Compare AI-augmented work to manual work, not to an imagined perfect assistant.
The goal is emotional stability that allows effective collaboration—neither euphoric over-trust nor bitter rejection, but pragmatic engagement with a powerful but flawed tool.
Interaction Models: Delegation, Collaboration, Supervision, and Augmentation
In Chapter 1, we introduced four interaction modes: Delegation, Collaboration, Supervision, and Augmentation. Let’s now explore these modes in practical detail, with guidance on when to use each and how to execute them effectively.
Delegation: When to Let Go
What it is. In Delegation mode, you specify a task and the AI executes it with minimal intervention. You provide clear requirements, let the AI work, then verify the output.
When to use Delegation.
Tasks with clear specifications and success criteria
Well-understood problems with standard solutions
Low-stakes work where errors are cheap to fix
Boilerplate code, documentation, or test generation
Repetitive transformations across similar structures
Example scenarios.
“Write unit tests for this function” (the function defines correct behavior)
“Generate API documentation from these endpoint definitions”
“Convert these SQL queries to use parameterized statements”
“Create getter and setter methods for these class properties”
How to delegate effectively.
1. Provide complete context upfront. Don’t assume AI will ask for missing information. Include:
Input/output specifications
Constraints and requirements
Relevant code or data structures
Coding standards or style preferences
Any edge cases you’re aware of
2. Be explicit about success criteria. State clearly what “correct” means:
“Tests should achieve 100% branch coverage”
“Documentation should follow our API doc template”
“Code should match our style guide (attached)”
3. Verify systematically. Don’t trust blindly. Check:
Does it compile/run?
Do tests pass?
Does it handle edge cases?
Does it match specifications?
Is it maintainable?
4. Iterate if needed. If output is wrong, don’t abandon delegation. Provide specific feedback and re-delegate:
“The tests don’t cover error cases. Add tests for invalid inputs.”
“The documentation is missing return type descriptions. Add them.”
When Delegation fails. If you’re iterating more than 3 times on the same delegated task, switch modes. The task may be too complex, too novel, or too poorly specified for pure delegation.
Collaboration: Working Together
What it is. In Collaboration mode, you and AI work iteratively. You provide direction, AI generates proposals, you refine direction, AI adjusts—back and forth until the result is satisfactory.
When to use Collaboration.
Complex tasks where requirements evolve during execution
Problems where you’re exploring solution spaces
Creative work where you’re refining through iteration
Tasks where your judgment improves AI output substantially
Learning situations where you want to understand AI’s reasoning
Example scenarios.
“Help me design a caching strategy for this API” (exploration)
“Let’s refactor this module to be more testable” (iterative improvement)
“Draft a technical proposal for distributed tracing” (creative work)
“Debug why this async function deadlocks” (problem-solving)
How to collaborate effectively.
1. Start with broad direction, narrow iteratively.
You: "I need a caching strategy for a high-read, low-write API."
AI: [proposes Redis with TTL-based expiration]
You: "Good start. How would we handle cache invalidation when writes occur?"
AI: [proposes cache-aside pattern with write-through]
You: "What about cache stampedes during cold starts?"
AI: [proposes probabilistic early expiration]
2. Ask AI to explain its reasoning. Understanding why AI suggests something helps you evaluate whether it’s appropriate:
“Why did you choose Redis over Memcached?”
“What’s the trade-off with this approach?”
“What are potential failure modes?”
3. Provide progressive context. As the conversation evolves, add context:
“Actually, we’re already using Redis for session storage”
“I should mention—writes are extremely rare, maybe 1% of traffic”
“Interesting. Our largest customers have 100x more data than typical ones”
4. Use AI to generate alternatives. Don’t settle for the first suggestion:
“Show me three different caching approaches and their trade-offs”
“What if we used a different consistency model?”
5. Maintain decision authority. You’re collaborating, but you’re making final calls. AI generates options; you choose:
“I like option 2 best for our use case. Let’s proceed with that.”
When Collaboration is working. You’re learning from AI’s suggestions, AI is adapting to your feedback, and the solution is converging toward something you couldn’t have reached alone as quickly.
When Collaboration fails. If you’re spending more time explaining context than making progress, or if AI keeps misunderstanding your intent, consider whether the task is too novel or whether you need to delegate sub-tasks instead.
Supervision: Monitoring Autonomous Work
What it is. In Supervision mode, AI operates semi-autonomously while you monitor for problems and intervene when necessary. This is appropriate for ongoing processes or tasks that span extended time.
When to use Supervision.
Long-running processes (multi-file refactoring, batch processing)
Agentic AI systems that work across multiple sub-tasks
Continuous monitoring or analysis tasks
Work that’s mostly routine but occasionally needs human judgment
Example scenarios.
AI agent implementing a feature across multiple files
Automated code review suggesting improvements
Continuous refactoring to improve code quality
Monitoring logs for anomalies and suggesting fixes
How to supervise effectively.
1. Set clear boundaries before autonomous work.
“Refactor the authentication module, but don’t touch the encryption logic”
“Suggest improvements, but don’t auto-merge anything”
“Flag anomalies, but only alert for high-severity issues”
2. Establish checkpoints. Don’t let AI work for hours uninterrupted:
“Show me your plan before starting”
“Check in after completing each file”
“Summarize what you’ve done every 30 minutes”
3. Monitor for drift. As AI works, watch for patterns:
Is it still addressing the original goal?
Are changes consistent in style and approach?
Is it introducing new problems while fixing old ones?
4. Intervene decisively. When something looks wrong, stop and redirect:
“Pause. This change breaks the API contract. Revert and try a different approach.”
“You’re optimizing prematurely. Focus on correctness first.”
5. Maintain situational awareness. This is the hardest part of supervision—staying engaged enough to intervene when needed without micromanaging. As we discussed in Chapter 1, this is the “out-of-the-loop” problem that Bainbridge identified [@Bainbridge1983].
Strategies for maintaining awareness.
Review AI’s plan before execution
Skim each change as it’s made (don’t deep-read, just verify direction)
Run tests frequently to catch issues early
Keep a mental model of what should be changing
When Supervision works. AI is making steady progress on routine aspects while you catch the non-routine issues that require human judgment.
When Supervision fails. If you find yourself constantly intervening, the task isn’t suitable for autonomous work. Drop to Collaboration mode where you’re more actively involved.
Augmentation: AI as Extension of Self
What it is. In Augmentation mode, AI enhances your capabilities without taking over the task. You remain the primary agent; AI provides real-time assistance that makes you more effective.
When to use Augmentation.
Tasks where you need to maintain full context and control
Situations requiring continuous judgment calls
Work where AI provides tools/information but you make all decisions
Learning and skill development scenarios
Example scenarios.
Code completion while you’re writing
Inline suggestions for improvements as you type
Real-time syntax checking and error detection
Documentation lookup while coding
Example generation to understand APIs
How to augment effectively.
1. Treat suggestions as options, not prescriptions.
AI completes your function → you can accept, modify, or ignore
AI suggests an improvement → you evaluate whether it’s actually better
AI offers an alternative approach → you decide if it’s worth switching
2. Maintain your train of thought. Don’t let AI derail your thinking:
If a suggestion doesn’t match your intent, ignore it immediately
Don’t stop to evaluate every suggestion—only when they seem relevant
Complete your thought before considering AI’s alternative
3. Use AI to explore quickly. Let AI handle the mechanical parts while you focus on the conceptual:
“What’s the syntax for…” → AI shows you instantly
“How do I…” → AI provides examples
“What would this look like if…” → AI generates for comparison
4. Learn from patterns. Pay attention to what AI suggests. Good suggestions teach you patterns:
AI consistently suggests error handling you forget → learn the pattern
AI offers idioms you don’t know → incorporate them into your repertoire
AI catches common mistakes → train yourself to avoid them
5. Adjust assistance levels. Most augmentation tools let you control intrusiveness:
Turn off suggestions when they’re distracting
Increase assistance when exploring unfamiliar territory
Adjust delay before suggestions appear
When Augmentation works. You feel more productive without feeling like you’re losing control. AI accelerates your work without changing your approach.
When Augmentation fails. If suggestions are consistently irrelevant, annoying, or wrong, reduce assistance levels or disable them for that task.
Choosing the Right Mode
Deciding which mode to use requires judgment based on several factors:
| Factor | Deleg. | Collab. | Superv. | Augment. |
|---|---|---|---|---|
| Task clarity | High | Med | Med | N/A |
| Your expertise | Any | High | High | Any |
| Stakes | Low-Med | Med-High | Med | Any |
| Time available | Limited | Flexible | Extended | Real-time |
| Novelty | Low | Med-High | Low-Med | Any |
| Involvement | Minimal | Continuous | Periodic | Constant |
Decision heuristics.
When the goal is clear and stakes are low → Delegate
When exploring options or requirements are evolving → Collaborate
When the task is extended but mostly routine → Supervise
When you need full control with AI assistance → Augment
Mode switching is normal. Start with one mode, switch to another if it’s not working:
Delegation → Collaboration (task is more complex than expected)
Collaboration → Delegation (you’ve clarified requirements through exploration)
Supervision → Collaboration (too many interventions needed)
Any mode → Augmentation (you want more hands-on control)
The skill is recognizing when a mode isn’t working and switching promptly rather than persisting with ineffective patterns.
There is a more fundamental choice that sits beneath these four modes: the choice between workflows and agents.
A workflow is a deterministic path—code and data flowing through predefined steps, with conditional logic that a human designed in advance. A CI/CD pipeline is a workflow. An ETL process is a workflow. The sequence is fixed; the behavior is predictable; the failure modes are known.
An agent, by contrast, is non-deterministic. It receives a goal and decides—step by step, based on observation and inference—what to do next. Its path is emergent, not designed. This makes agents powerful for open-ended tasks but unreliable for tasks where predictability matters.
The decision heuristic is straightforward: if you can specify the steps in advance and the path is stable, use a workflow. It will be faster, cheaper, and more reliable. If the steps depend on intermediate results that you cannot predict, or if the task requires adaptation, use an agent. The mistake many teams make is reaching for agents when a well-designed workflow would suffice—seduced by the sophistication of the tool rather than the requirements of the task. The best engineers match the tool to the problem, not the other way around.
How to Correct, Guide, and Teach AI Systems
Working effectively with AI requires more than choosing interaction modes—it requires skill in correcting errors, providing guidance, and iteratively improving outputs. This section provides practical techniques for these meta-skills.
The Correction Loop: Diagnosing and Fixing AI Errors
When AI produces wrong output, the temptation is to regenerate or give up. More effective is diagnosing why it failed and providing specific correction.
Step 1: Categorize the failure
Different failure types require different corrections:
Category 1 - Misunderstood Requirements. AI solved the wrong problem
Example: Asked for error handling, got logging instead
Correction approach: Clarify requirements more explicitly
Fix: “I need error handling, not error logging. Handle errors by…”
Category 2 - Incomplete Context. AI lacked necessary information
Example: Generated code incompatible with existing architecture
Correction approach: Provide missing context
Fix: “This needs to work with our existing auth system (here’s the interface)…”
Category 3 - Edge Cases. AI handled common cases but missed corner cases
Example: Code works for valid inputs but crashes on invalid ones
Correction approach: Specify edge cases explicitly
Fix: “This doesn’t handle null inputs. Add validation for…”
Category 4 - Wrong Patterns. AI applied patterns from training that don’t fit
Example: Used inheritance when composition would be better
Correction approach: Explain why the pattern doesn’t work here
Fix: “Inheritance creates tight coupling here. Use composition instead because…”
Category 5 - Hallucination. AI invented facts or APIs that don’t exist
Example: Called methods that don’t exist in the library
Correction approach: Provide accurate information
Fix: “The library doesn’t have a
doThing()method. UseperformAction()instead…”
Step 2: Provide specific, actionable feedback
Vague corrections don’t help:
- Bad: “This is wrong”
- Bad: “Try again”
- Bad: “That doesn’t work”
Specific corrections do:
- Good: “The function returns string but should return integer”
- Good: “The variable
userDatais undefined—you need to pass it as parameter” - Good: “This approach is O(n²) but we need O(n log n) for our scale”
Step 3: Show, don’t just tell
When possible, provide examples of correct behavior:
Instead of: “Handle errors properly”
Provide: “Handle errors like this: try { ... } catch (error) { logger.error(error); throw new CustomError(...); }”
Instead of: “Use better variable names”
Provide: “Use descriptive names like authenticatedUser instead of u”
Step 4: Iterate progressively
Don’t expect perfection immediately. Correct iteratively:
Round 1: "Add error handling"
→ AI adds try-catch but doesn't log errors
Round 2: "Log errors before re-throwing"
→ AI logs but uses wrong log level
Round 3: "Use logger.error() for exceptions, not logger.info()"
→ AI corrects it
Round 4: "Include stack trace in error log"
→ Final correct version
This feels inefficient but is often faster than trying to specify everything perfectly upfront.
- When to abandon correction. If you’re on the 5th iteration and still not getting correct output, the task may be:
- Too complex for AI’s current capabilities
- Too novel (outside training distribution)
- Too poorly specified (you’re not sure what you want either)
At this point, either simplify the task, switch modes, or write it yourself.
From Prompting to Context Engineering
How you communicate with AI significantly affects output quality. Most discussions frame this as “prompt engineering” — the craft of writing better prompts. That framing is useful but incomplete. It optimises at the wrong level of abstraction.
The more precise discipline is context engineering — shaping the entire informational environment that an AI system operates within. A prompt is a single input. Context is everything: the system instructions, the examples provided, the documents retrieved, the conversation history, the tool descriptions, and the constraints that bound acceptable behaviour.
The distinction matters because engineers who think only in terms of prompts treat each interaction as an isolated question-and-answer exchange. Engineers who think in terms of context treat each interaction as part of a designed informational architecture. They ask not just “what should I say to the model?” but “what does the model need to know — and what does it need to not know — in order to produce useful output?”
Context engineering is to AI collaboration what systems design is to software architecture. It requires deciding what to include, what to exclude, how to structure information for maximum signal, and how to anticipate failure modes before they occur. A well-engineered context makes every subsequent prompt more effective — because the model is already operating within the right constraints, with the right examples, and with the right framing of the problem space.
The techniques below are the building blocks of effective context engineering. Each one shapes a different dimension of the model’s informational environment:
Technique 1: Provide Role and Context
Instead of: “Write a function to validate emails”
Try: “You’re an experienced backend engineer. Write a production-grade email validation function that handles international domains and provides clear error messages.”
The role primes AI to match that persona’s patterns. The context clarifies quality expectations.
Technique 2: Show Examples (Few-Shot Learning)
Instead of: “Use our coding style”
Try:
Here are three examples of our coding style:
[Example 1]
[Example 2]
[Example 3]
Now write a function following this style...
AI learns patterns from examples better than from descriptions.
Technique 3: Request Step-by-Step Reasoning
Instead of: “Design a caching layer”
Try: “Design a caching layer. First, list the requirements. Then, evaluate three approaches with pros/cons. Finally, recommend one with justification.”
Forcing explicit reasoning often produces better results and lets you catch errors in logic before implementation.
Technique 4: Specify Format and Structure
Instead of: “Document this API”
Try: “Document this API using this format:
- Brief description (one sentence)
- Parameters (name, type, description for each)
- Returns (type and description)
- Example usage (code snippet)
- Edge cases and error conditions”
Explicit structure prevents missing important information.
Technique 5: Use Constraints to Guide Quality
Instead of: “Generate test cases”
Try: “Generate test cases that:
- Cover all branches
- Test edge cases (empty input, null, max values)
- Include one negative test per function
- Use descriptive test names”
Constraints guide AI toward better outputs without requiring you to review and request additions.
Technique 6: Ask AI to Check Its Own Work
After AI generates output:
“Review the code you just wrote for:
- Type errors
- Unhandled edge cases
- Performance issues
- Security vulnerabilities
List any issues found and provide fixes.”
AI often catches its own mistakes when explicitly prompted to review.
Technique 7: Break Complex Tasks into Subtasks
Instead of: “Implement user authentication with email verification, password reset, and rate limiting”
Try:
Let's implement authentication in stages:
1. First, just basic login/logout
2. Then add email verification
3. Then add password reset
4. Finally, add rate limiting
Let's start with stage 1...
This prevents AI from trying to handle too much at once and getting confused.
Notice the pattern across all seven techniques: none of them are really about writing a better sentence. They are about shaping what the model knows before it generates a response — providing role context, supplying examples, structuring constraints, decomposing complexity. Each technique engineers a different dimension of the model’s informational environment. That is context engineering in practice.
Teaching AI Your Patterns and Preferences
The techniques above shape context within a single exchange. But context engineering also operates at the session level — establishing patterns, preferences, and shared understanding that improve every interaction that follows. While current AI systems don’t learn persistently across sessions, you can “teach” them within a conversation by providing consistent examples.
Creating a Style Guide
Compile examples of your preferred patterns and provide them as reference:
# Our Code Style
## Naming Conventions
- Variables: camelCase (userData, not user_data)
- Functions: verbNoun (getUserData, not get_data)
- Classes: PascalCase (UserManager, not userManager)
## Error Handling
Always use try-catch with specific error types:
```javascript
try {
// operation
} catch (error) {
if (error instanceof ValidationError) {
// handle validation
} else {
// handle unexpected
logger.error(error);
throw error;
}
}
Example of Good Code
[Show 2-3 examples of well-written code from your codebase]
Then reference this when prompting: "Follow the style guide I provided earlier"
**Establishing Preferences Through Examples**
If AI keeps making the same mistake, create an example that shows the correct pattern:
"When implementing data fetching, always use this pattern:
```javascript
async function fetchData() {
const cacheKey = generateKey();
const cached = await cache.get(cacheKey);
if (cached) return cached;
const fresh = await fetch(source);
await cache.set(cacheKey, fresh);
return fresh;
}
Now implement fetchUserProfile() following this pattern."
Building Shared Context
Early in a session, establish shared understanding:
“Context for this session:
- We’re working on a Node.js API server
- We use TypeScript strict mode
- All database access goes through our ORM (Prisma)
- We follow RESTful conventions
- We write tests using Jest
Keep this context in mind for all following questions.”
This reduces repeated explanations and improves consistency.
Correcting Persistent Errors
If AI repeatedly makes the same mistake:
“I notice you keep using var instead of const/let. In modern JavaScript:
- Use
constby default - Use
letif reassignment is needed - Never use
var
Going forward, always use const/let. Confirm you understand this rule.”
Explicit confirmation helps establish the correction.
When to Restart vs. When to Persist
Sometimes a conversation with AI goes off the rails. Deciding whether to restart or persist is important:
Restart when.
AI is consistently misunderstanding despite multiple corrections
The conversation has accumulated too much confusing context
You want to try a completely different approach
AI is hallucinating heavily and corrections aren’t helping
You’ve been iterating for >10 rounds without convergence
Persist when.
You’re making steady progress (each iteration improves)
AI has built up useful context you’d have to re-provide
The problem is complex but you’re narrowing in on solution
Errors are easy to identify and correct
How to restart effectively.
Don’t start completely fresh—take your learning with you
Incorporate corrections from the failed session into your new prompt
Be more explicit about requirements upfront
Consider breaking the task into smaller pieces
Example of improved restart:
First session: "Create a user authentication system"
→ AI made many mistakes, had to correct repeatedly
Restart session: "Create a user authentication system with these requirements:
- Use bcrypt for password hashing (not plain text)
- Generate JWT tokens after successful login
- Validate tokens on protected routes
- Handle these edge cases: [list from first session]
Here's an example of our preferred code structure: [paste example]"
You’ve learned what to specify upfront from the failed session.
Chapter Summary
Working with AI requires new mental models. Treat AI as a cognitive prosthetic rather than a colleague or simple tool—it extends capability but requires learning to use effectively [@Parasuraman1997; @Dietvorst2015].
Four interaction modes serve different purposes. Delegation (low involvement, clear tasks), Collaboration (iterative refinement), Supervision (monitor autonomous work), and Augmentation (AI as extension of self) each suit different contexts [@Bainbridge1983].
Choosing the right mode requires judgment. Consider task clarity, your expertise, stakes, time available, novelty, and desired involvement level. Mode switching when one approach isn’t working is normal and productive.
Effective correction requires diagnosis. Categorize failures (misunderstood requirements, incomplete context, edge cases, wrong patterns, hallucination) and provide specific, actionable feedback rather than vague criticism.
Context engineering is the higher-order discipline. Effective AI collaboration requires shaping the model’s entire informational environment — not just the immediate prompt. Techniques like providing role and context, showing examples, requesting step-by-step reasoning, specifying format, using constraints, self-review prompts, and task decomposition are all components of context engineering.
Teaching AI within sessions is possible. Create style guides, establish preferences through examples, build shared context early, and explicitly correct persistent errors with confirmation.
Know when to restart. If making no progress after many iterations, restart with lessons learned. If making steady progress, persist despite imperfections.
Emotional regulation matters. Expect imperfection, separate capability from reliability, take breaks when frustrated, maintain calibrated skepticism, and remember that even imperfect AI assistance often beats working alone [@Vaccaro2018].
Maintain appropriate skepticism always. As we’ll explore in Chapter 10, calibrated trust means verifying outputs systematically, especially for high-stakes or novel tasks.
In the next chapter, we’ll examine calibrated trust—how to develop systematic judgment about when to trust AI outputs and when to verify them, building the discernment that separates effective AI collaboration from dangerous over-reliance.