How to Build a Text Summarizer with Claude API
Building a text summarizer with Claude API means sending raw text (articles, transcripts, support tickets, PDFs) to a Claude model with a prompt that specifies length, tone, and format, then handling the response in your app. Claude is a strong fit for this because of its long context window and controllable output style — you can ask for a one-sentence summary, a bulleted digest, or an executive brief, and get consistent results.
This guide walks through the actual implementation: designing the prompt, handling long inputs that exceed context limits, streaming output for better UX, and deploying it reliably in production.
What you need before starting
- Access to Claude (either direct Anthropic API access or a wrapped access method)
- A way to call an HTTPS endpoint from your backend or script
- Input text source (file upload, scraped page, transcript, etc.)
If you already have a Claude subscription but no API key, services like SubToAPI turn that access into a standard HTTPS API with sub_live_... keys, so you can call it from any backend without setting up separate API billing. The examples below use that endpoint, but the logic applies to any Claude-compatible API.
Step 1: Design the summarization prompt
The quality of a summarizer lives in the prompt, not the code. Be explicit about:
- Length — "in 3 sentences," "under 100 words," "5 bullet points"
- Audience — technical reader vs. general audience
- Format — plain prose, bullets, or structured JSON
- What to exclude — boilerplate, ads, navigation text if scraped from the web
A solid baseline prompt:
Summarize the following text in 3-5 bullet points.
Focus on key facts, decisions, and action items.
Omit greetings, filler, and repeated information.
Text:
"""
{input_text}
"""
Putting the instructions before the text and wrapping the content in delimiters (triple quotes) keeps the model from confusing instructions with content — important when summarizing user-generated text that might contain its own instructions.
Step 2: Call the API
Here's a minimal request using the SubToAPI messages endpoint:
curl https://api.subtoapi.app/v1/messages \
-H "Authorization: Bearer $SUBTOAPI_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "claude-sonnet-4",
"max_tokens": 300,
"messages": [
{
"role": "user",
"content": "Summarize the following text in 3-5 bullet points. Focus on key facts and action items.\n\nText:\n\"\"\"\nYour long article text here...\n\"\"\""
}
]
}'
In JavaScript:
const response = await fetch("https://api.subtoapi.app/v1/messages", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.SUBTOAPI_KEY}`,
"Content-Type": "application/json"
},
body: JSON.stringify({
model: "claude-sonnet-4",
max_tokens: 300,
messages: [
{ role: "user", content: `Summarize in 3-5 bullet points:\n\n"""${inputText}"""` }
]
})
});
const data = await response.json();
console.log(data.content[0].text);
See the messages docs for the full request/response schema, including how usage metadata is returned per call — useful if you're summarizing at volume and want to track token cost.
Step 3: Handle text longer than the context window
Most real-world documents fit comfortably within Claude's context window, but transcripts, logs, or books can exceed it. Two common strategies:
Chunk and summarize recursively — split the text into sections (by paragraph, heading, or a fixed token count), summarize each chunk independently, then summarize the summaries into a final digest.
async function summarizeChunk(text) {
// call the API with a single-chunk summarization prompt
}
async function summarizeLongDocument(fullText, chunkSize = 6000) {
const chunks = splitIntoChunks(fullText, chunkSize);
const chunkSummaries = await Promise.all(chunks.map(summarizeChunk));
const combined = chunkSummaries.join("\n\n");
return summarizeChunk(combined); // final pass
}
Single-pass with a large context window — if your document fits within the model's limit, skip chunking entirely and send it in one request. This is simpler and usually produces better coherence since the model sees the full context at once. Only chunk when you have to.
Step 4: Stream the output for long summaries
If you're summarizing inside a UI (not a batch job), streaming the response token-by-token makes the app feel responsive instead of waiting on a single blocking call. Enable streaming by setting "stream": true in the request and reading the response as server-sent events:
const response = await fetch("https://api.subtoapi.app/v1/messages", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.SUBTOAPI_KEY}`,
"Content-Type": "application/json"
},
body: JSON.stringify({
model: "claude-sonnet-4",
max_tokens: 400,
stream: true,
messages: [{ role: "user", content: prompt }]
})
});
for await (const chunk of response.body) {
process.stdout.write(chunk.toString());
}
Full event format and reconnection handling are covered in the streaming docs.
Step 5: Add structure with tool use (optional)
If you need the summary as structured data — say, a JSON object with title, key_points, and sentiment fields — define a tool schema instead of parsing free text. Claude will return a structured tool call matching your schema, which is far more reliable than regex-parsing a text response. Details are in the tool use docs.
Step 6: Production considerations
- Batch jobs: for nightly summarization of large document sets, run requests in parallel with a concurrency limit rather than sequentially.
- Cost control: cap
max_tokenson the output since summaries rarely need more than a few hundred tokens. - Caching: if the same document is summarized repeatedly, cache the result keyed by a content hash instead of re-calling the API.
- Access management: if multiple team members or services need to call the summarizer, issue separate API keys per environment rather than sharing one credential — this makes usage tracking and key rotation far easier.
If you're starting from a Claude subscription and want this running as a proper backend without managing separate API billing, SubToAPI issues sub_live_... keys per app and gives each team member seat-level access from one dashboard. Check pricing for the Solo, Team, and Scale tiers, or start with the quickstart guide and a free trial at signup.
Questions
Does Claude have a token limit I need to worry about for long documents? Yes — very long inputs (full books, multi-hour transcripts) can exceed the context window. Use the chunk-and-summarize pattern above for those cases; most articles, reports, and tickets fit in a single request.
Should I use streaming for a batch summarization job? No, streaming is mainly useful for interactive UIs where users watch the summary generate. For batch jobs, use standard non-streaming requests and run them with controlled concurrency.
How do I get structured output instead of free text summaries? Define a tool schema with the fields you need (e.g., key_points, sentiment) instead of asking for plain text. Claude returns a structured tool call matching the schema, which is easier to parse reliably — see the tool use docs for the schema format.