Courseiva

CCNA Prompt Engineering and Structured Output Questions

57 questions · Prompt Engineering and Structured Output · All types, answers revealed

1
MCQmedium

Refer to the exhibit. The developer wants to ensure the summary is concise and follows a specific structure. What is the most effective way to improve this prompt?

A.Include the instructions directly inside the user content field.
B.Use a system prompt to define the task, format, and style constraints.
C.Increase the temperature setting to 1.0 to ensure more creative summaries.
D.Repeat the instruction three times within the user content to enforce it.
AnswerB

The system prompt is the appropriate location for defining formatting and behavioral constraints. By placing instructions here, the model treats them as immutable directives. This separation ensures the model consistently adheres to the desired structure and tone, regardless of the variations found in the document content provided.

Why this answer

Providing a system prompt to establish the 'Persona' and 'Task Constraint' is superior to relying on the user message. By separating instructions from content, you provide a stable context for the model. This is standard architectural practice for Anthropic models, ensuring that the model maintains its directive despite varying document lengths, thus improving the consistency and quality of the generated summarization output over time.

Exam trap

Candidates often suggest modifying the user message directly to include more instructions, failing to realize that system prompts are the architectural standard for defining task constraints and style.

2
MCQmedium

Which strategy most effectively handles long documents that exceed the model's immediate focus in a single prompt?

A.Use a single prompt and ask the model to process the entire document at once.
B.Implement a Map-Reduce strategy to process document chunks independently.
C.Increase the 'max_tokens' parameter to its maximum limit.
D.Switch to a different model family that supports infinite input.
AnswerB

Map-Reduce is the industry-standard design pattern for large-scale document processing. By splitting the task into modular chunks, you ensure that the model can focus effectively on each part. The final aggregation step then combines these insights, providing a much more reliable and coherent final result than a single-shot attempt.

Why this answer

The 'Map-Reduce' pattern is the standard architectural approach for handling large datasets. You break the document into smaller chunks, process them independently to generate intermediate results, and then perform a final 'aggregation' pass to synthesize those results. This ensures that no individual prompt exceeds the optimal processing capacity, maintaining high quality throughout the pipeline while overcoming the limitations of single-prompt context handling for massive amounts of data.

Exam trap

Candidates often choose to increase the model's context window limit or attempt to pass the entire document in a single prompt, ignoring the efficiency and scalability benefits of chunking.

3
MCQhard

Refer to the exhibit. The developer observes that Claude occasionally includes conversational filler before the JSON block. What is the most reliable way to ensure the output starts immediately with the JSON object?

A.Include a strict JSON schema in the system prompt.
B.Prefill the assistant response with the '{' character.
C.Set the temperature to 0.0 for deterministic output.
D.Use a higher frequency penalty to avoid repetitions.
AnswerB

Starting the assistant's message with an opening curly brace forces the model to complete the JSON object immediately. This technical maneuver bypasses the model's tendency to explain its actions, ensuring that the very first character of the generated response is part of the structured data payload.

Why this answer

Prefilling the assistant's response is a powerful technique to force Claude to start its output with a specific character or string. By providing the opening brace of the JSON object in the assistant message, the model is constrained to continue the sequence as a valid JSON object, effectively eliminating any preceding conversational text or explanations.

Exam trap

Candidates often suggest using system prompts or specific output instructions like 'do not include conversational text,' which are frequently ignored by the model, rather than using the structural prefill technique.

4
MCQmedium

Which of the following describes the 'Chain of Thought' prompting strategy, and why should it be used for complex logic tasks?

A.Providing the model with a list of facts and asking it to select the most relevant one.
B.Asking the model to outline its reasoning process step-by-step before providing the final answer.
C.Instructing the model to write its output in a specific programming language format.
D.Forcing the model to repeat the user's prompt back to them to ensure comprehension.
AnswerB

Chain of Thought forces the model to articulate its logic, which acts as a self-correction mechanism. This step-by-step articulation allows the model to verify its own intermediate conclusions, leading to much higher accuracy for complex, multi-step logical problems compared to asking for a single-step final answer.

Why this answer

Chain of Thought involves asking the model to show its reasoning process before delivering the final answer. This is critical for complex tasks because it forces the model to decompose the problem into intermediate steps, which significantly reduces logical errors. By 'thinking' through the steps, the model is less likely to hallucinate the result, leading to more reliable and verifiable outputs in complex analytical scenarios.

Exam trap

Many candidates assume Chain of Thought is only for complex math, ignoring its utility in reducing hallucinations and logical errors in general analytical or classification tasks.

5
MCQhard

A developer builds a Claude-powered assistant that answers questions over a 300-page policy manual. When the whole manual is placed in a single prompt, answers to questions about clauses in the middle of the document are frequently wrong or vague, while answers about the opening and closing sections are accurate. The manual must stay available in full, and the team wants to keep latency reasonable. Which technique most effectively improves accuracy for the mid-document clauses?

A.Split the manual into sections, embed each section, retrieve the most relevant sections for the question, and place only those retrieved sections in the prompt before the question.
B.Increase max_tokens substantially and instruct the model to think step by step before answering each question.
C.Ask the user to restate their question using exact phrases from the manual so the model can match keywords directly.
D.Keep the full manual in the prompt but move it so the manual text appears after the question rather than before it.
AnswerA

Retrieval-augmented prompting addresses the mid-document weakness by selecting the passages most relevant to the question and placing them near the end of the prompt, where attention is strongest. The model reasons over a small, on-topic context instead of a long document, improving accuracy for clauses that previously sat in the poorly attended middle. Keeping the full manual in the index preserves availability while bounding prompt size and latency.

Why this answer

Accuracy drops for material buried in the middle of a very long context because attention is spread thin across the document. Retrieving the sections most relevant to each question and placing only those in the prompt shrinks the context to on-topic passages, which restores accuracy for mid-document clauses while the full manual stays indexed for availability. Reordering or enlarging the same long context does not fix the attention problem.

Exam trap

The trap here is assuming that simply reordering the long document or enlarging the token budget fixes mid-context recall, when the real fix is reducing the prompt to retrieved, relevant passages.

6
MCQhard

A team is extracting medication names and dosages from clinical notes. The notes contain many similar-looking terms, and the team needs high precision to avoid false positives. They plan to use few-shot examples. Which design of the few-shot examples best supports high precision in this scenario?

A.Include a mix of positive examples and carefully chosen hard negatives that resemble medications but should not be extracted.
B.Provide many examples of correct extractions only, covering a wide range of medication names.
C.Randomly sample examples from the dataset without regard to difficulty or similarity.
D.Use a single detailed example and rely on the model to generalize to all other notes.
AnswerA

Hard negatives show the model the boundary between true medication mentions and lookalikes, which directly improves precision. In this scenario, where similar terms cause false positives, contrastive examples clarify what to exclude. This design teaches the decision boundary rather than only the target class, making it the most effective choice for high precision.

Why this answer

High precision in a field with lookalike terms depends on teaching the model where the boundary lies. A mix of positive examples and hard negatives does that by showing both what to extract and what to reject. Positive-only, single-example, or random sampling designs do not surface the confusing cases, so they are less likely to reduce false positives in clinical extraction.

Exam trap

The trap here is assuming that more positive examples alone improve extraction, when precision in a lookalike-rich domain depends on contrastive hard negatives.

7
MCQmedium

A financial analyst uses Claude via the Messages API to extract line items from scanned invoices. The response must be valid JSON conforming to a fixed schema with fields invoice_number, date, and total. During testing, the model occasionally adds a trailing sentence after the JSON object or wraps the JSON in a markdown code fence. Which approach best guarantees the response parses cleanly while preserving extraction accuracy?

A.Instruct the model to begin the response with a tool_use block whose input_schema defines the invoice fields, then read the structured tool input from the response.
B.Set the max_tokens parameter to the exact length of the expected JSON string so the model cannot emit extra characters.
C.Request the JSON inside <output> tags and run a regular expression that captures everything between the opening and closing tags.
D.Append the phrase 'Return only JSON' to the end of the system prompt and set temperature to 0.0 before each request.
AnswerA

Defining a tool with an input_schema and instructing the model to call it constrains generation through the model's structured tool-calling pathway, so the extracted fields arrive as a parsed JSON object inside the tool_use block rather than as free text. This removes code fences and trailing prose while keeping the model focused on the invoice content, giving both clean parsing and high extraction accuracy.

Why this answer

Constraining the response through a tool definition with an input_schema channels generation into the model's structured tool-calling pathway, so the extracted invoice fields arrive as an already-parsed object instead of free-form text. This eliminates markdown fences and trailing commentary while keeping the model focused on the document content. Prompt phrasing and sampling parameters reduce, but do not remove, format drift.

Exam trap

The trap here is assuming that adding 'Return only JSON' or lowering temperature guarantees parseable output, when only schema-constrained generation removes format drift.

