Call Analytics Pipeline: Diarized Transcription + LLM Analysis
Call Analytics Pipeline: Diarized Transcription + LLM Analysis
Overview
This cookbook builds a call analytics pipeline that turns raw call recordings into structured, actionable insights. It uses Sarvamโs Batch Speech-to-Text Translate API with speaker diarization to transcribe calls, then uses a Sarvam chat model to analyze the conversation, answer follow-up questions, and generate summaries.
What youโll build:
- A reusable
CallAnalyticsclass that goes from raw audio to structured insight with one method call - Speaker-wise, diarized transcripts (
*_conversation.txt) with per-speaker talk-time (*_timing.json) - An LLM-generated structured analysis of each call, covering customer type, issue, sentiment, and resolution (
*_analysis.txt) - Answers to any custom question you ask across all processed calls
- A consolidated summary report across all calls (
summary_*.txt)
Business Value
- Improve agent effectiveness
- Understand customer sentiment
- Detect operational issues early
- Spot upsell/cross-sell opportunities
- Generate real-time dashboards
E-commerce / D2C
Contact Centers / BPOs
Healthcare & Insurance
Understand refund requests, delivery concerns, or dissatisfaction with product quality directly from customer calls.
Sample audio files are available in the sarvam-ai-cookbook GitHub repo.
How It Works
Diarization assigns a speaker label to every line of the transcript, which is what makes agent/customer-specific analysis (sentiment, talk-time, resolution tracking) possible in the first place. The pipeline below preserves that speaker structure end-to-end, from raw audio to the final report.
Transcribe with diarization
Upload one or more call recordings to Sarvamโs Batch STT Translate API with with_diarization=True. The API transcribes and translates the call to English, tagging each line with a speaker ID.
Parse speaker-wise transcripts
Convert the raw diarized JSON into a clean SPEAKER: text transcript and compute total speaking time per speaker, useful for agent talk-time vs. listening-time monitoring.
1. Prerequisites
- Python 3.8+
- A Sarvam API key, sign up on the Sarvam AI Dashboard to get one
- FFmpeg installed and on your
PATH, required bypydubto read and split audio files - One or more call recordings (
.mp3,.wav, etc.). You can use the sample call recording to follow along
2. Install the SDK and Dependencies
pydub is used to inspect and split long recordings before transcription. See The Full Pipeline Script below. It requires FFmpeg to be installed separately (it is not a Python package).
3. Authentication
- Obtain your API key: If you donโt have one, sign up on the Sarvam AI Dashboard.
- Set your API key: Export it as an environment variable,
export SARVAM_API_KEY="your-key-here"(macOS/Linux) orsetx SARVAM_API_KEY "your-key-here"(Windows). The script below reads it viaos.environ["SARVAM_API_KEY"].
Loading the key from an environment variable, instead of hardcoding it, keeps it out of source control. If youโre just experimenting locally, you can instead replace os.environ["SARVAM_API_KEY"] with the key as a plain string, but avoid committing that change.
4. The Full Pipeline Script
Everything below, imports, the 2-hour-file-limit helpers, the CallAnalytics class, and the code that runs it end-to-end, lives in one script. Copy it into a single .py file as-is:
How it works
split_audio/prepare_audio_pathshandle the Batch APIโs 2-hour-per-file limit. Most calls are well under 2 hours, soprepare_audio_pathsjust returns the original path unchanged; only recordings longer than 2 hours actually get split and exported into parts.process_audio_filescreates a diarized transcription job on Sarvamโs Batch STT Translate API, uploads your audio, waits for completion, checks per-file success/failure, downloads the raw outputs, and kicks off analysis for every successfully transcribed file._parse_transcriptionsreads the downloaded JSON, converts diarized entries into aSPEAKER: texttranscript (*_conversation.txt), and tallies each speakerโs total talk-time (*_timing.json), handy for spotting whether the agent is doing too much (or too little) of the talking.analyze_transcriptionsends the parsed transcript to a Sarvam chat model with a structured prompt covering speaker roles, customer type, issue, resolution, sentiment, and upsell opportunities, saving the result to*_analysis.txt.answer_questionlets you ask any custom question (e.g. โDid the agent mention a refund timeline?โ) against every transcript youโve processed so far.get_summarycondenses each callโs analysis into a 2-3-word-per-field summary and writes one consolidated report, the fastest way to scan many calls at a glance.
sarvam-105b has reasoning enabled by default, and reasoning tokens count toward max_tokens. With no max_tokens set, the 9-point structured analysis prompt above can get cut off mid-answer (which then breaks get_summary, since it summarizes a truncated analysis). Setting max_tokens=4096 and reasoning_effort=None avoids this and is also cheaper and faster for this kind of structured-extraction task, which doesnโt benefit much from chain-of-thought reasoning. See Reasoning for details.
For very long calls, the transcript plus prompt may exceed the chat modelโs context window. See Tips and Best Practices below for how to handle this.
The last block in the script creates the client, runs the pipeline on your audio, asks a follow-up question, and generates a summary. Once it completes, check the outputs/ directory. Youโll have the raw transcription JSON, the parsed conversation and timing files, the structured analysis, your questionโs answer, and a summary report, all named by the original audio file.
5. Sample Output
Below is the analysis youโd get by running the pipeline on the sample Sample_product_refund.mp3 recording.
6. Tips & Best Practices
- Audio quality: Clear audio with minimal background noise and cross-talk significantly improves diarization and transcription accuracy.
- Speaker count: If you know the number of speakers in advance, pass
num_speakerstocreate_jobfor more consistent diarization instead of relying on auto-detection. - Batch limits: A single job accepts up to 20 files and each file can be up to 2 hours long.
split_audioandprepare_audio_pathsin The Full Pipeline Script handle anything longer. - Long transcripts: If a call transcript is long enough to risk exceeding the chat modelโs context window, chunk it (e.g. by time segment) and analyze each chunk before combining results, rather than sending the entire transcript in one prompt.
- Cost & latency: Each call triggers one LLM request per method (
analyze_transcription,answer_question,get_summary). For large call volumes, batch or parallelize these calls and monitor your token usage. - API key security: Load your key from an environment variable rather than hardcoding it, especially outside local experimentation.
7. Error Handling
You may encounter these errors while using the API:
- 403 Forbidden (
invalid_api_key_error), invalid API key. Use a valid key from the Sarvam AI Dashboard. - 429 Too Many Requests (
insufficient_quota_error/rate_limit_exceeded_error), credits exhausted or rate limit hit. Retry with exponential backoff. - 500 Internal Server Error (
internal_server_error), issue on our servers. Try again later; contact support if persistent.
For the full error-code table, request validation errors (400/422), retry guidance, and SDK exceptions, see Errors & Troubleshooting.
8. Additional Resources
- Documentation: docs.sarvam.ai
- Related cookbooks: Batch Speech-to-Text Translate ยท Chat Completion API
- Example projects: sarvam-ai-cookbook on GitHub
- Community: Join the Discord Community
9. Final Notes
- Keep your API key secure, prefer environment variables over hardcoding.
- Use clear audio for best diarization and transcription results.
- All outputs (transcripts, timing, analysis, answers, summaries) are saved under
outputs/for easy review.
Keep Building! ๐