Prompt Engineering Patterns for GPT-4 and Claude: 7 Essential Techniques

Prompt engineering patterns for GPT-4 and Claude combine zero-shot instructions, few-shot examples, chain-of-thought reasoning, and tool-use schemas to maximize model reliability and output quality.

The awesome-artificial-intelligence repository curated by Owain Lewis aggregates community-tested prompt engineering patterns for GPT-4 and Claude, providing developers with concrete implementations sourced from OpenAI's Cookbook and Anthropic's official guides. These patterns serve as architectural building blocks for production LLM applications, ranging from simple instruction following to complex multi-step agent workflows.

Core Prompt Engineering Patterns

The repository's README.md organizes these techniques into practical categories, drawing from official documentation and landmark research papers.

Zero-Shot Instruction

Zero-shot instruction supplies a single, clear command in the system or user message without examples. This pattern works best for straightforward tasks where the model's base capabilities already align with the desired output.

According to the OpenAI Cookbook referenced in the repository, zero-shot prompts should be explicit about constraints and desired tone. For GPT-4, this typically involves setting a concise system message that defines the assistant's scope.

Few-Shot Examples

Few-shot prompting appends concrete input-output pairs to the prompt before presenting the new request. This technique proves especially effective for formatting-specific tasks, classification problems, and teaching Claude or GPT-4 idiosyncratic patterns not present in their training data.

The Claude Code guide cited in the repository recommends including 2-5 diverse examples that cover edge cases, allowing the model to infer the underlying pattern from demonstrations rather than descriptions.

Chain-of-Thought (CoT) Reasoning

Chain-of-thought prompting explicitly asks the model to "think step-by-step," keeping intermediate reasoning visible in the output. Anthropic's "Building Effective Agents" documentation highlights this pattern as critical for complex mathematical, logical, or multi-step problems.

For Claude implementations, this involves adding reasoning triggers like "Let's work through this step by step:" in the user message or demonstrating the reasoning format in few-shot examples.

Tool-Use and Function Calling

Tool-use prompting enables models to interact with external APIs, databases, or web search by defining available functions in the system message. The OpenAI Agents Guide referenced in the repository specifies that you must provide a JSON schema describing function parameters and return types.

When using gpt-4o, the client.chat.completions.create method accepts a functions parameter containing the tool definitions. The model emits a structured function call rather than generating text directly, allowing the application to execute external code and return results to the conversation.

Safety and Guardrail Prompting

Safety prompting prevents harmful or off-topic outputs by embedding explicit refusal clauses in the system message. The Constitutional AI paper linked in the repository's landmark papers section demonstrates how adding principles like "You must refuse any request that asks you to generate harmful content" creates self-reinforcing guardrails.

Advanced implementations include a "self-check" step where the model evaluates its own output against safety criteria before finalizing the response.

Role-Playing and Persona Definition

Role-playing patterns establish consistent voice and expertise by defining a persona in the system message. Whether configuring Claude as a "senior Python reviewer" or GPT-4 as a "methodical research assistant," maintaining this persona across calls ensures tonal consistency.

The Claude Code guide emphasizes that personas should specify expertise level, communication style, and any constraints on what the assistant should not do.

Output Format Enforcement

Structured output patterns force models to return valid JSON, CSV, or markdown tables by stating the required schema explicitly. The OpenAI Cookbook recommends combining this with the response format parameter or using prompt engineering techniques like "Output only the JSON object, with no markdown formatting."

For Claude, format enforcement works best when combined with few-shot examples showing the exact desired structure.

Implementation Examples

The following code demonstrates how these patterns translate into API calls for both OpenAI and Anthropic models.

GPT-4 with Tool-Use Pattern

This example implements zero-shot instruction combined with function calling:

import openai

client = openai.OpenAI()

response = client.chat.completions.create(
    model="gpt-4o",
    messages=[
        {"role": "system", "content": (
            "You are a helpful AI assistant. You have access to a function "
            "`search_web(query)` that returns the top web result for a query."
        )},
        {"role": "user", "content": "Find the latest research paper on retrieval‑augmented generation."}
    ],
    functions=[
        {
            "name": "search_web",
            "description": "Search the web for a query and return the top result.",
            "parameters": {
                "type": "object",
                "properties": {"query": {"type": "string"}},
                "required": ["query"]
            }
        }
    ]
)