8
Multi-Selecthard

You are building a document-processing pipeline with the Anthropic Messages API. Claude must extract a fixed set of fields from each document and return them as JSON. In production, you observe two problems: (1) some responses include explanatory prose before the JSON, and (2) some responses omit required fields when the document is ambiguous. You need to make the pipeline more reliable. (Choose two.)

Select 2 answers
A.Add a stop sequence of '\n\n' so Claude stops as soon as it finishes the JSON object.
B.Prefill the assistant turn with `{` to force the response to begin as a JSON object.
C.Set `temperature` to 0 to make the output deterministic and therefore always complete.
D.Increase `max_tokens` to the model's maximum so the response has room for all fields.
E.Define the required fields and their types in the system prompt, and instruct Claude to use null for fields it cannot determine.
AnswersB, E

Prefilling the assistant turn with `{` makes Claude continue directly from that character, so the response cannot start with explanatory prose or a markdown fence. This directly addresses the first observed problem by structurally guaranteeing that the output begins as a JSON object. It is the recommended Anthropic technique for eliminating preamble and is a correct choice for improving reliability.

Why this answer

The two problems are a formatting issue and a completeness issue. Prefilling the assistant turn with `{` structurally prevents prose before the JSON, and specifying required fields with a null fallback ensures keys are always present even when the document is ambiguous. Raising max_tokens, lowering temperature, or adding a stop sequence do not enforce format or completeness and can even truncate valid output.

Exam trap

The trap here is assuming that sampling parameters like temperature or max_tokens can fix structured-output reliability, when only structural constraints and explicit schema instructions do.

9
MCQmedium

A developer is building a classification pipeline that routes support tickets into one of eight categories. They want Claude to return a category label and a confidence score between 0 and 1. The output must be parseable by a JSON parser without post-processing. They plan to use the Anthropic Messages API. Which approach best ensures the output is directly parseable JSON with the required fields?

A.Set `temperature` to 1 and rely on the model's creativity to produce varied but valid JSON.
B.Ask Claude to return the category and confidence in a single sentence like 'Category: X, Confidence: 0.9'.
C.Describe the JSON schema in the system prompt, prefill the assistant turn with `{`, and validate the response with a JSON parser.
D.Use the `stop_sequences` parameter set to '}' so Claude stops as soon as it finishes the JSON object.
AnswerC

Combining a clear schema description with an assistant-turn prefill of `{` produces raw JSON that starts with the opening brace, and validating with a parser catches any rare deviation. This is the recommended Anthropic pattern for guaranteed parseable JSON. The schema description tells Claude which keys and types to emit, while the prefill prevents preamble or code fences, making the output directly parseable.

Why this answer

Describing the schema in the system prompt gives Claude the keys and types to emit, and prefilling the assistant turn with `{` forces the response to begin as a JSON object with no preamble or markdown fence. Validating with a JSON parser catches rare deviations. Together these produce directly parseable output, unlike free-text formats, stop-sequence tricks, or high-temperature sampling.

Exam trap

The trap here is thinking that a stop sequence on the closing brace will neatly end the JSON, when in fact it truncates the response and removes the closing brace.

10
MCQmedium

Refer to the exhibit. When using variable injection in a prompt template for Claude, why is the use of XML tags preferred over simple text labels?

A.XML tags automatically compress the input tokens.
B.XML tags are a requirement for the Anthropic API to function.
C.They provide clear delimiters for variable content.
D.XML tags prevent the model from using outside knowledge.
AnswerC

XML tags act as explicit boundaries that prevent the model from 'bleeding' the content of one variable into another. This structural clarity is vital when variables contain complex data, ensuring Claude correctly attributes the metadata (like the source) to the correct piece of content.

Why this answer

XML tags provide a clear, unambiguous structure that helps Claude identify where one variable ends and another begins. This is especially important when the variables contain unstructured text that might include characters like colons or dashes, which could confuse the model if simple text labels were used as delimiters.

Exam trap

Candidates often incorrectly assume XML tags are for tokenization efficiency or model speed, rather than recognizing their primary purpose as clear, unambiguous delimiters for variable content within prompts.

11
MCQhard

You are using Claude to generate complex JSON configurations. The model frequently truncates the output because the response exceeds the token limit. What is the most robust architectural solution to handle this?

A.Increase the max_tokens parameter to the absolute maximum allowed by the API.
B.Decompose the prompt into multiple sequential calls that generate parts of the configuration.
C.Use a system prompt to ask the model to summarize the configuration if it gets too long.
D.Switch to a model with a smaller context window to force the model to be concise.
AnswerB

Decomposition reduces the cognitive load on the model for each turn, resulting in higher accuracy and better adherence to structural constraints. It also allows for easier error handling and validation at each stage of the process, ensuring that the final configuration is built from validated, smaller, accurate components.

Why this answer

When complex output is required, breaking the task into sub-tasks or using a more granular approach is superior to just increasing token limits. Truncation is often a sign of a complex, monolithic prompt. By splitting the work into smaller, manageable chunks, you maintain high output quality, ensure structural integrity, and avoid the risks associated with hitting hard output length limits in a single turn.

Exam trap

Candidates frequently opt to increase the maximum generation length parameter, ignoring that complex monolithic outputs naturally degrade in quality and hit limits.

12
Multi-Selecthard

You are building an application that extracts data from messy, unstructured text. Which THREE practices help maximize the accuracy and consistency of the extraction?

Select 3 answers
A.Providing few-shot examples that show both clean and noisy input scenarios.
B.Using a very high temperature setting to encourage creative extraction interpretations.
C.Defining explicit negative constraints in the system prompt.
D.Requesting the model to summarize the text before performing the extraction.
E.Using a strict JSON schema via tool use to define the output format.
AnswersA, C, E

Few-shot examples are highly effective at helping the model understand how to handle edge cases and noise. By seeing how to extract data from messy text in examples, the model learns the implicit rules for cleaning and structuring the information, which significantly improves the quality of the extraction.

Why this answer

To achieve high accuracy in extraction, you need to provide the model with a clearly defined schema, few-shot examples of inputs and outputs, and clear negative constraints. These three pillars guide the model on how to handle noise, what the expected structure is, and what to avoid, ensuring the output is consistently usable for automated systems without manual intervention or excessive cleanup.

Exam trap

Candidates frequently select generic prompt tuning or increased token limits while ignoring the necessity of strict structural schemas and negative constraints.

13
MCQmedium

An architect is building a legal research assistant using Claude 3.5 Sonnet. To ensure the model adopts a formal, authoritative tone and strictly adheres to statutory interpretations, where is the most effective location to define this persona?

A.At the end of the user message using a specific 'tone' tag.
B.Within the system prompt field.
C.Inside a JSON schema definition for the output.
D.By setting a specific stop sequence for informal words.
AnswerB

System prompts are specifically designed to provide high-level instructions and context that govern the model's behavior throughout the interaction. By establishing the legal researcher persona here, Claude internalizes the constraints more effectively, resulting in higher fidelity to the desired authoritative tone and statutory focus.

Why this answer

Defining the persona in the system prompt sets the foundational behavior and context for the entire conversation. This approach ensures that Claude maintains consistency in its professional tone and adherence to specific constraints, such as statutory interpretation, without needing repetitive instructions in every user message, thereby optimizing the model's performance and output reliability.

Exam trap

Candidates mistakenly place persona definitions inside user prompts or individual task messages, leading to inconsistent tone enforcement across multi-turn conversations.

14
MCQmedium

An application requires Claude to consistently return JSON data for a configuration parser. Which technique most effectively ensures the model adheres to a specific schema?

A.Add a system prompt stating 'Output only JSON'.
B.Include 50 examples of JSON in the prompt.
C.Use the assistant pre-fill feature to start with '{'.
D.Set the temperature to 0.0 without other changes.
AnswerC

Pre-filling the assistant response with the opening curly brace forces the model to complete the string as a valid JSON object. This technique is a robust architectural pattern in the Claude API that minimizes non-JSON tokens and ensures the generated content is immediately ready for schema validation.

Why this answer

