CLAUDE LABJP
FORK — Claude Code 2.1.212 changes what /fork does: it copies your conversation into a new background session with its own row in claude agents, so you can keep working. The old in-session subagent is now /subtaskLIMITS — WebSearch calls are now capped at 200 per session by default, and subagent spawns get the same 200 ceiling, so a runaway search or delegation loop stops on its ownMCPBG — MCP tool calls running past two minutes now move to the background automatically, keeping the session usable. Tune the threshold with CLAUDE_CODE_MCP_AUTO_BACKGROUND_MSPLANFIX — Fixed plan mode auto-running file-modifying Bash commands such as touch and rm without a permission prompt or an SDK canUseTool callbackSONNET5 — Claude Sonnet 5 is running on introductory pricing of $2 per million input tokens and $10 per million output. After August 31 it moves to $3 and $15IPO — Bankers are reportedly lining up investor meetings for Anthropic ahead of a possible public listing as soon as OctoberFORK — Claude Code 2.1.212 changes what /fork does: it copies your conversation into a new background session with its own row in claude agents, so you can keep working. The old in-session subagent is now /subtaskLIMITS — WebSearch calls are now capped at 200 per session by default, and subagent spawns get the same 200 ceiling, so a runaway search or delegation loop stops on its ownMCPBG — MCP tool calls running past two minutes now move to the background automatically, keeping the session usable. Tune the threshold with CLAUDE_CODE_MCP_AUTO_BACKGROUND_MSPLANFIX — Fixed plan mode auto-running file-modifying Bash commands such as touch and rm without a permission prompt or an SDK canUseTool callbackSONNET5 — Claude Sonnet 5 is running on introductory pricing of $2 per million input tokens and $10 per million output. After August 31 it moves to $3 and $15IPO — Bankers are reportedly lining up investor meetings for Anthropic ahead of a possible public listing as soon as October
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 API115output-300klong-form generation2beta featurePython17Anthropic13

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-06-25
Reach a Remote MCP Server in a Single API Request: Implementing the Messages API MCP Connector
How to call a remote MCP server's tools using only the Messages API's mcp_servers and mcp_toolset—no local MCP client. Covers allowlist/denylist design, response handling, and the pitfalls to avoid before unattended production use.
API & SDK2026-06-13
Claude API Python Advanced Cookbook: 20 Production Patterns You'll Actually Use
20 battle-tested Python patterns for the Claude API—retry logic, parallel processing, cost optimization, testing, and monitoring. Copy-paste ready code recipes.
API & SDK2026-06-01
Grouping Crashes by Root Cause: A Triage Design Built on the Claude API
Crashlytics 'Issues' often scatter the same root cause across separate entries. After years of running apps with 50M+ cumulative downloads, here is how I use the Claude API to regroup crashes by actual root cause and rank them, with working code and real numbers.
📚RECOMMENDED BOOKS
Build a Large Language Model (From Scratch)
Sebastian Raschka
LLM Dev
Prompt Engineering for LLMs
Berryman & Ziegler
Prompting
AI Engineering
Chip Huyen
AI Eng
* Contains affiliate links
See all →