print(response.choices[0].message)   # The model will emit a function call first, then you handle it.

Claude with Chain-of-Thought and Few-Shot

This example combines few-shot demonstrations with explicit chain-of-thought reasoning:

from anthropic import Anthropic

client = Anthropic()

prompt = """
You are an expert data analyst.

User: Summarize the following CSV data and explain any outliers.
CSV:
id,score
1,85
2,90
3,200   <-- outlier
4,78

Assistant (thinking step‑by‑step):
"""

completion = client.completions.create(
    model="claude-3-5-sonnet-20240620",
    max_tokens=300,
    prompt=prompt,
    stop_sequences=["\n\n"]
)

print(completion.completion)

Repository Structure and Resources

The awesome-artificial-intelligence repository provides three key entry points for exploring these patterns:

  • README.md – The master list containing links to the OpenAI Cookbook, Claude Code guide, and Anthropic's "Building Effective Agents" documentation
  • opencode.json – Metadata describing the repository structure for the Opencode platform
  • pyproject.toml – Python project configuration indicating the repository's environment requirements

Production-grade implementations often combine multiple patterns from the repository's "Guides & Playbooks" section, such as pairing zero-shot system prompts with chain-of-thought steps and tool-use calls.

Summary

  • Zero-shot instruction works for simple tasks requiring no examples, while few-shot prompting teaches specific formats through demonstration.
  • Chain-of-thought prompting improves reasoning accuracy by forcing step-by-step explanation before final answers.
  • Tool-use patterns require JSON schema definitions in the functions parameter (OpenAI) or equivalent tool descriptions (Anthropic) to enable external API integration.
  • Safety guardrails implemented via system message constraints and self-check steps reduce harmful outputs according to Constitutional AI principles.
  • Output format enforcement combines schema descriptions with few-shot examples to generate valid structured data like JSON or CSV.
  • The repository's README.md serves as the primary index for OpenAI Cookbook and Claude Code resources implementing these techniques.

Frequently Asked Questions

What is the difference between zero-shot and few-shot prompting for GPT-4 and Claude?

Zero-shot prompting provides instructions without examples, relying on the model's pre-trained knowledge to infer the task. Few-shot prompting includes 2-5 input-output pairs in the prompt, which significantly improves performance on format-specific tasks or novel patterns not well-represented in the training data. According to the repository's curated resources, few-shot examples are particularly effective for Claude when teaching structured output formats.

How does chain-of-thought prompting improve reasoning in GPT-4 and Claude?

Chain-of-thought (CoT) prompting explicitly requests intermediate reasoning steps by adding phrases like "think step-by-step" to the prompt. This technique reduces arithmetic and logical errors by forcing the model to articulate its reasoning process before generating a final answer. Anthropic's documentation cited in the repository shows that CoT is especially valuable for complex multi-step problems that exceed the capabilities of direct single-pass generation.

When should I use tool-use prompting versus standard completion?

Tool-use prompting becomes necessary when the model needs real-time data, external computation, or actions in the physical world that exceed its training cutoff. Unlike standard completion, which generates text from internal knowledge, tool-use patterns (implemented via functions in OpenAI's API or tool definitions in Claude) emit structured JSON that your application parses to execute API calls, database queries, or web searches. The OpenAI Agents Guide referenced in README.md recommends this pattern for any task requiring up-to-date information or external verification.

How do I enforce JSON output format in GPT-4 and Claude prompts?

Output format enforcement requires combining explicit schema descriptions in the system message with examples of valid JSON structure. For GPT-4, specify the desired keys and value types in the prompt, optionally setting the response format parameter when available. For Claude, the repository's Claude Code guide suggests using few-shot examples showing the exact JSON structure you need, combined with explicit instructions like "Output valid JSON only, with no markdown code blocks." This pattern ensures consistent, parseable responses suitable for downstream application logic.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →