Use custom instructions to ask for claims, caveats, sales objections or the implementation steps in a tutorial.
Submit media with optional instructions. tldw.sh retrieves available source text, analyzes it and saves the result. Python and JavaScript use the same asynchronous API; jobs keep running after your local wait ends.
Install the clients
The JavaScript client requires Node.js 20.11 or newer. Python uses a virtual environment:
npm install @tldw/clientpython3 -m venv .venv
. .venv/bin/activate
python -m pip install tldw-clientOnly @tldw/client on npm and tldw-client on PyPI are these clients. Versioned downloads are listed on https://tldw.sh/agents.
Create an activated account and supply a scoped API key privately as TLDW_API_TOKEN. Both examples need jobs:write, jobs:read and summaries:read. They use a public video URL supplied on the command line; a plain-text string can also be submitted through the API.
JavaScript: submit, show progress and read the output
Save this as analyze.mjs:
import { writeFile } from "node:fs/promises";
import { TldwClient, TldwTimeoutError } from "@tldw/client";
const client = new TldwClient({
apiUrl: "https://api.tldw.sh",
token: process.env.TLDW_API_TOKEN,
});
let jobId = process.env.TLDW_JOB_ID;
if (!jobId) {
const media = process.argv[2];
const idempotencyKey = process.env.TLDW_REQUEST_ID;
if (!media || !idempotencyKey) {
throw new Error("Supply a video URL and a saved TLDW_REQUEST_ID, or TLDW_JOB_ID to resume.");
}
const receipt = await client.submitAnalysis(media, {
instructions: "Extract the main claim, practical steps and caveats. Avoid repetition.",
maxCredits: 30,
idempotencyKey,
});
jobId = receipt.job_id;
await writeFile("tldw-job.json", JSON.stringify({ job_id: jobId }), { mode: 0o600 });
}
console.error(`Job ID: ${jobId}`);
try {
const job = await client.waitForJob(jobId, {
timeoutMs: 120_000,
onProgress: (current) => {
console.error(`${current.status}: ${current.progress}%`);
},
});
const summary = await client.getSummary(job.summary_id);
const transcript = await client.getTranscript(job.summary_id);
console.log(JSON.stringify({ summary, transcript }, null, 2));
} catch (error) {
if (error instanceof TldwTimeoutError) {
console.error(`Wait ended. Resume with TLDW_JOB_ID=${jobId} node analyze.mjs`);
process.exitCode = 2;
} else {
throw error;
}
}Create a request ID once per intended analysis, keep it for retries, and run:
export TLDW_REQUEST_ID="$(node -e 'console.log(crypto.randomUUID())')"
node analyze.mjs 'https://www.youtube.com/shorts/af3oL9JMA1g'If the wait expires, run the resume command printed by the script. It uses the existing job without resubmitting the source. Progress goes to stderr; the final summary and transcript go to stdout, so you can redirect them to a private file.
Python: submit and read the result
Save this as analyze.py:
import json
import os
import sys
from pathlib import Path
from tldw_client import TldwClient, TldwTimeoutError
client = TldwClient(
api_url="https://api.tldw.sh",
token=os.environ["TLDW_API_TOKEN"],
)
job_id = os.environ.get("TLDW_JOB_ID")
if not job_id:
media = sys.argv[1] if len(sys.argv) > 1 else None
request_id = os.environ.get("TLDW_REQUEST_ID")
if not media or not request_id:
raise ValueError("Supply a video URL and a saved TLDW_REQUEST_ID, or TLDW_JOB_ID to resume.")
receipt = client.submit_analysis(
media,
instructions="Extract the main claim, practical steps and caveats. Avoid repetition.",
max_credits=30,
idempotency_key=request_id,
)
job_id = receipt["job_id"]
Path("tldw-job.json").write_text(json.dumps({"job_id": job_id}))
print(f"Job ID: {job_id}", file=sys.stderr)
try:
job = client.wait_for_job(
job_id,
timeout_seconds=120,
on_progress=lambda current: print(
f"{current['status']}: {current['progress']}%", file=sys.stderr
),
)
summary = client.get_summary(job["summary_id"])
transcript = client.get_transcript(job["summary_id"])
print(json.dumps({"summary": summary, "transcript": transcript}, indent=2))
except TldwTimeoutError:
print(f"Wait ended. Resume with TLDW_JOB_ID={job_id} python analyze.py", file=sys.stderr)
sys.exit(2)Use a new request identity for a new intended analysis:
export TLDW_REQUEST_ID="$(python -c 'import uuid; print(uuid.uuid4())')"
python analyze.py 'https://www.youtube.com/shorts/af3oL9JMA1g'Both scripts save tldw-job.json in the working directory. Run one example at a time there, or use a separate directory for each workflow. The file contains an identifier, not an API token; results and identifiers should still be handled as account data.
Make retries safe
If a submission response is lost before the job ID is saved, reuse the same request ID and exactly the same body. For a new video or different instructions, create a new request identity. Persist that identity and request body before submitting in a production integration.
The SDK polling helpers honor server polling guidance and raise errors for failed or canceled jobs. A wait timeout leaves the server job running. Authentication, quota and ownership errors require a deliberate fix rather than an unlimited retry loop. For parallel workflows, store each request and receipt independently in your own database or queue.
Read saved source pages
The scripts above read the original source with the completed analysis's summary ID.
Use listTranscripts / list_transcripts to browse recent saved sources with
pagination, UTC date filters and unread status. Given a saved transcript ID, use
getSavedTranscriptPage(transcriptId, {offset: 0, limit: 100}) or
get_saved_transcript_page(transcript_id, offset=0, limit=100) for bounded pages.
These reads start no new processing. See the current SDK contract
for complete options.
Know what the result covers
getSummary / get_summary returns generated analysis. getTranscript / get_transcript returns saved original source material. A requested output language changes the analysis, not the saved captions. Reading saved results uses no processing credits.
These examples use usable saved source or captions within a 30-credit ceiling. Fresh audio transcription is unsupported on every plan; legacy transcription controls do not enable it. Missing captions produce nonretryable CAPTIONS_UNAVAILABLE, release the hold and incur no processing-credit charge. Blocked or temporary retrieval failures retain their own codes. Stop or supply authorized source text rather than resubmitting automatically. Free includes 100 monthly caption/text credits and a 30-minute per-source limit. Captions cost 1 credit per billable minute; limits and rounding apply. Visual-only content is outside this analysis.
Use the API reference for current schemas and the error guide for recovery details.