◉CLAUDE LABJP
●SONNET 4.5 — Sonnet 4.5 was retired from the Claude API on 11/30. Calls now return an error. Move to Sonnet 5.5●PROJECTS — The Enterprise Analytics API now reports daily usage for the new projects experience (beta)●OPUS 4.5 — claude-opus-4-5 retires on 2027/1/22, 52 days from now. The replacement is claude-opus-5-5●LANGUAGE — Some users say Claude switches to another language mid-session while they write in English●NEW — New: Weekly usage looks like it jumped right after a plan upgrade? Check this first●COWORK — Handing Cowork a folder for the first time? Start with a task that only reads files●SONNET 4.5 — Sonnet 4.5 was retired from the Claude API on 11/30. Calls now return an error. Move to Sonnet 5.5●PROJECTS — The Enterprise Analytics API now reports daily usage for the new projects experience (beta)●OPUS 4.5 — claude-opus-4-5 retires on 2027/1/22, 52 days from now. The replacement is claude-opus-5-5●LANGUAGE — Some users say Claude switches to another language mid-session while they write in English●NEW — New: Weekly usage looks like it jumped right after a plan upgrade? Check this first●COWORK — Handing Cowork a folder for the first time? Start with a task that only reads files
Articles/API & SDK
⬡ API & SDK/2026-04-06Intermediate

Generating 300K Token Long-Form Content with Claude API — The output-300k Beta Feature Explained

Learn how to use the output-300k-2026-03-24 beta header in Claude API to generate up to 300,000 tokens of content in a single request. Covers setup, supported models, streaming, cost calculation, and Python/TypeScript code examples.

Claude API150output-300klong-form generationbeta featurePython33Anthropic13

Anthropic has quietly rolled out a powerful beta feature for the Claude API: the ability to generate up to 300,000 tokens — roughly 225,000 words — in a single request. Activate it with the output-300k-2026-03-24 beta header, and you unlock a new level of long-form content generation with Claude Opus 4.6 and Claude Sonnet 4.6.

Whether you need to generate a complete codebase, produce a book-length technical document, or output exhaustive analysis reports without splitting your work across multiple requests — this guide covers everything you need to get started.

What Is the output-300k Beta Feature?

Previously, the Claude API capped single-request output at 128,000 tokens. In April 2026, Anthropic raised this ceiling to 300,000 tokens via a beta flag available on the standard (non-batch) Messages API.

This is distinct from the Messages Batches API, which also supports 300K output tokens but is designed for asynchronous, bulk processing. For more on that approach, check out the Claude Message Batches API 300K Output Tokens Guide.

Comparing the Two Approaches

The regular Messages API with the output-300k header is designed for synchronous, real-time generation — ideal when you want a single large output delivered immediately, with optional streaming. The Batches API, by contrast, is optimized for processing many requests offline at up to 50% lower cost.

Supported Models and Requirements

The output-300k-2026-03-24 beta is available for these models only:

  • claude-opus-4-6-20260401
  • claude-sonnet-4-6-20250514

Claude Haiku 4.5 and older models are not supported. Since this is still a beta feature, Anthropic may adjust its specifications. For up-to-date pricing and limits, see the Claude API Pricing Guide 2026.

How to Enable the Beta Header

Enabling the feature is straightforward — just pass output-300k-2026-03-24 in the betas parameter of your request.

Python SDK Example

import anthropic
 
client = anthropic.Anthropic(api_key="YOUR_API_KEY")
 
message = client.messages.create(
    model="claude-sonnet-4-6-20250514",
    max_tokens=300000,  # Up to 300,000 tokens
    messages=[
        {
            "role": "user",
            "content": "Write a comprehensive Python async programming reference covering asyncio, aiohttp, Trio, concurrency patterns, and testing strategies."
        }
    ],
    betas=["output-300k-2026-03-24"]  # Enable the beta
)
 
print(message.content[0].text)
print(f"Output tokens used: {message.usage.output_tokens}")

Note: The betas parameter accepts a list of beta identifiers. Set max_tokens up to 300,000.

TypeScript / Node.js Example

import Anthropic from "@anthropic-ai/sdk";
 
const client = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });
 