Using pre-filling with a starting brace is the most effective way to constrain the model's output in the Claude API. By providing the opening '{' inside the assistant block, you force the model to continue the sequence in valid JSON format. This architectural pattern reduces hallucinations and ensures the downstream parser successfully processes the structured output without requiring complex post-processing or excessive few-shot examples.

Exam trap

Candidates often suggest using extensive few-shot examples or complex system prompts to force JSON, ignoring that pre-filling the assistant response is a more direct, reliable structural constraint.

15
MCQhard

An architect is designing a prompt that asks Claude to analyze a contract and return a risk rating plus supporting clauses. The response must be machine-readable and include a confidence score. Which design most reliably produces both a rating and a confidence score in a single response?

A.Include a few-shot example showing a JSON object with both keys and ask Claude to follow it exactly.
B.Define a tool with an 'input_schema' containing required 'rating' and 'confidence' properties and force tool use.
C.Ask for a JSON object with 'rating' and 'confidence' keys and parse the text response.
D.Use two separate prompts: one for rating and one for confidence, then merge the results.
AnswerB

A tool 'input_schema' with both properties marked required and tool use forced ensures Claude returns a tool call containing both values. The schema mechanically enforces presence and type, so the application receives a single structured object with rating and confidence together. This is the most reliable way to get both fields in one response.

Why this answer

A tool definition with an 'input_schema' that marks 'rating' and 'confidence' as required, combined with forced tool use, guarantees both fields appear in a single structured tool call. This keeps the rating and its confidence score aligned and eliminates parsing ambiguity. Few-shot examples and prose instructions only influence behavior and cannot enforce required fields.

Exam trap

The trap here is assuming that a well-crafted JSON instruction or example guarantees both fields, when only a schema with required properties enforces their presence.

16
MCQmedium

A data-engineering team uses Claude to normalize product descriptions into a fixed set of attributes. Their few-shot examples all come from the electronics catalog, and accuracy is high there, but when the same prompt is applied to apparel listings the model mislabels attributes. They want to improve apparel accuracy without degrading electronics results. Which approach best addresses the problem?

A.Lower the temperature to 0.0 and keep the existing electronics-only example set unchanged.
B.Add a small number of diverse, correctly labeled few-shot examples drawn from apparel alongside the existing electronics examples.
C.Raise the number of electronics examples from four to twenty so the model has more evidence about how attributes are labeled.
D.Remove all few-shot examples and rely solely on detailed prose definitions of each attribute.
AnswerB

Few-shot examples teach the model the mapping between input phrasing and output attributes, so examples from the apparel domain supply the patterns the model is currently missing while the retained electronics examples preserve performance there. Mixing domains in one prompt broadens the demonstrated distribution without retraining. This directly targets the observed domain gap while protecting existing accuracy.

Why this answer

Few-shot examples define the distribution the model imitates, so the electronics-only set teaches electronics patterns and fails on apparel. Adding a few correctly labeled apparel examples introduces the missing patterns while keeping the electronics demonstrations that already work, improving the weak domain without harming the strong one. Sampling and prompt-length changes do not broaden domain coverage.

Exam trap

The trap here is assuming that more examples always help, when additional examples from only the already-working domain deepen the bias instead of covering the failing domain.

17
Multi-Selecthard

When designing a prompt for high-reliability JSON extraction from unstructured medical reports, which THREE strategies are considered best practices for Anthropic models?

Select 3 answers
A.Provide a clear JSON schema or template.
B.Use few-shot examples with valid JSON output.
C.Prefill the assistant response with '{'.
D.Set the temperature to 1.0 for diverse extractions.
E.Avoid using XML tags for the input reports.
AnswersA, B, C

Defining the keys and expected data types in a schema gives Claude a blueprint to follow. This reduces ambiguity about how to represent specific medical findings and ensures that the resulting JSON can be reliably parsed by downstream software systems without manual intervention or complex regex.

Why this answer

Achieving reliable structured output involves providing a clear schema, showing the model examples of the desired output, and using prefilling to guide the start of the response. These techniques combined minimize formatting errors and ensure the model adheres to the specific data types and keys required by the application.

Exam trap

Candidates often overlook the necessity of prefilling the assistant response, incorrectly believing that a system prompt instruction alone is sufficient to guarantee valid JSON formatting in all cases.

18
MCQeasy

Which of the following is the recommended approach for handling PII (Personally Identifiable Information) in prompts?

A.Tell the model in the system prompt to ignore and delete any PII found.
B.Redact the PII at the application layer before sending the request to the API.
C.Use a specialized system prompt that instructs the model to encrypt the data.
D.Send the PII but add a disclaimer in the system prompt about data usage.
AnswerB

Redacting PII before the data leaves your infrastructure is the industry standard for security. This prevents sensitive information from being processed by external services, maintaining full control over the data lifecycle. It is the most robust way to ensure that the model never encounters or outputs actual user data.

Why this answer

Always sanitize PII before it reaches the model to protect user privacy and comply with data governance policies. Anthropic recommends that sensitive data be redacted or masked upstream. Relying on the model to ignore or redact PII is not a secure architectural pattern, as models are not deterministic security filters.

Protecting data at the application layer ensures compliance and minimizes security risks within the LLM pipeline.

Exam trap

Candidates often assume that instructing the model to 'ignore PII' or 'redact PII' is sufficient, ignoring the risk of model failure or leakage of sensitive information in the output.

19
Multi-Selectmedium

A data scientist is adjusting generation parameters for a creative writing application. They want to ensure a wide variety of vocabulary while preventing the model from selecting highly improbable words. Which TWO parameters should be adjusted?

Select 2 answers
A.Temperature.
B.Max Tokens.
C.Top-P (Nucleus Sampling).
D.Stop Sequences.
E.Presence Penalty.
AnswersA, C

Temperature controls the 'randomness' of the output by scaling the probability distribution of the next token. A higher temperature increases variety by making less likely tokens more probable, which is essential for creative writing, although it must be balanced to maintain the logical flow of the narrative.

Why this answer

Temperature and Top-P are the primary controls for balancing creativity and coherence. Temperature scales the logits to influence the probability distribution, while Top-P (nucleus sampling) cuts off the 'long tail' of low-probability tokens, ensuring that the model remains creative without drifting into nonsensical or irrelevant word choices.

Exam trap

Candidates often confuse Temperature and Top-P with frequency or presence penalties, which are not standard controls for balancing creativity and coherence in the context of Anthropic API parameters.

20
MCQmedium

You are iterating on a prompt that summarizes technical articles. The summaries are sometimes too long and sometimes miss the required 'key_takeaways' section. You want to diagnose whether the problem is the instruction wording or the input content. Which practice best supports systematic prompt iteration?

A.Maintain a small set of representative articles with expected outputs and run the prompt against them after each change.
B.Change several instructions at once and evaluate the final output by reading it once.
C.Switch to a larger model and assume the summaries will meet the requirements.
D.Ask Claude to critique its own summary and trust the critique as the final answer.
AnswerA

A fixed evaluation set with expected outputs lets you compare results across prompt versions and see whether a change improves length control or key_takeaways coverage. In this scenario, it separates wording effects from content effects because the same inputs are reused. This is the foundation of reliable prompt iteration and regression testing.

Why this answer

Using a fixed evaluation set with expected outputs is the core of systematic prompt iteration. It makes results comparable across versions and isolates the effect of instruction wording from input content. Changing many things at once, switching models, or trusting self-critique does not provide the controlled measurement needed to diagnose the length and missing-section problems.

Exam trap

The trap here is believing that a stronger model or self-critique replaces a repeatable evaluation set, when only controlled comparison across versions reveals the true cause.

21
MCQhard

You notice that your prompt, which works perfectly with Claude 3.5 Sonnet, fails when you switch to Claude 3 Haiku. What is the most likely reason?

A.The context window is smaller on Haiku.
B.Haiku has a higher temperature default, causing more errors.
C.Haiku requires more granular instructions and more few-shot examples.
D.The API endpoint has changed for the smaller model.
AnswerC

Smaller models benefit significantly from explicit, step-by-step instructions and robust few-shot examples to compensate for lower parameter counts. What suffices as a 'hint' for Sonnet may be insufficient for Haiku. Refining the prompt to be more prescriptive will help the smaller model perform the task more effectively.

Why this answer

Smaller models like Haiku have less 'instruction-following capacity' and may require more explicit, simplified prompting compared to larger models like Sonnet. When switching to smaller models, you must often reduce task complexity, provide more examples, and simplify formatting instructions. The smaller model's reduced parameter count necessitates clearer, less ambiguous prompts to achieve the same level of structural adherence and task accuracy expected from larger, more capable models.

Exam trap

Candidates often attribute the failure to a bug in the API or the model itself, rather than recognizing the reduced instruction-following capability of smaller, faster models.

22
MCQhard

You are building an agent that uses tool calls to interact with an external API. The agent is failing to select the correct tool. What is the most effective way to improve the agent's tool selection performance?

A.Increase the system prompt length to include more examples of tool calls.
B.Improve the 'description' field for each tool to clearly state when it should be used.
C.Combine multiple tools into one large tool with optional parameters.
D.Set the temperature to 1.0 to allow the model to explore different tool options.
AnswerB

The 'description' field is the primary signal for the model to understand the tool's functionality and scope. By providing clear, concise instructions on when to invoke the tool and what input is expected, you significantly increase the likelihood of the model selecting the correct tool for the specific user request.

Why this answer

For tool selection, the quality of the tool's name and description is paramount. Claude relies on these descriptions to understand the semantic intent of the tool. If the descriptions are vague or lack clear context, the model will struggle to map user requests to the appropriate tool.

Improving the documentation within the tool definition is the single most effective architectural lever for improving tool-use accuracy.

Exam trap

Candidates often focus on the tool's code implementation rather than the semantic clarity of the tool's description, which is the actual signal the model uses for selection.

23
MCQmedium

Refer to the exhibit. The model output is inconsistently professional. What is the best architectural improvement?

A.Add a definition of 'professional' in the system prompt.
B.Use a few-shot prompt with an example of the desired professional output.
C.Set the top_p parameter to 0.1.
D.Change the role to 'Professional Writer' in the system prompt.
AnswerB

Few-shot prompting provides the model with a clear target. By showing the model how you want an informal paragraph to be transformed into a professional one, you calibrate its style effectively. This is far more successful than descriptive instructions for style-based tasks because it demonstrates the expected output.

Why this answer

By providing a few-shot example that demonstrates a 'before' and 'after' transformation, you give the model a concrete target for 'professionalism.' Professionalism is subjective; examples provide the standard by which the model should calibrate its transformations. This approach is superior to abstract instructions, as it aligns the model's style with your specific enterprise requirements effectively.

Exam trap

Candidates often rely on abstract adjectives like 'be professional' in prompts, underestimating the subjective nature of tone without concrete demonstrations.

24
Multi-Selecthard

A platform team ships a Claude-based service that classifies incoming tickets into one of eight categories and returns a JSON object with category and confidence. In production they observe two failure modes: the model sometimes returns a category outside the eight allowed values, and occasionally returns confidence as the string "high" instead of a number. Which TWO changes most directly reduce these failures while keeping the pipeline automated? (Choose two.)

Select 2 answers
A.Add a validation step that parses the JSON, checks category against the allowed list and confidence against a numeric range, and re-prompts with the specific error when either check fails.
B.Define a tool whose input_schema enumerates the eight categories for the category property and types confidence as a number, then read the structured tool input.
C.Ask the model in the prompt to 'be careful and always use one of the eight categories', and trust the instruction without further checks.
D.Increase max_tokens so the model has more room to produce the JSON object without truncation.
E.Raise the temperature to 0.7 so the model explores more phrasing and is less likely to repeat a bad category.
AnswersA, B

A post-generation validator that inspects category membership and confidence type catches exactly the two failure modes and, by feeding the concrete error back on a retry, gives the model a targeted correction. This closes the loop so invalid outputs never reach downstream systems, and it works even when the model ignores schema hints. It complements schema constraints by handling residual drift.

Why this answer

Schema-constrained tool input directly prevents out-of-set categories and non-numeric confidence by enumerating and typing the fields, while a validating re-prompt loop catches any residual drift and feeds the exact error back for correction. Together they address both failure modes structurally. Sampling and length parameters do not constrain vocabulary or type, and unverified prose instructions are too weak for production.

Exam trap

The trap here is believing that a clear prose instruction alone fixes type and vocabulary drift, when only schema constraints plus validation reliably enforce them.

25
MCQmedium

Refer to the exhibit. You are using few-shot prompting to guide the model's extraction behavior. What is the purpose of including this specific interaction in your prompt?

A.To reduce the number of tokens required for the actual extraction task.
B.To force the model to use a specific ticker symbol if it's missing.
C.To define the expected output format and behavior for missing data points.
D.To increase the temperature of the model for that specific prompt.
AnswerC

This example explicitly teaches the model how to handle cases where the required information does not exist. It ensures consistency by setting a precedent for using 'N/A' as a null value, which is vital for schemas that require all fields to be populated to avoid errors in downstream data ingestion.

Why this answer

Providing a few-shot example that demonstrates how to handle missing information (e.g., 'N/A') is crucial for robust data extraction. It shows the model exactly how to maintain schema consistency when data is absent. Without such an example, the model might hallucinate values or skip fields, breaking the downstream JSON parser.

This establishes a predictable pattern for handling nulls or missing attributes in your data pipeline.

Exam trap

Candidates often focus only on positive examples in few-shot prompting, neglecting edge cases like missing or null data, which leads to unpredictable output when real-world data is imperfect.

26
MCQmedium

A company wants to prevent Claude from answering questions outside the scope of their internal knowledge base. Which prompt engineering strategy is most effective for enforcing this constraint?

A.Increase the top-p value to allow more diverse answers.
B.Use few-shot examples of Claude answering general knowledge.
C.Include explicit 'stay in character' instructions in the user message.
D.Set strict boundary instructions in the system prompt.
AnswerD

The system prompt is the ideal location for establishing 'guardrails' and boundary conditions. By instructing the model to only use the provided context and to state 'I do not have information on that' for other topics, you create a robust mechanism for ensuring the model stays on-task.

Why this answer

Negative constraints and grounding instructions in the system prompt are essential for maintaining scope. By explicitly telling the model to decline questions not covered by the provided context and providing a specific 'out-of-scope' response phrase, the developer can reliably control the model's boundary behavior and reduce hallucinations.

Exam trap

Candidates often assume that simply stating 'only use the provided files' is sufficient, failing to include a specific negative constraint or a fallback response for out-of-scope queries.

27
MCQeasy

Which of the following is an advantage of using XML tags in Anthropic prompts?

A.It guarantees that the output will be in JSON format.
B.It helps the model differentiate between instructions and data.
C.It automatically reduces the token usage of the prompt.
D.It is required for the Anthropic API to function.
AnswerB

XML tags act as clear delimiters that allow the model to interpret sections of the prompt with specific intent. This structural separation is highly effective for reducing confusion in long or complex prompts, as it helps the model identify what is data to be processed versus instructions to be followed.

Why this answer

XML tags provide a clear way to structure input, allowing the model to distinguish between instructions, examples, and data. Because Claude is trained to respect these delimiters, using them improves the model's ability to parse complex prompts. This architectural clarity reduces ambiguity, makes prompts easier to maintain, and leads to significantly more consistent performance, especially when dealing with complex data extraction or multi-step reasoning tasks.

Exam trap

Test-takers frequently believe XML tags are only meant to reduce token usage or speed up processing, confusing syntax formatting with compression techniques.

28
MCQmedium

You are designing a prompt for Claude to convert a customer email into a JSON object with fields "customer_name", "order_id", and "issue_summary". During testing, about 15% of outputs include the JSON inside markdown code fences (```json ... ```) or add a friendly sentence before the JSON. You need the raw JSON object only, with no extra text, every time. Which approach is most effective?

A.Increase the max_tokens parameter to give the model more room to complete the full JSON object.
B.Lower the temperature to 0 and rely on deterministic sampling to remove the extra text.
C.Add the instruction 'Do not use markdown' to the system prompt and repeat it in the user turn.
D.Add a prefill to the assistant turn containing the opening brace `{` so Claude must continue directly with the JSON body.
AnswerD

Prefilling the assistant turn with `{` forces the model to continue from that exact token, eliminating any preamble or markdown fence before the object. Because the response is a continuation of the prefilled turn, Claude cannot emit a sentence or a code fence opener first. This is the canonical Anthropic technique for guaranteeing raw JSON output and is the most reliable fix here.

Why this answer

Prefilling the assistant turn with the opening brace of the JSON object forces Claude to continue directly from that character, structurally preventing any preamble or markdown fence. Instructions and sampling parameters only bias the model toward the desired format; they do not enforce it. The prefill is the deterministic, Anthropic-recommended technique for guaranteeing raw structured output.

Exam trap

The trap here is assuming that a strong instruction like 'output only JSON' is sufficient, when in practice only a structural constraint such as an assistant-turn prefill guarantees the format.

29
MCQmedium

A team is using Claude to generate a structured incident report from raw log excerpts. The report must contain a 'summary' paragraph, a 'root_cause' field, and a 'remediation' list. During review, engineers find that remediation steps sometimes appear inside the summary paragraph, and summaries sometimes contain root-cause speculation. Which technique most reliably keeps each piece of content in its designated section?

A.Ask Claude to write the report as a single flowing narrative and let reviewers sort the content into the three sections afterward.
B.Randomize the order of the three sections on each invocation so the model learns to keep them separate.
C.Increase the length of the prompt by adding several paragraphs of general guidance about good report writing.
D.Define each section with XML tags and include a one-line description of what belongs in each tag, then instruct Claude to place content only within the matching tag.
AnswerD

Named XML tags give each section an explicit container, and the per-tag description states what content belongs there, so remediation steps have a dedicated list and root-cause speculation has its own field. This structural separation, reinforced by an instruction to respect tag boundaries, directly prevents content from drifting between sections.

Why this answer

Content stays in its designated section when each section is a named container with an explicit description of its contents. XML tags provide those containers and the descriptions disambiguate which material belongs where, so remediation steps have their own list and root-cause analysis has its own field. Narrative formats, generic guidance, and randomized ordering do not create the structural boundaries the task requires.

Exam trap

The trap here is assuming that clearer prose instructions alone will separate the content, when the real need is distinct structural containers that give each content type a fixed home.

30
MCQmedium

Which of the following describes the 'Sandwich' prompting technique?

A.Placing the prompt instructions before and after the main content.
B.Mixing multiple tasks in a single sandwich-style prompt.
C.Using only few-shot examples without any system instructions.
D.Formatting the entire prompt output as a JSON sandwich.
AnswerA

Sandwich prompting reinforces the model's focus by framing the content with instructions. By repeating key guidelines at the end, you ensure the model carries those constraints through the entire context window, significantly reducing the likelihood of the model forgetting its task when dealing with extensive input documents.

Why this answer

Sandwich prompting involves placing instructions at both the beginning and the end of the input context. This is highly effective because it helps the model maintain focus on the instructions even when processing very long documents, where 'lost in the middle' phenomena often occur. This architectural pattern is a critical strategy for ensuring high-quality, instruction-compliant output in long-context, enterprise-scale language processing workflows.

Exam trap

Candidates often think 'Sandwich' prompting means placing instructions only at the very beginning of the prompt or repeating them uniformly throughout every paragraph.

31
MCQmedium

You are building a data extraction pipeline using Claude 3.5 Sonnet. You need the model to return a valid JSON object representing user feedback metrics. Which technique best ensures the model adheres to your specific schema?

A.Include the schema in the system prompt and ask the model to wrap output in markdown code blocks.
B.Set the temperature to 0.0 to ensure the model produces the exact same JSON format every time.
C.Define the structure using the 'tools' parameter and require the model to call that tool.
D.Add a few-shot example in the user prompt and instruct the model to follow that pattern.
AnswerC

Defining a schema within the tools framework forces Claude to generate output that adheres to the specific JSON Schema provided. This leverages the model's native capability to generate function arguments, ensuring that the resulting object is syntactically valid and compliant with the requirements of your application's data ingestion layer.

Why this answer

Using the 'tool_use' capability is the recommended architectural pattern for enforcing structured output in Claude. By defining a schema in the tools parameter, you force the model to generate a valid JSON object that adheres strictly to the provided JSON Schema. This approach reduces hallucination and provides a programmatic contract, which is essential for downstream data processing pipelines that require predictable, machine-readable responses without parsing errors.

Exam trap

Test-takers often try to enforce JSON formats using only descriptive system prompt text, overlooking the programmatic guarantees of structured tool use.

32
MCQmedium

A developer is extracting line items from invoices. The prompt includes a schema and examples, yet Claude occasionally invents field names not in the schema. Which change most directly prevents hallucinated field names?

A.Lower the temperature to 0 to reduce randomness in field name selection.
B.Add more few-shot examples showing correct field names.
C.Instruct Claude in the system prompt to 'never add fields not in the schema'.
D.Define the extraction schema as a tool 'input_schema' and force tool use.
AnswerD

When the schema is expressed as a tool 'input_schema' and tool use is forced, Claude must emit arguments that conform to that schema. Invented field names would violate the schema and are therefore avoided. This provides structural enforcement that examples and temperature settings cannot achieve, directly preventing hallucinated keys in the extraction output.

Why this answer

Expressing the extraction schema as a tool 'input_schema' and forcing tool use constrains Claude's output to the defined fields. Because the API validates the tool call input against the schema, invented field names are structurally prevented. This is stronger than examples, temperature tuning, or negative instructions, which only influence behavior probabilistically.

Exam trap

The trap here is thinking that more examples or a strict instruction eliminates invented fields, when only schema-enforced tool use constrains the allowed key set.

33
MCQeasy

When designing a prompt, why is it important to define a clear persona for the model?

A.It increases the model's internal reasoning capability for complex math.
B.It creates a behavioral anchor that sets the tone and scope of responses.
C.It is the only way to enable JSON mode for output.
D.It prevents the model from hallucinating facts during the conversation.
AnswerB

A persona acts as an architectural guide for the model, establishing the expected tone and constraints for the output. By framing the model as an expert, you encourage it to adopt a style appropriate for the task, which improves the overall quality and consistency of the user experience.

Why this answer

Defining a persona provides a 'behavioral anchor' that influences the model's tone, verbosity, and perspective. It acts as an implicit instruction set that helps the model select the most appropriate style for the given task. This is a best practice for maintaining consistency across different interactions, ensuring that the model behaves predictably and adheres to the professional standards required by the specific application context.

Exam trap

Candidates often view personas as purely cosmetic or stylistic, failing to realize they act as critical behavioral anchors that define the scope and tone of the model's output.

34
MCQmedium

A developer is building a contract-analysis pipeline. The prompt instructs Claude to return JSON with fields 'party_a', 'party_b', and 'effective_date'. In testing, Claude sometimes wraps the JSON in a Markdown code fence or adds a trailing comment, causing json.loads to fail. Which approach best ensures the response can be parsed directly as JSON?

A.Increase the model's max_tokens so the full JSON object fits in one response.
B.Use a tool definition with a JSON schema for the contract fields and require the model to call that tool.
C.Add 'Please do not use Markdown' to the end of the prompt.
D.Instruct Claude to wrap the JSON in triple backticks so it is easy to find.
AnswerB

Defining a tool with an input schema constrains the model to emit arguments that match the schema, which the API returns as structured data. In this scenario, that guarantees the fields party_a, party_b, and effective_date are produced in a parseable form without Markdown fences or comments. Tool use is the most reliable way to enforce a JSON shape.

Why this answer

Tool use with a JSON schema is the most reliable way to force structured output. The API validates the model's arguments against the schema and returns them as structured data, so the developer receives fields that match party_a, party_b, and effective_date without Markdown. Prompt-level requests and temperature changes do not guarantee parseable JSON in the same way.

Exam trap

The trap here is treating tool use as only for external actions, when it is also the strongest mechanism for constraining the model to emit a schema-conformant JSON object.

35
MCQmedium

When designing prompts, what is the 'Persona' strategy and how does it improve performance?

A.It forces the model to use more complex and sophisticated vocabulary.
B.It helps the model adopt a relevant context, knowledge base, and tone for the task.
C.It prevents the model from hallucinating facts by setting a strict persona boundary.
D.It makes the model faster by reducing the amount of processing required.
AnswerB

Persona setting provides a frame of reference that narrows the model's search space for the most appropriate style and knowledge. It helps the model prioritize domain-specific information, improving the quality of the response by aligning it with the expected output style and professional standards of the assigned role.

Why this answer

Assigning a specific persona (e.g., 'You are a senior cybersecurity analyst') narrows the model's focus to a specific domain of knowledge and tone. This helps the model prioritize relevant vocabulary and logical patterns associated with that professional role. It acts as an implicit constraint, setting the 'style' of the reasoning, which leads to more accurate and professionally aligned results compared to a generic prompt.

Exam trap

Candidates often view personas as mere 'flavor text' rather than a functional tool to narrow the model's probabilistic space and enforce domain-specific constraints and terminology.

36
Multi-Selectmedium

You are designing a system to process customer support tickets. You want to ensure Claude provides accurate summaries and extracts the priority level. Which TWO strategies should you implement to improve output reliability?

Select 2 answers
A.Use a long system prompt that covers every possible edge case for ticket classification.
B.Provide clear, concise system instructions that define the role and the goal of the task.
C.Always set the maximum token limit to 4096 to ensure the model has enough space to explain its reasoning.
D.Leverage tool use to enforce a specific schema for the ticket summary and priority.
E.Enable high temperature settings to ensure the model explores all possible priority levels.
AnswersB, D

System instructions are foundational for establishing the context and behavior of the model. Clear instructions help the model understand its role, leading to more consistent performance. By clearly defining the goal, you reduce the likelihood of the model wandering off-task or ignoring critical components of the requested output.

Why this answer

Combining clear, task-oriented system instructions with structured output formats provides the best results. The system prompt sets the boundary for behavior, while tool use or structured formatting ensures the output is predictable. Together, these two strategies minimize hallucinations and ensure that the extracted information can be easily mapped to backend database fields, which is vital for automated ticket routing and resolution workflows.

Exam trap

Candidates often rely solely on natural language instructions for formatting, failing to realize that tool use provides the programmatic enforcement necessary for reliable, machine-readable output in production systems.

37
MCQhard

Refer to the exhibit. Your API call is returning incomplete JSON because it hits a token limit. What is the most robust architectural fix for this error?

A.Increase the max_tokens limit to handle the full JSON response.
B.Rewrite the system prompt to force the model to be more concise and avoid truncation.
C.Decompose the data extraction into multiple, smaller requests to avoid hitting limits.
D.Use a post-processing script to append the missing closing brace.
AnswerC

Decomposition is the correct architectural approach. By breaking the task into parts, you ensure each request finishes within the token limit, yielding valid, fully-formed JSON for each chunk. This makes the system more resilient and avoids the structural failures caused by attempting to force large data in one turn.

Why this answer

Truncation at the token limit is a structural failure. Simply increasing the token limit is a temporary fix that can still fail with larger inputs. The robust solution is to architect the application to return smaller, modular pieces of data that the model can generate within the limits, or to use a streaming implementation that can handle multi-part responses, ensuring each piece is valid and complete.

Exam trap

Test-takers frequently select answers that suggest simply increasing the maximum output token limit, overlooking the architectural instability of generating massive monolithic responses.

38
MCQeasy

A developer wants Claude to summarize a long support thread and return the result as a JSON object with a single field "summary". They want to minimize the chance that Claude adds commentary outside the JSON. Which is the most direct Anthropic-recommended technique to apply?

A.Use the `stop_sequences` parameter set to '}' to end generation after the JSON object.
B.Set `temperature` to 0 and `top_p` to 1 to make the output more deterministic.
C.Add the phrase 'Return only JSON' to the end of the user message.
D.Prefill the assistant turn with `{"summary": "` so Claude continues directly with the summary text and closing quote.
AnswerD

Prefilling with `{"summary": "` forces Claude to continue from inside the JSON value, so it cannot add commentary before the object or wrap it in markdown. The model simply completes the string value and closes the brace. This is the most direct Anthropic technique for constraining output to a specific JSON shape and is ideal for a single-field object like this one.

Why this answer

Prefilling the assistant turn with `{"summary": "` constrains Claude to continue inside the JSON string value, so the response cannot contain commentary before the object or wrap it in markdown. Instructions, stop sequences, and sampling parameters do not structurally enforce the format. The prefill is the most direct Anthropic-recommended technique for this single-field JSON output.

Exam trap

The trap here is believing that a stop sequence on the closing brace will cleanly end the JSON, when it actually removes the brace and produces invalid JSON.

39
Multi-Selecthard

A platform team is building a Claude-powered service that returns structured records to a downstream database. During testing, roughly 4% of responses include a friendly sentence before the JSON, and another 3% omit a required field entirely. Which TWO changes most directly reduce these failure modes? (Choose two.)

Select 2 answers
A.Switch the output format from JSON to a comma-separated list to simplify parsing.
B.List every required field with its type and a short description, and instruct the model to include all fields even when a value is unknown.
C.Lower the temperature to 0 and rely on that alone to eliminate both the preamble and the missing fields.
D.Increase max_tokens substantially so the model has room to complete every field.
E.Add an explicit instruction that the response must begin with the opening brace and contain no preamble or trailing commentary.
AnswersB, E

Omitted fields usually stem from the model deciding a value is unavailable or unimportant. Enumerating each field with its type and a description, plus an explicit rule to emit every field and use a null or sentinel for unknowns, removes that judgment call. This directly addresses the 3% omission rate while keeping the schema stable for the database loader.

Why this answer

The two observed defects have distinct causes: conversational framing produces leading sentences, and unstated field requirements produce omissions. An instruction forbidding any text outside the JSON object fixes the first, while enumerating every field with its type and a rule for unknown values fixes the second. Token budget, temperature, and format changes do not target either root cause and would leave both failure rates essentially unchanged.

Exam trap

The trap here is treating both failures as one generic 'model quality' problem and reaching for a single global knob like temperature or max_tokens, when each defect has a separate, prompt-level cause that must be fixed independently.

40
MCQeasy

A support-engineering team is prototyping a Claude-powered assistant that must always reply in a consistent tone and never invent refund policies. They want a single, reusable instruction block that applies to every conversation regardless of the user's message. Where should this persistent behavioral guidance be placed in a Messages API request?

A.In an assistant turn that precedes the user's first message, so the model sees its own prior commitment to the rules.
B.In the metadata field of the request, which the model reads as context before generating a reply.
C.In the system prompt parameter, which is processed before the conversation turns and applies to the whole exchange.
D.In the first user message, prefixed with 'Always follow these rules:' before the actual customer question.
AnswerC

The system prompt is specifically designed to carry persistent role, tone, and policy instructions that apply across every turn of a conversation. Placing the refund-policy constraints there keeps them separate from user content, so the model treats them as standing rules rather than one-off requests. It also lets the team reuse the same block across sessions and endpoints without rewriting each user message.

Why this answer

The system prompt exists precisely to hold persistent, cross-turn instructions such as tone, persona, and business rules. Keeping refund-policy constraints there separates durable guidance from user content, prevents dilution as the conversation grows, and lets the same block be reused across sessions. Metadata and assistant prefills serve different purposes and cannot carry standing policy.

Exam trap

The trap here is treating metadata or an assistant prefill as a place for behavioral rules, when only the system prompt is designed to apply guidance across the whole exchange.

41
MCQeasy

A developer wants Claude to generate a list of items but stop immediately after the fifth item is completed to save on token costs. Which configuration change is most appropriate?

A.Reduce the temperature to 0.1.
B.Set a custom stop sequence.
C.Use a system prompt to ask for brevity.
D.Increase the top-k parameter value.
AnswerB

A stop sequence is a string that, if generated, causes the model to stop immediately. If the developer knows the model will output '6.' at the start of the sixth item, they can set '6.' as a stop sequence to ensure generation terminates after the fifth item.

Why this answer

Stop sequences allow the API to terminate generation as soon as a specific string is encountered. By defining a sequence that naturally follows the completion of the fifth item, developers can effectively control output length and costs without relying solely on the max_tokens parameter, which might truncate the response mid-sentence.

Exam trap

Candidates often attempt to use max_tokens to control the output length, which is unreliable as it truncates content arbitrarily rather than stopping at a logical completion point.

42
MCQhard

You are building an application that uses the Anthropic API to classify customer support tickets into exactly one of five categories: Billing, Technical, Account, Feature Request, or Other. You require the output to be a JSON object with a single field "category" and a value from that list. During testing, you notice that for ambiguous tickets the model sometimes returns a different key name, such as "ticket_category", or wraps the JSON in markdown code fences, causing parsing failures. You need to enforce the schema reliably while keeping latency and cost low. Which approach is most effective?

A.Add a system prompt instruction that explicitly states the exact JSON schema and warns the model not to include markdown formatting.
B.Set the temperature parameter to 0 and include a detailed example of the desired JSON output in the prompt.
C.Post-process the model's raw text response with a regular expression that extracts the first JSON object and remaps any key to "category".
D.Use the Anthropic API's tool use feature by defining a tool with an input schema that specifies the required "category" field and its allowed enum values, then force the model to call that tool.
AnswerD

Defining a tool with a strict input schema and forcing its use constrains the model's output to match the schema exactly, eliminating extraneous keys or markdown. The API validates the tool call against the schema, providing deterministic structure. This is the most reliable way to enforce a fixed JSON shape while remaining efficient.

Why this answer

Forcing the model to use a tool with a strict input schema ensures the output conforms exactly to the required JSON structure, including the key name and allowed enum values. Unlike prompt instructions or temperature adjustments, tool use provides a hard constraint enforced by the API, making it the most reliable and efficient method for schema adherence in production.

Exam trap

The trap here is assuming that a detailed system prompt or few-shot examples can guarantee JSON schema compliance, when only structured mechanisms like tool use provide enforceable constraints.

43
MCQeasy

Which prompting technique involves providing Claude with a few examples of the desired input-output pairs to improve performance on a specific task?

A.Zero-shot prompting.
B.Chain of Thought prompting.
C.Few-shot prompting.
D.Role prompting.
AnswerC

Few-shot prompting specifically refers to the practice of including a small number of examples in the prompt to demonstrate the desired behavior. This technique is highly effective for teaching Claude new formats or specific stylistic requirements that might be difficult to describe with instructions alone.

Why this answer

Few-shot prompting is a foundational technique used to guide the model by showing it exactly what is expected. By providing examples within the prompt, the developer can specify the tone, format, and logic required for the task, which is particularly useful for niche or highly structured requirements.

Exam trap

Candidates confuse few-shot prompting with fine-tuning or zero-shot evaluation, overlooking the direct inclusion of input-output examples within the prompt text.

44
MCQmedium

A financial analyst wants Claude to extract the total amount due from each invoice in a batch of 300 PDF-extracted text blobs, returning results as JSON with fields "invoice_id", "amount_due", and "currency". Some invoices list multiple line items and a subtotal, while others show only a single grand total. Which prompt design most reliably produces consistent, machine-parseable extraction across all invoices?

A.Ask Claude to 'summarize the key financial figures' and parse whatever numbers appear in the free-text response.
B.Provide a strict JSON schema with the three required fields, instruct Claude to output only valid JSON, and include two worked examples covering both single-total and multi-line-item invoices.
C.Ask Claude to return the entire invoice text unchanged so the analyst can manually locate the amount due in each document.
D.Set the temperature to 1.0 so Claude produces varied outputs, then use a fuzzy regex to catch any dollar amounts in the response.
AnswerB

Specifying the exact JSON schema fixes the output shape, the 'output only valid JSON' instruction suppresses prose wrappers, and the two few-shot examples teach Claude how to reconcile multi-line invoices to a single amount_due. Together these make the extraction deterministic enough for automated parsing across all 300 documents, including the two structural variants present in the batch.

Why this answer

Reliable batch extraction requires a fixed schema, an explicit instruction to emit only JSON, and few-shot examples that cover every structural variant in the input set. Combining a named-field schema with instruction and examples constrains the model's output shape so a parser can consume it without manual intervention. Free-text, high-temperature, or echo approaches all fail to yield consistent, machine-readable fields.

Exam trap

The trap here is assuming that asking for a summary of financial figures will naturally yield the amount due in a parseable form, when summaries vary in wording and often surface subtotals instead of the grand total.

45
MCQhard

You maintain a production pipeline where Claude extracts line items from scanned invoices and must return them as strict JSON conforming to a supplied schema. Intermittent outputs include a short apology sentence before the JSON object, which breaks your downstream parser. Logs show the preamble appears only when the OCR text contains contradictory totals. Which change most reliably eliminates the preamble while preserving extraction quality?

A.Increase the max_tokens value so the model has room to emit the apology and the full JSON without truncation.
B.Wrap the OCR text in <invoice> tags and instruct the model to read them carefully before answering.
C.Lower the temperature to 0 so the sampling becomes deterministic and the apology sentence disappears.
D.Add a prefilled assistant turn containing the opening brace '{' so the model must continue directly from that character.
AnswerD

Prefilling the assistant turn with the opening brace constrains generation to continue from that exact character, so the model cannot emit an apology sentence before the JSON. This works because the completion is a continuation of the provided prefix, which is precisely the failure mode observed: the model wants to comment on contradictory totals before producing the object.

Why this answer

The failure is a prefix problem: the model decides to narrate before emitting the object. Constraining the assistant turn to begin with the opening brace forces the very first generated token to be part of the JSON structure, so no preamble can precede it. This preserves extraction quality because the model still reasons internally about contradictory totals while writing fields.

Exam trap

The trap here is assuming that lowering temperature or adding XML tags controls what the model says first, when only constraining the completion prefix directly prevents a conversational preamble.

46
Multi-Selecthard

A developer is building a structured output pipeline where Claude must return a list of support tickets, each with 'id', 'priority', and 'category'. The pipeline must be robust against malformed responses. Which TWO practices most directly improve the reliability of this structured output? (Choose two.)

Select 2 answers
A.Set 'temperature' to 1.0 to encourage diverse ticket categorizations.
B.Ask Claude to 'be careful' and 'double-check' the output before responding.
C.Append a stop sequence of '}' to end the response as soon as the JSON closes.
D.Validate the parsed output against the schema in application code and retry with a corrective prompt on failure.
E.Define a tool with an 'input_schema' that specifies the ticket array and required fields, and force tool use.
AnswersD, E

Even with schema-enforced tool use, edge cases can produce values that fail business validation, such as an unknown priority. Parsing the tool call input and validating it against the schema in code, then retrying with a corrective message that includes the error, catches these cases and recovers automatically. This defensive layer makes the pipeline robust against residual malformed responses.

Why this answer

Reliability comes from structural enforcement plus defensive validation. Defining a tool 'input_schema' with required ticket fields and forcing tool use guarantees a structured tool call, while validating the parsed result in application code and retrying with corrective feedback handles residual edge cases. Together they make the pipeline robust against malformed or invalid responses.

Exam trap

The trap here is relying on soft instructions or stop sequences for structure, when only schema-enforced tool use and application-side validation provide real reliability.

47
MCQeasy

A developer is prompting Claude to classify 5,000 customer support tickets into one of six fixed categories. The first 200 classifications look correct, but the developer notices that category labels come back with inconsistent capitalization and occasional trailing punctuation. What is the simplest change that makes the labels uniform and directly usable as database keys?

A.Add a post-processing step that lowercases and strips punctuation from each label before insertion.
B.Provide the six allowed labels in a fixed, lowercase form and instruct Claude to return exactly one of those labels with no other characters.
C.Raise the temperature so Claude explores more label phrasings and picks the most natural one.
D.Ask Claude to explain its reasoning for each ticket and include the category somewhere in the explanation.
AnswerB

Supplying the allowed labels verbatim in their canonical form and constraining the output to one of them removes the model's freedom to re-case or punctuate. This is the minimal, direct fix: the label set is enumerated and the output is restricted to that set, so every returned string matches a known database key without post-processing.

Why this answer

Label uniformity is achieved by enumerating the allowed values in their canonical form and restricting the output to exactly one of them. This closes off the model's latitude to change case or append punctuation, so returned strings match database keys directly. Downstream normalization, higher temperature, and reasoning text all either mask the problem or make the output harder to consume reliably.

Exam trap

The trap here is reaching for a downstream cleanup script instead of constraining the model at the prompt, which leaves the model free to produce label variants that can collide or mismap after normalization.

48
Multi-Selectmedium

You are designing a prompt that asks Claude to review a pull request and return findings in a strict XML structure with a severity attribute for each finding. Your parser depends on the structure being consistent. Which TWO techniques most directly improve the consistency of the XML output? (Choose two.)

Select 2 answers
A.Ask the model to return the findings as a Markdown bulleted list for readability.
B.Set the temperature to a high value so the model explores different XML layouts.
C.Instruct the model to think step by step before producing the XML.
D.Describe the required tags and attributes precisely in the instructions, specifying allowed severity values.
E.Provide a short example of the exact XML structure expected, including the severity attribute.
AnswersD, E

Explicit, precise instructions define the contract the model must follow. In this scenario, naming the tags and enumerating allowed severity values removes ambiguity about what to emit. Clear specifications complement examples and reduce structural drift. This is a direct lever for making the XML consistent enough for a parser.

Why this answer

Consistency in structured output comes from removing ambiguity. A concrete example shows the exact shape, and precise instructions define tags and allowed attribute values. Together they constrain the model to a stable format.

Step-by-step reasoning, high temperature, and Markdown lists either do not enforce structure or actively introduce variation, so they do not meet the parser's needs in this scenario.

Exam trap

The trap here is assuming that improving the model's reasoning or readability will also improve structural consistency, when only explicit format specification and examples constrain the XML shape.

49
MCQeasy

To reduce the risk of Claude hallucinating information when it doesn't know the answer, what instruction should be added to the prompt?

A.Tell the model to 'Be as creative as possible'.
B.Instruct the model to 'Always provide an answer'.
C.Tell the model to say 'I don't know' if unsure.
D.Set the max_tokens to a very high number.
AnswerC

This simple instruction sets a clear behavioral boundary. It gives the model permission to be honest about its limitations, which significantly increases the reliability of the system by ensuring that the model only provides information it can actually verify from the provided source or training.

Why this answer

Explicitly giving the model an 'out' is a highly effective way to prevent hallucinations. By instructing Claude to say 'I don't know' or 'Information not found' when it is uncertain, you steer the model away from its natural tendency to be helpful by generating plausible but incorrect answers.

Exam trap

Candidates tend to choose generic system instructions like 'always tell the truth' instead of specifically instructing the model to output a precise fallback phrase like 'I don't know' when uncertain.

50
Multi-Selecthard

Which THREE strategies are effective for reducing hallucinations in RAG (Retrieval-Augmented Generation) systems?

Select 3 answers
A.Instruct the model to say 'I don't know' if the context does not contain the answer.
B.Force the model to cite the specific document chunk used for each sentence.
C.Increase the temperature to 1.5 to allow for more creative exploration.
D.Use a complex system prompt that describes the model as an 'Omniscient Expert'.
E.Ask the model to verify its own answer against the context provided.
AnswersA, B, E

Explicitly instructing the model to admit ignorance prevents it from filling gaps with hallucinated information. This is a critical guardrail for RAG systems, ensuring that accuracy is prioritized over completing the task, which helps maintain user trust and factual integrity in enterprise-grade information retrieval applications.

Why this answer

To reduce hallucinations in RAG, you must constrain the model to the provided context, encourage it to admit ignorance if the answer is missing, and verify its reasoning. These techniques transform the model from a creative writer into a grounded processor of provided facts. Architects must build these guardrails into the prompt to ensure the output is factually tethered to the retrieved source material, which is critical for trustworthy systems.

Exam trap

Test-takers often assume that simply retrieving documents via RAG is enough, forgetting that models still tend to extrapolate beyond provided context.

51
MCQeasy

You are using the Anthropic Claude API in a customer-support application. Your prompt asks Claude to classify each incoming ticket into exactly one of four categories and return the result. Occasionally, Claude adds a friendly sentence before the category, which breaks your parser. Which change most directly prevents this extra text?

A.Increase the max_tokens value so the model has room to output the category.
B.Set the temperature parameter to 0.0 in the API request.
C.Add a system prompt that says 'You are a helpful assistant for a support team.'
D.Add a prefill to the assistant turn, such as an opening XML tag, so the response continues from that point.
AnswerD

Prefilling the assistant turn with an opening tag or a fixed prefix forces the model to continue from that exact point, which suppresses conversational preamble. In this scenario, starting the assistant message with the tag that should wrap the category prevents any friendly sentence from appearing first. This is a direct, reliable way to control the beginning of the output.

Why this answer

Prefilling the assistant turn is the most direct control over the start of the response. By beginning the assistant message with the exact tag or token that should open the answer, the model is forced to continue from there, eliminating any preamble. Temperature and max_tokens affect randomness and length, not format, and a friendly system persona does not enforce structure.

Exam trap

The trap here is assuming that lowering temperature or adding a strict system prompt will guarantee a clean output format, when only controlling the assistant turn directly prevents leading text.

52
MCQhard

An engineering team is building a Claude-powered contract analyzer that must return a JSON object with a 'parties' array, an 'effective_date' string, and a 'governing_law' string. Legal reviewers report that for about one in twenty contracts, the model invents a governing law when the contract is silent. The team wants to stop fabricated values without losing valid extractions. Which approach best addresses this?

A.Increase the model's temperature so it considers more possible governing laws and picks the most probable one.
B.Ask Claude to search its training knowledge for the governing law typically used in the contract's jurisdiction and fill that in.
C.Instruct Claude to set 'governing_law' to null when the contract does not state one, and include a few-shot example of a silent contract returning null.
D.Add a rule that any contract without a governing law clause should be rejected and returned to the legal team for manual review.
AnswerC

Fabrication occurs because the schema implies a value is always expected, so the model fills the gap. Explicitly permitting null for absent fields, plus an example showing a silent contract yielding null, gives the model a legitimate way to represent missing data and teaches it when to use that path. This preserves valid extractions while eliminating invented governing laws.

Why this answer

Fabricated values appear when the requested schema implies every field must be populated and the model has no sanctioned way to report absence. Explicitly allowing null for missing fields, paired with a few-shot example of a silent contract, gives the model a correct representation for gaps. Rejecting documents, raising temperature, or inferring from jurisdiction knowledge all either discard good data or amplify invention instead of eliminating it.

Exam trap

The trap here is assuming the model will stay silent when a field is absent, when a schema that names the field effectively pressures it to produce a plausible value rather than admit the document is silent.

53
MCQmedium

A team uses Claude to generate release notes from git commit messages. The output must be a JSON array of objects with 'title' and 'summary' fields. The model sometimes wraps the JSON in markdown fences or adds a conversational preamble. Which approach most reliably yields parseable JSON?

A.Set 'max_tokens' to a small value so the model cannot add extra text around the JSON.
B.Use a system prompt that says 'Do not use markdown' and rely on Claude to follow it.
C.Instruct Claude to respond only with JSON and include a prefilled assistant message starting with '{'.
D.Define a tool with an 'input_schema' describing the array of release note objects and set 'tool_choice' to that tool.
AnswerD

A tool definition with an 'input_schema' that models the array of objects, combined with forcing that tool through 'tool_choice', makes Claude emit a 'tool_use' block whose 'input' is validated against the schema. This eliminates markdown fences and preamble because the output is a structured tool call, not free-form text. The application can then read the JSON arguments directly without cleanup.

Why this answer

Forcing a tool call whose 'input_schema' describes the release note array makes the model's output a structured tool_use block that must conform to the schema. This removes markdown fences and conversational text because the response is not free-form. Downstream code can consume the tool call arguments as JSON directly, giving deterministic parsing.

Exam trap

The trap here is believing that a JSON-only instruction or a '{' prefill guarantees valid JSON, when only schema-enforced tool use removes fences and preamble structurally.

54
MCQmedium

When prompting Claude to process a large document and perform multiple tasks like summarization and sentiment analysis, what is the recommended way to separate the source text from the instructions?

A.Using Markdown headers like #Source and #Task.
B.Enclosing the source text in XML tags like <document>.
C.Separating sections with several empty newline characters.
D.Indenting the source text by four spaces.
AnswerB

Anthropic models are highly optimized to parse and respect XML tags as delimiters. Using tags like <document> and <instructions> creates a clear hierarchy, allowing Claude to distinguish between the data it must process and the commands it must follow, which significantly improves overall task accuracy.

Why this answer

Using XML tags is a core best practice for Claude as it provides clear structural boundaries that the model is specifically trained to recognize. This prevents instruction leakage, where the model might confuse the content of the source document with the prompt instructions, ensuring that the output remains focused on the requested tasks.

Exam trap

Candidates frequently rely on markdown headers or blank lines to separate text, missing the structural delimiters that the model is specifically trained to parse reliably.

55
MCQhard

You are building a system that must extract entities from messy transcripts. The model often misses entities at the end of the text. What is the most likely cause and architectural fix?

A.The context window is too small; increase it by reducing the prompt complexity.
B.Place the instructions before the transcript and repeat them after the transcript.
C.Switch to a smaller model to increase processing speed and focus.
D.Set the top_p parameter to 0.0 to force deterministic entity extraction.
AnswerB

Reinforcing instructions at the end of a long context window is a proven technique to counter degradation. By providing the instruction again after the transcript, you anchor the model's focus, ensuring it processes the final elements of the input with the same level of care as the start.

Why this answer

The model is likely experiencing 'recency bias' or 'middle-of-the-prompt' degradation, where focus shifts away from the end. By moving instructions to the end of the prompt or using 'sandwich prompting'—placing key instructions at both the start and end—you reinforce the task. This architectural adjustment ensures the model maintains focus on the entire context window, which is vital for long-context entity extraction tasks in production environments.

Exam trap

Candidates often suggest increasing the model's temperature or changing the model version, failing to identify that the issue is a structural 'recency bias' inherent in long-context processing.

56
MCQhard

A team is using the Anthropic Messages API to extract line items from vendor invoices. They define a tool named `record_line_items` with an input_schema that requires `description`, `quantity`, and `unit_price`. In production, Claude sometimes returns a text message describing the items instead of calling the tool, especially on invoices with unusual layouts. They want to guarantee a tool call every time. Which change is most effective?

A.Add few-shot examples showing Claude calling `record_line_items` for several invoice layouts.
B.Add a system prompt line instructing Claude to always call `record_line_items` and never respond with text.
C.Set `tool_choice` to `{"type": "any"}` so Claude can pick whichever tool it prefers.
D.Set `tool_choice` to `{"type": "tool", "name": "record_line_items"}` so the model must call that specific tool.
AnswerD

Setting tool_choice to a specific tool forces Claude to invoke `record_line_items` on every request, eliminating the fallback to a plain text response. This is the documented Anthropic way to require a particular tool call, and it directly addresses the scenario where the model sometimes describes items instead of calling the tool. It is the only option that structurally guarantees the desired behaviour.

Why this answer

Anthropic's Messages API supports `tool_choice` with a named tool, which forces Claude to call that tool on every turn. This is the only mechanism that structurally guarantees the desired tool call rather than merely biasing the model toward it. Instructions, examples, and `tool_choice: any` all leave room for the model to respond with text or a different tool, so they cannot satisfy the 'every time' requirement.

Exam trap

The trap here is treating prompt instructions and few-shot examples as equivalent to API-level enforcement, when only a named `tool_choice` guarantees the tool call.

57
MCQmedium

In the context of structured output, what is the primary benefit of 'prefilling' the assistant's response in the API call?

A.It reduces the latency of the first token.
B.It allows the model to bypass the system prompt.
C.It steers the model toward a specific output format.
D.It encrypts the output for better security.
AnswerC

By starting the assistant's turn with a character like '{' or a specific XML tag, you're giving the model a 'nudge' that it must continue in that format. This effectively prevents the model from adding unwanted conversational preambles and ensures the output is immediately parseable.

Why this answer

Prefilling allows the developer to start the model's response with a specific string, which guides the model's subsequent output. This is particularly useful for ensuring that the model follows a specific format, such as JSON or XML, by providing the opening characters of that format and eliminating introductory text.

Exam trap

Candidates think prefilling modifies the system prompt or changes underlying model weights, rather than simply priming the assistant role's starting text.

Ready to test yourself?

Try a timed practice session using only Prompt Engineering and Structured Output questions.