async function generateLongContent(prompt: string): Promise<string> {
  const message = await client.beta.messages.create({
    model: "claude-sonnet-4-6-20250514",
    max_tokens: 300000,
    messages: [
      {
        role: "user",
        content: prompt
      }
    ],
    betas: ["output-300k-2026-03-24"]
  });
 
  const textContent = message.content.find((c) => c.type === "text");
  return textContent?.text ?? "";
}
 
const content = await generateLongContent(
  "Generate detailed architecture documentation for a scalable e-commerce platform built with Next.js and PostgreSQL."
);
console.log(`Content length: ${content.length} characters`);

Using Streaming for Large Outputs

For a 300K token response, generation can take several minutes. Streaming is highly recommended — it lets users see content as it arrives rather than waiting for the entire response.

import anthropic
 
client = anthropic.Anthropic(api_key="YOUR_API_KEY")
 
# Streaming with the output-300k beta
with client.beta.messages.stream(
    model="claude-sonnet-4-6-20250514",
    max_tokens=200000,
    messages=[
        {
            "role": "user",
            "content": "Write the complete source code for a RESTful e-commerce backend API using FastAPI and PostgreSQL. Include full implementations of product catalog, shopping cart, order management, and user authentication endpoints."
        }
    ],
    betas=["output-300k-2026-03-24"]
) as stream:
    for text in stream.text_stream:
        print(text, end="", flush=True)
 
final_message = stream.get_final_message()
print(f"\n\nOutput tokens: {final_message.usage.output_tokens}")
# Expected output: Output tokens: 148523

Practical Use Cases

Generating Complete Codebases

Instead of generating a project piece by piece, you can ask Claude to produce an entire application's scaffold — controllers, models, tests, configuration files — in one shot. This eliminates inconsistencies that often arise when stitching together multiple partial outputs.

Large Technical Documents

API references, architecture design docs, and internal playbooks can easily exceed 50,000 words. With the output-300k feature, you can generate these in a single, coherent pass rather than breaking the document into sections that you later need to merge.

Detailed Reports and Analysis

Data analysis summaries, research reports, and market analyses that require both depth and breadth benefit from this feature. The model can maintain consistent terminology and structure throughout a much longer output window.

Comprehensive Test Suites

Generating 100+ test cases in one request is now practical. You can include setup/teardown logic, edge cases, and integration tests all in a single generation pass.

Understanding the Cost

Here is a cost estimate for generating 300K tokens with Claude Sonnet 4.6:

  • Output token price for Claude Sonnet 4.6: $3 per 1 million tokens
  • Cost for 300,000 output tokens: approximately $0.90

Input token costs are additional but typically small for a single-turn prompt. Keep in mind that if you set max_tokens much higher than your expected output, you are only charged for tokens actually generated — not for the ceiling you set.

Looking back

The output-300k-2026-03-24 beta feature in Claude API is a practical upgrade for developers who routinely need large, coherent outputs in a single request.

  • How to enable: Add betas=["output-300k-2026-03-24"] and set max_tokens up to 300,000
  • Supported models: Claude Opus 4.6 and Claude Sonnet 4.6 only
  • Best for: Full codebases, long documents, detailed reports, large test suites
  • Cost: Standard token pricing — no extra fees for the beta

Pair it with streaming to deliver content progressively, and you have a reliable foundation for generating large-scale content with minimal friction.

Best Practices for Long-Output Requests

Working with outputs this large requires a slightly different mindset than typical API calls. Here are a few patterns that work well in practice.

Design Your Prompt for Completeness

Claude may not naturally know how long the output should be unless you tell it explicitly. Include length cues in your prompt — phrases like "provide full implementations," "include all edge cases," or "write the complete module with no placeholders" help the model understand that a thorough response is expected.

Use a Structured Output Format

When generating large amounts of content, a predictable structure makes downstream parsing much easier. For code generation, specifying the exact file structure you want — along with delimiters or filename comments — ensures the output is actionable.

prompt = """
Generate a complete FastAPI application with the following structure.
Separate each file with a comment like: # FILE: path/to/file.py
 
Files to generate:
- main.py (app entry point)
- routers/users.py (user endpoints)
- routers/products.py (product endpoints)
- models/user.py (SQLAlchemy user model)
- models/product.py (SQLAlchemy product model)
- schemas/user.py (Pydantic schemas)
- schemas/product.py (Pydantic schemas)
- core/database.py (database connection)
- core/security.py (JWT authentication)
- tests/test_users.py (pytest user tests)
- tests/test_products.py (pytest product tests)
 
Use async SQLAlchemy, Alembic migrations, and include full error handling.
"""

Save Incrementally When Streaming

For very long outputs, consider writing to disk as the stream arrives rather than accumulating everything in memory. This protects against connection drops mid-generation and keeps memory usage manageable.

import anthropic
 
client = anthropic.Anthropic(api_key="YOUR_API_KEY")
 
output_file = "generated_output.md"
 
with open(output_file, "w", encoding="utf-8") as f:
    with client.beta.messages.stream(
        model="claude-sonnet-4-6-20250514",
        max_tokens=250000,
        messages=[{"role": "user", "content": "Write a comprehensive DevOps handbook..."}],
        betas=["output-300k-2026-03-24"]
    ) as stream:
        for text in stream.text_stream:
            f.write(text)
            f.flush()  # Write to disk after each chunk
 
print(f"Output saved to {output_file}")

Retry on Truncated Output

If you receive a response with stop_reason == "max_tokens", the model ran out of room before finishing. You can detect and handle this automatically:

response = client.messages.create(
    model="claude-sonnet-4-6-20250514",
    max_tokens=300000,
    messages=[{"role": "user", "content": prompt}],
    betas=["output-300k-2026-03-24"]
)
 
if response.stop_reason == "max_tokens":
    # Output was truncated — request a continuation
    continuation = client.messages.create(
        model="claude-sonnet-4-6-20250514",
        max_tokens=100000,
        messages=[
            {"role": "user", "content": prompt},
            {"role": "assistant", "content": response.content[0].text},
            {"role": "user", "content": "Please continue from where you left off."}
        ],
        betas=["output-300k-2026-03-24"]
    )
    full_output = response.content[0].text + continuation.content[0].text
else:
    full_output = response.content[0].text

When to Use output-300k vs. Other Approaches

The new beta is powerful but is not always the right tool. Here is a quick decision guide:

For generating a single large, coherent artifact (a complete codebase, a comprehensive report, a full novel chapter) where internal consistency matters, the output-300k single-turn approach is the strongest choice. The model has full awareness of everything it has written so far, which keeps the output consistent throughout.

For generating many medium-sized outputs (say, product descriptions for 500 SKUs), the Messages Batches API is more economical and processes the work in parallel.

For iterative, collaborative writing where you want to review and guide the content section by section, a multi-turn conversation with standard token limits is often more controllable than a single massive output.

Understanding these tradeoffs helps you get the most value out of each Claude API capability.

Share

Thank You for Reading

Claude Lab is ad-free, supported entirely by members like you. We publish practical guides daily with implementation code, benchmarks, and production-ready patterns. If you've found it useful, we'd love to have you on board.

  • ✦Copy-paste ready implementation code
  • ✦New advanced guides published daily
  • ✦$5/mo or $10 for lifetime access
View Membership →

If you found this article helpful, a small tip ($1.50) would mean a lot to us. Your support helps keep this site ad-free and covers server and hosting costs.

Related Articles

⬡ API & SDK2026-04-18
Building a Real-Time AI Processing Pipeline with Claude API and Apache Kafka
Learn how to integrate Claude API into Apache Kafka event streams with production-grade patterns. Implement smart buffering, model routing, and Dead Letter Queues to run large-scale real-time AI analysis at low cost.
⬡ API & SDK2026-11-30
The unit price drops 20%, yet the bill may rise: estimating the Opus 4.5 to 5.5 switch before January 22
claude-opus-4-5-20251101 retires on January 22, 2027, and the official replacement is claude-opus-5-5. Prices fall by a fifth, but the tokenizer changes and thinking can no longer be turned off. You will be able to count the cost per 1,000 of your own requests and pick a replacement and an effort level.
⬡ API & SDK2026-11-25
After Sonnet 4.5 Retired: Checking the Three Things That Change Without an Error, Even When the Old Model No Longer Answers
claude-sonnet-4-5 retired from the Claude API on November 30, 2026, and calls now return a 404. Switching to claude-sonnet-5-5 raises no 400, yet thinking runs by default, max_tokens covers more than the answer, and stop_reason shifts. Three ways to fill the 'before' column after retirement (old logs, Bedrock, thinking on vs. off), a troubleshooting table, and how to get ahead of the Opus 4.5 deadline.