# Create Alert Definition Source: https://docs.usetuner.ai/api-reference/agent-settings/create-alert-definition https://api.usetuner.ai/public/openapi.json post /api/v1/workspaces/{workspace_id}/agents/{agent_id}/settings/alert-definitions Create a new alert definition for an agent. An alert fires when its condition matches enough calls within a rolling window. # Create Call Intent Source: https://docs.usetuner.ai/api-reference/agent-settings/create-call-intent https://api.usetuner.ai/public/openapi.json post /api/v1/workspaces/{workspace_id}/agents/{agent_id}/settings/call-intents Create a call intent for an agent. Call intents are the reasons a caller reached out — "billing question", "cancel subscription". Calls are classified into one of them when AI intent detection is enabled. # Create Call Outcome Source: https://docs.usetuner.ai/api-reference/agent-settings/create-call-outcome https://api.usetuner.ai/public/openapi.json post /api/v1/workspaces/{workspace_id}/agents/{agent_id}/settings/call-outcomes Create a call outcome for an agent. Call outcomes are the end-states a call can be classified into after analysis — "resolved", "escalated", "no answer". Each carries an `outcome_type` of success or failure, which drives the success rate on your dashboards. # Create Eval Source: https://docs.usetuner.ai/api-reference/agent-settings/create-eval https://api.usetuner.ai/public/openapi.json post /api/v1/workspaces/{workspace_id}/agents/{agent_id}/settings/evals Create an eval for an agent. Evals are the criteria used to grade calls after analysis. Eval names must be unique per agent. # Create Evals Bulk Source: https://docs.usetuner.ai/api-reference/agent-settings/create-evals-bulk https://api.usetuner.ai/public/openapi.json post /api/v1/workspaces/{workspace_id}/agents/{agent_id}/settings/evals/bulk Create multiple evals for an agent in a single request. Equivalent to calling `POST /settings/evals` once per item, but atomic from the caller's perspective. # Create Extraction Field Source: https://docs.usetuner.ai/api-reference/agent-settings/create-extraction-field https://api.usetuner.ai/public/openapi.json post /api/v1/workspaces/{workspace_id}/agents/{agent_id}/settings/data-extraction Create a data extraction field for an agent. Extraction fields are structured values the AI pulls from each call transcript — an order number, a reported issue, a callback date. # Create Rule Source: https://docs.usetuner.ai/api-reference/agent-settings/create-rule https://api.usetuner.ai/public/openapi.json post /api/v1/workspaces/{workspace_id}/agents/{agent_id}/settings/rules Create a rule that labels or red-flags matching calls. Describe the condition with `condition_tree`: AND/OR groups of conditions, nested as deep as you need. Get valid condition sources from List Rule Conditions. # Delete Alert Definition Source: https://docs.usetuner.ai/api-reference/agent-settings/delete-alert-definition https://api.usetuner.ai/public/openapi.json delete /api/v1/workspaces/{workspace_id}/agents/{agent_id}/settings/alert-definitions/{alert_id} Delete an alert definition. Also permanently deletes the alert's saved matching calls and its trigger history. The calls themselves are kept. # Delete Call Intent Source: https://docs.usetuner.ai/api-reference/agent-settings/delete-call-intent https://api.usetuner.ai/public/openapi.json delete /api/v1/workspaces/{workspace_id}/agents/{agent_id}/settings/call-intents/{intent_id} Delete a call intent. # Delete Call Outcome Source: https://docs.usetuner.ai/api-reference/agent-settings/delete-call-outcome https://api.usetuner.ai/public/openapi.json delete /api/v1/workspaces/{workspace_id}/agents/{agent_id}/settings/call-outcomes/{outcome_id} Delete a call outcome. # Delete Eval Source: https://docs.usetuner.ai/api-reference/agent-settings/delete-eval https://api.usetuner.ai/public/openapi.json delete /api/v1/workspaces/{workspace_id}/agents/{agent_id}/settings/evals/{eval_id} Delete an existing eval. Alerts and rules that use the eval are paused, not deleted, so their history is kept. If any do, the request fails with 409 and lists them unless `confirm` is `true`. # Delete Extraction Field Source: https://docs.usetuner.ai/api-reference/agent-settings/delete-extraction-field https://api.usetuner.ai/public/openapi.json delete /api/v1/workspaces/{workspace_id}/agents/{agent_id}/settings/data-extraction/{field_id} Delete a data extraction field. Alerts and rules that use the field are paused, not deleted, so their history is kept. If any do, the request fails with 409 and lists them unless `confirm` is `true`. # Delete Outbound Config Source: https://docs.usetuner.ai/api-reference/agent-settings/delete-outbound-config https://api.usetuner.ai/public/openapi.json delete /api/v1/workspaces/{workspace_id}/agents/{agent_id}/settings/outbound-config Delete the outbound calling configuration for an agent. # Delete Rule Source: https://docs.usetuner.ai/api-reference/agent-settings/delete-rule https://api.usetuner.ai/public/openapi.json delete /api/v1/workspaces/{workspace_id}/agents/{agent_id}/settings/rules/{rule_id} Delete an existing rule. Deleting a red-flag rule affects alerts that match its tag. They are paused, not deleted, so their history is kept. If any do, the request fails with 409 and lists them unless `confirm` is `true`. Label rules are deleted without this check. # Delete SIP Config Source: https://docs.usetuner.ai/api-reference/agent-settings/delete-sip-config https://api.usetuner.ai/public/openapi.json delete /api/v1/workspaces/{workspace_id}/agents/{agent_id}/settings/sip-config Delete the SIP trunk configuration for an agent. # Get Alert Definition Source: https://docs.usetuner.ai/api-reference/agent-settings/get-alert-definition https://api.usetuner.ai/public/openapi.json get /api/v1/workspaces/{workspace_id}/agents/{agent_id}/settings/alert-definitions/{alert_id} Get a single alert definition by ID. # Get Analysis Settings Source: https://docs.usetuner.ai/api-reference/agent-settings/get-analysis-settings https://api.usetuner.ai/public/openapi.json get /api/v1/workspaces/{workspace_id}/agents/{agent_id}/settings/call-analysis Get the configuration that controls how this agent's calls are analyzed. Returns the agent's call outcomes, call intents, data extraction fields, and whether AI intent detection is enabled. Read-only — each of these is configured through its own endpoint. # Get Eval Source: https://docs.usetuner.ai/api-reference/agent-settings/get-eval https://api.usetuner.ai/public/openapi.json get /api/v1/workspaces/{workspace_id}/agents/{agent_id}/settings/evals/{eval_id} Get a single eval by ID. # Get Outbound Config Source: https://docs.usetuner.ai/api-reference/agent-settings/get-outbound-config https://api.usetuner.ai/public/openapi.json get /api/v1/workspaces/{workspace_id}/agents/{agent_id}/settings/outbound-config Get the outbound calling configuration for an agent. # Get Rule Source: https://docs.usetuner.ai/api-reference/agent-settings/get-rule https://api.usetuner.ai/public/openapi.json get /api/v1/workspaces/{workspace_id}/agents/{agent_id}/settings/rules/{rule_id} Get a single rule by ID. # Get SIP Config Source: https://docs.usetuner.ai/api-reference/agent-settings/get-sip-config https://api.usetuner.ai/public/openapi.json get /api/v1/workspaces/{workspace_id}/agents/{agent_id}/settings/sip-config Get the SIP trunk configuration for an agent. # List Alert Conditions Source: https://docs.usetuner.ai/api-reference/agent-settings/list-alert-conditions https://api.usetuner.ai/public/openapi.json get /api/v1/workspaces/{workspace_id}/agents/{agent_id}/settings/alert-definitions/available-conditions List the condition sources available for building alert definitions on this agent. Returns evals, voice metrics, extraction fields, call metadata, and red flags including aggregates. Use these to build a `condition_tree`. # List Alert Definitions Source: https://docs.usetuner.ai/api-reference/agent-settings/list-alert-definitions https://api.usetuner.ai/public/openapi.json get /api/v1/workspaces/{workspace_id}/agents/{agent_id}/settings/alert-definitions List all alert definitions configured for an agent. Alert definitions notify a set of recipients (email) when a condition is met on a call, based on evals, voice metrics, data extraction fields, call metadata, or red flags. # List Evals Source: https://docs.usetuner.ai/api-reference/agent-settings/list-evals https://api.usetuner.ai/public/openapi.json get /api/v1/workspaces/{workspace_id}/agents/{agent_id}/settings/evals List all evals configured for an agent. # List Rule Conditions Source: https://docs.usetuner.ai/api-reference/agent-settings/list-rule-conditions https://api.usetuner.ai/public/openapi.json get /api/v1/workspaces/{workspace_id}/agents/{agent_id}/settings/rules/available-conditions List the condition sources available for building rules on this agent. Returns each source with the operators and value types it accepts, grouped by `source_type`. Use these to build a rule's `condition_tree`; Create Rule explains how an item becomes a condition. The `call_metadata` source has seven items (IDs 0 to 5 and 12). In a tree, Call Outcome (0), Call Intent (1), Call Duration (2), Call Cost (3), Call Outcome Type (4) and Call Ended Reason (12) are written `call_outcome`, `call_intent`, `call_duration`, `call_cost`, `call_outcome_type` and `call_ended_reason` in `lhs`; ID 5, "Extra Metadata", is written `metadata.`. # List Rules Source: https://docs.usetuner.ai/api-reference/agent-settings/list-rules https://api.usetuner.ai/public/openapi.json get /api/v1/workspaces/{workspace_id}/agents/{agent_id}/settings/rules List an agent's rules. A rule tests a condition against each analyzed call and, when it matches, applies a tag. `output_type` determines whether the tag is a label or a red flag. `condition_tree` holds the rule's conditions. # Save Outbound Config Source: https://docs.usetuner.ai/api-reference/agent-settings/save-outbound-config https://api.usetuner.ai/public/openapi.json put /api/v1/workspaces/{workspace_id}/agents/{agent_id}/settings/outbound-config Save the outbound calling configuration for an agent. Tuner sends a request to the `trigger_url` to verify it's reachable before saving. The configuration is only stored if that check succeeds. # Save SIP Config Source: https://docs.usetuner.ai/api-reference/agent-settings/save-sip-config https://api.usetuner.ai/public/openapi.json put /api/v1/workspaces/{workspace_id}/agents/{agent_id}/settings/sip-config Save the SIP trunk configuration for an agent. Tuner connects to the trunk to verify the details before saving. The configuration is only stored if the check succeeds, so a successful response means the trunk is reachable. # Update Alert Definition Source: https://docs.usetuner.ai/api-reference/agent-settings/update-alert-definition https://api.usetuner.ai/public/openapi.json put /api/v1/workspaces/{workspace_id}/agents/{agent_id}/settings/alert-definitions/{alert_id} Update an existing alert definition. Switching `threshold_type` requires sending the fields that mode needs, and switching to `percentage` requires a single-predicate condition tree. # Update Call Intent Source: https://docs.usetuner.ai/api-reference/agent-settings/update-call-intent https://api.usetuner.ai/public/openapi.json put /api/v1/workspaces/{workspace_id}/agents/{agent_id}/settings/call-intents/{intent_id} Update an existing call intent. # Update Call Outcome Source: https://docs.usetuner.ai/api-reference/agent-settings/update-call-outcome https://api.usetuner.ai/public/openapi.json put /api/v1/workspaces/{workspace_id}/agents/{agent_id}/settings/call-outcomes/{outcome_id} Update an existing call outcome. # Update Eval Source: https://docs.usetuner.ai/api-reference/agent-settings/update-eval https://api.usetuner.ai/public/openapi.json put /api/v1/workspaces/{workspace_id}/agents/{agent_id}/settings/evals/{eval_id} Update an eval. # Update Extraction Field Source: https://docs.usetuner.ai/api-reference/agent-settings/update-extraction-field https://api.usetuner.ai/public/openapi.json put /api/v1/workspaces/{workspace_id}/agents/{agent_id}/settings/data-extraction/{field_id} Update an existing data extraction field. # Update Intent Detection Source: https://docs.usetuner.ai/api-reference/agent-settings/update-intent-detection https://api.usetuner.ai/public/openapi.json put /api/v1/workspaces/{workspace_id}/agents/{agent_id}/settings/intent-detection Enable or disable AI intent detection for an agent. When disabled, calls are no longer classified into the agent's configured call intents. Existing intents are kept and classification resumes if you re-enable it. # Update Rule Source: https://docs.usetuner.ai/api-reference/agent-settings/update-rule https://api.usetuner.ai/public/openapi.json put /api/v1/workspaces/{workspace_id}/agents/{agent_id}/settings/rules/{rule_id} Update an existing rule. Only the fields you send are changed. `condition_tree` replaces the whole condition. Sending `state` pauses or resumes the rule; a rule is always checked when it is set back to `active`. Sending `null` for any field except `output_description` is the same as leaving it out. # Create Agent Source: https://docs.usetuner.ai/api-reference/agents/create-agent https://api.usetuner.ai/public/openapi.json post /api/v1/workspaces/{workspace_id}/agents/ Create an agent and link it to a voice provider. Tuner reuses the workspace's existing integration for the provider, so sending the same credentials for multiple agents won't create duplicates. The integration is keyed by provider per workspace: creating a second agent with different credentials for the same provider overwrites the shared integration's credentials. # Get Agent Source: https://docs.usetuner.ai/api-reference/agents/get-agent https://api.usetuner.ai/public/openapi.json get /api/v1/workspaces/{workspace_id}/agents/{agent_id} Retrieve an agent with its provider integration. Includes the linked integration and provider details. # List Agents Source: https://docs.usetuner.ai/api-reference/agents/list-agents https://api.usetuner.ai/public/openapi.json get /api/v1/workspaces/{workspace_id}/agents/ List all active agents in a workspace. Each agent includes its Tuner `id`, which every other agent and call endpoint expects. Inactive agents are excluded. # Update Agent Source: https://docs.usetuner.ai/api-reference/agents/update-agent https://api.usetuner.ai/public/openapi.json put /api/v1/workspaces/{workspace_id}/agents/{agent_id} Replace an agent's configuration. This is a full replacement: omitted fields are cleared (except `api_key`, which keeps the stored provider key when omitted), so fetch the agent first and re-send any values you aren't changing. # Create Call Source: https://docs.usetuner.ai/api-reference/calls/create-call https://api.usetuner.ai/public/openapi.json post /api/v1/public/call Ingest a completed call for analysis. Accepts the transcript and metadata for a call that has already finished. Tuner queues it for evaluation; scores, outcomes, and red flags appear on the call record shortly after. `call_id` must be unique: re-sending an already-ingested call returns a conflict. # Get Call Source: https://docs.usetuner.ai/api-reference/calls/get-call https://api.usetuner.ai/public/openapi.json get /api/v1/workspaces/{workspace_id}/agents/{agent_id}/calls/{call_id} Retrieve a single call with its full transcript and analysis. # Get Call Spans Source: https://docs.usetuner.ai/api-reference/calls/get-call-spans https://api.usetuner.ai/public/openapi.json get /api/v1/workspaces/{workspace_id}/agents/{agent_id}/calls/{call_id}/spans Retrieve a call's OpenTelemetry spans, flat and in start-time order. Returns an empty list when the call has no trace, which is the common case — whether spans exist depends on how the customer's agent is instrumented. # List Calls Source: https://docs.usetuner.ai/api-reference/calls/list-calls https://api.usetuner.ai/public/openapi.json get /api/v1/workspaces/{workspace_id}/agents/{agent_id}/calls/ List an agent's calls with filtering, sorting, and pagination. # List Filter Options Source: https://docs.usetuner.ai/api-reference/calls/list-filter-options https://api.usetuner.ai/public/openapi.json get /api/v1/workspaces/{workspace_id}/agents/{agent_id}/calls/filter-options List the filter values available for this agent's calls. Returns the call intents, call outcomes, and labels/red flags that can be passed to the corresponding filters on List Calls. # List Red Flagged Calls Source: https://docs.usetuner.ai/api-reference/calls/list-red-flagged-calls https://api.usetuner.ai/public/openapi.json get /api/v1/workspaces/{workspace_id}/agents/{agent_id}/calls/recent-red-flags List an agent's most recently red-flagged calls. # Recalculate Transcription Accuracy Source: https://docs.usetuner.ai/api-reference/calls/recalculate-transcription-accuracy https://api.usetuner.ai/public/openapi.json post /api/v1/workspaces/{workspace_id}/agents/{agent_id}/calls/{call_id}/transcription-accuracy/rescore Re-score one clip-replay call against the clips' current transcripts. Runs synchronously (a text comparison only) and returns the refreshed accuracy block. Clip edits never re-score on their own; this is how an outdated score is brought up to date. On an unexpected error the old score is left untouched. # List Providers Source: https://docs.usetuner.ai/api-reference/providers/list-providers https://api.usetuner.ai/public/openapi.json get /api/v1/providers/ List the voice providers Tuner supports. Each provider's `name` is the value to pass as `provider_name` when creating or updating an agent. # Complete Voice Clip Upload Source: https://docs.usetuner.ai/api-reference/replay-testing/complete-voice-clip-upload https://api.usetuner.ai/public/openapi.json post /api/v1/workspaces/{workspace_id}/agents/{agent_id}/voice-clip-uploads/{voice_clip_upload_id}/complete Finish an upload once every part has been sent, and queue it for analysis. Safe to call again: an upload that is already complete is returned unchanged. # Create Replay Run Source: https://docs.usetuner.ai/api-reference/replay-testing/create-replay-run https://api.usetuner.ai/public/openapi.json post /api/v1/workspaces/{workspace_id}/agents/{agent_id}/replay-runs Start a replay run against one or more voice clip sets. Plays each clip set's recorded caller turns back byte-identical, placing one call per clip set and repetition, for inbound and outbound agents alike. Returns 202 while the calls run asynchronously; poll List Replay Runs for progress. # Create Voice Clip Set Source: https://docs.usetuner.ai/api-reference/replay-testing/create-voice-clip-set https://api.usetuner.ai/public/openapi.json post /api/v1/workspaces/{workspace_id}/agents/{agent_id}/voice-clip-sets Create a voice clip set from a call or an uploaded recording. The clips are cut asynchronously: the set is returned in `extracting` status. Poll Get Voice Clip Set until it is `ready`. # Delete Voice Clip Set Source: https://docs.usetuner.ai/api-reference/replay-testing/delete-voice-clip-set https://api.usetuner.ai/public/openapi.json delete /api/v1/workspaces/{workspace_id}/agents/{agent_id}/voice-clip-sets/{voice_clip_set_id} Delete a voice clip set. # Delete Voice Clip Upload Source: https://docs.usetuner.ai/api-reference/replay-testing/delete-voice-clip-upload https://api.usetuner.ai/public/openapi.json delete /api/v1/workspaces/{workspace_id}/agents/{agent_id}/voice-clip-uploads/{voice_clip_upload_id} Delete an upload and discard its audio. # Edit or Verify a Voice Clip Source: https://docs.usetuner.ai/api-reference/replay-testing/edit-or-verify-a-voice-clip https://api.usetuner.ai/public/openapi.json patch /api/v1/workspaces/{workspace_id}/agents/{agent_id}/voice-clip-sets/{voice_clip_set_id}/clips/{turn_index} Edit a clip's transcript and/or verify or unverify it. Saving a changed transcript verifies the clip and bumps its version; saving the same text only verifies. `verified=false` clears the verification. The set's `transcripts_version` changes only when the clip actually changed. Editing never re-scores anything: a real change only bumps the set's `transcripts_version`, which makes existing transcription-accuracy scores for the set show as outdated. The user re-scores a single call on demand. # Get Voice Clip Set Source: https://docs.usetuner.ai/api-reference/replay-testing/get-voice-clip-set https://api.usetuner.ai/public/openapi.json get /api/v1/workspaces/{workspace_id}/agents/{agent_id}/voice-clip-sets/{voice_clip_set_id} Get a voice clip set, including its clips in playback order. # Get Voice Clip Set Audio URL Source: https://docs.usetuner.ai/api-reference/replay-testing/get-voice-clip-set-audio-url https://api.usetuner.ai/public/openapi.json get /api/v1/workspaces/{workspace_id}/agents/{agent_id}/voice-clip-sets/{voice_clip_set_id}/audio Get a short-lived URL for a voice clip set's caller track. Only available once the set is `ready`. # Get Voice Clip Upload Source: https://docs.usetuner.ai/api-reference/replay-testing/get-voice-clip-upload https://api.usetuner.ai/public/openapi.json get /api/v1/workspaces/{workspace_id}/agents/{agent_id}/voice-clip-uploads/{voice_clip_upload_id} Get an upload's status. Poll it to follow the upload through analysis. # Get Voice Clip Upload Channel Sample URL Source: https://docs.usetuner.ai/api-reference/replay-testing/get-voice-clip-upload-channel-sample-url https://api.usetuner.ai/public/openapi.json get /api/v1/workspaces/{workspace_id}/agents/{agent_id}/voice-clip-uploads/{voice_clip_upload_id}/samples/{channel_index} Get a short-lived presigned URL for one channel's preview sample. Only available once analysis has reached `awaiting_selection`. # Get Voice Clip Upload Parts Source: https://docs.usetuner.ai/api-reference/replay-testing/get-voice-clip-upload-parts https://api.usetuner.ai/public/openapi.json get /api/v1/workspaces/{workspace_id}/agents/{agent_id}/voice-clip-uploads/{voice_clip_upload_id}/parts Resume an interrupted upload. Returns which parts have already been uploaded and fresh URLs for the rest, so you don't need to restart from the first part. # List Replay Runs Source: https://docs.usetuner.ai/api-reference/replay-testing/list-replay-runs https://api.usetuner.ai/public/openapi.json get /api/v1/workspaces/{workspace_id}/agents/{agent_id}/replay-runs List an agent's replay runs with their replayed test calls. Each run includes its simulation calls, pass/fail counts, and the clip sets and evals it was configured with. Filter by `status` to poll for completion. # List Source Call Candidates Source: https://docs.usetuner.ai/api-reference/replay-testing/list-source-call-candidates https://api.usetuner.ai/public/openapi.json get /api/v1/workspaces/{workspace_id}/agents/{agent_id}/voice-clip-sets/source-calls List calls that can be used as the source of a voice clip set. Only calls with both a recording and a transcript are included. # List Voice Clip Sets Source: https://docs.usetuner.ai/api-reference/replay-testing/list-voice-clip-sets https://api.usetuner.ai/public/openapi.json get /api/v1/workspaces/{workspace_id}/agents/{agent_id}/voice-clip-sets List an agent's active voice clip sets, newest first. # Start Voice Clip Upload Source: https://docs.usetuner.ai/api-reference/replay-testing/start-voice-clip-upload https://api.usetuner.ai/public/openapi.json post /api/v1/workspaces/{workspace_id}/agents/{agent_id}/voice-clip-uploads Start a resumable audio upload. Returns a presigned upload URL for every part up front. Use Get Voice Clip Upload Parts to resume an interrupted upload or to get fresh URLs after they expire. # Create Scenario Source: https://docs.usetuner.ai/api-reference/scenarios/create-scenario https://api.usetuner.ai/public/openapi.json post /api/v1/workspaces/{workspace_id}/agents/{agent_id}/scenarios Create a scenario in the agent's library. The scenario is recorded as manually authored; `origin`, `format` and `source_run_id` cannot be set. # Delete Scenario Source: https://docs.usetuner.ai/api-reference/scenarios/delete-scenario https://api.usetuner.ai/public/openapi.json delete /api/v1/workspaces/{workspace_id}/agents/{agent_id}/scenarios/{scenario_id} Delete a scenario. Simulation runs that already used the scenario keep their own copy, so run history is unaffected. # Get Scenario Source: https://docs.usetuner.ai/api-reference/scenarios/get-scenario https://api.usetuner.ai/public/openapi.json get /api/v1/workspaces/{workspace_id}/agents/{agent_id}/scenarios/{scenario_id} Get a single scenario, scoped to the agent. # Get Scenario Run History Source: https://docs.usetuner.ai/api-reference/scenarios/get-scenario-run-history https://api.usetuner.ai/public/openapi.json get /api/v1/workspaces/{workspace_id}/agents/{agent_id}/scenarios/{scenario_id}/runs List every past execution of a scenario across all simulation runs, newest run first. No pass/fail verdict is computed; each execution carries its call status and eval results. # List Scenarios Source: https://docs.usetuner.ai/api-reference/scenarios/list-scenarios https://api.usetuner.ai/public/openapi.json get /api/v1/workspaces/{workspace_id}/agents/{agent_id}/scenarios List an agent's active scenarios, newest first. # Preview Scenario Prompt Source: https://docs.usetuner.ai/api-reference/scenarios/preview-scenario-prompt https://api.usetuner.ai/public/openapi.json post /api/v1/workspaces/{workspace_id}/agents/{agent_id}/scenarios/preview-prompt Preview the prompt that would be used for a scenario. Excludes the caller-persona prefix, profile facts and inbound/outbound footer that are added when the call is placed. Nothing is saved. # Update Scenario Source: https://docs.usetuner.ai/api-reference/scenarios/update-scenario https://api.usetuner.ai/public/openapi.json put /api/v1/workspaces/{workspace_id}/agents/{agent_id}/scenarios/{scenario_id} Update a scenario's authored fields. `origin`, `format` and `source_run_id` cannot be changed. # Create Profile Source: https://docs.usetuner.ai/api-reference/simulation/create-profile https://api.usetuner.ai/public/openapi.json post /api/v1/workspaces/{workspace_id}/agents/{agent_id}/simulation-profiles Create a simulation profile for an agent. # Delete Profile Source: https://docs.usetuner.ai/api-reference/simulation/delete-profile https://api.usetuner.ai/public/openapi.json delete /api/v1/workspaces/{workspace_id}/agents/{agent_id}/simulation-profiles/{profile_id} Delete a simulation profile. Runs that already used this profile keep their snapshot of it. # Get Run Source: https://docs.usetuner.ai/api-reference/simulation/get-run https://api.usetuner.ai/public/openapi.json get /api/v1/workspaces/{workspace_id}/agents/{agent_id}/simulation-runs/{run_id} Get one simulation run with its test calls and results. The same run as in List Runs, plus `is_terminal` and a `dashboard_url`. Poll this until `is_terminal` is true. # List Caller Personas Source: https://docs.usetuner.ai/api-reference/simulation/list-caller-personas https://api.usetuner.ai/public/openapi.json get /api/v1/workspaces/{workspace_id}/caller-personas List the caller personas (language and accent) a simulated caller can use. Use a persona's `id` as `caller_persona_id` when you use Run AI-Generated Scenarios or Run Saved Scenarios. # List Noise Environments Source: https://docs.usetuner.ai/api-reference/simulation/list-noise-environments https://api.usetuner.ai/public/openapi.json get /api/v1/workspaces/{workspace_id}/noise-environments List the background-noise environments a simulation run can play under the caller. Use an environment's `id` as `noise_environment_id` when you use Run AI-Generated Scenarios or Run Saved Scenarios. # List Profiles Source: https://docs.usetuner.ai/api-reference/simulation/list-profiles https://api.usetuner.ai/public/openapi.json get /api/v1/workspaces/{workspace_id}/agents/{agent_id}/simulation-profiles List an agent's simulation profiles. A profile is a named set of details, such as names, dates and reference numbers, that gives simulated callers concrete information to work with. # List Run Scenarios Source: https://docs.usetuner.ai/api-reference/simulation/list-run-scenarios https://api.usetuner.ai/public/openapi.json get /api/v1/workspaces/{workspace_id}/agents/{agent_id}/simulation-runs/{simulation_run_id}/scenarios List the generated test-call scenarios for a simulation run. Scenarios are generated asynchronously after a run starts, so this returns an empty list until generation completes. # List Runs Source: https://docs.usetuner.ai/api-reference/simulation/list-runs https://api.usetuner.ai/public/openapi.json get /api/v1/workspaces/{workspace_id}/agents/{agent_id}/simulation-runs List an agent's simulation runs, both AI-generated and from saved scenarios. Each run includes its test calls and results. Replay runs are listed separately by List Replay Runs. # Run AI-Generated Scenarios Source: https://docs.usetuner.ai/api-reference/simulation/run-ai-generated-scenarios https://api.usetuner.ai/public/openapi.json post /api/v1/workspaces/{workspace_id}/agents/{agent_id}/simulation-runs Start an AI-generated simulation run. Tuner generates new test scenarios for your agent, a mix of functional and adversarial, places a call for each, and grades them with the agent's `PASS_FAIL` evals. Scenarios are generated asynchronously, so poll List Runs for progress. To re-test scenarios you've already saved, use Run Saved Scenarios. # Run Saved Scenarios Source: https://docs.usetuner.ai/api-reference/simulation/run-saved-scenarios https://api.usetuner.ai/public/openapi.json post /api/v1/workspaces/{workspace_id}/agents/{agent_id}/simulation-runs/select Start a run from saved scenarios. Places a call for each scenario you pick from your scenario library, by id or by tag. No new scenarios are generated, so you can re-test the same cases. The caller persona, profile and noise can be given by name (`language`, `profile`, `noise`) instead of id. Each call is scored against every `PASS_FAIL` eval on the agent. Atomic: if any id or name is invalid, the whole request is rejected and nothing is created. To have Tuner generate new scenarios instead, use Run AI-Generated Scenarios. # Save Scenarios To Library Source: https://docs.usetuner.ai/api-reference/simulation/save-scenarios-to-library https://api.usetuner.ai/public/openapi.json post /api/v1/workspaces/{workspace_id}/agents/{agent_id}/simulation-runs/{simulation_run_id}/scenarios/save Save generated scenarios from a finished run into the scenario library. A scenario whose call failed to connect can still be saved. Atomic: if any selection is invalid, not found, or already saved, the whole request is rejected and nothing is created. # Search Runs Source: https://docs.usetuner.ai/api-reference/simulation/search-runs https://api.usetuner.ai/public/openapi.json get /api/v1/workspaces/{workspace_id}/agents/{agent_id}/simulation-runs/search Search an agent's simulation runs by status. A lighter alternative to List Runs for polling. Returns runs newest first. # Update Profile Source: https://docs.usetuner.ai/api-reference/simulation/update-profile https://api.usetuner.ai/public/openapi.json put /api/v1/workspaces/{workspace_id}/agents/{agent_id}/simulation-profiles/{profile_id} Update a simulation profile. # Receive Traces Source: https://docs.usetuner.ai/api-reference/traces/receive-traces https://api.usetuner.ai/public/openapi.json post /api/v1/traces Receive OpenTelemetry traces over OTLP/HTTP. Only the protobuf encoding (`application/x-protobuf`) is accepted. A 4xx response is permanent and should not be retried; a 5xx response is transient and safe to retry. # Create Workspace API Key Source: https://docs.usetuner.ai/api-reference/workspaces/create-workspace-api-key https://api.usetuner.ai/public/openapi.json post /api/v1/workspaces/{workspace_id}/api-keys Mint a new API key for this workspace. **The value is returned once, here, and cannot be retrieved again.** To rotate a key, create its successor, deploy it, then revoke the old one. # Get Data Retention Source: https://docs.usetuner.ai/api-reference/workspaces/get-data-retention https://api.usetuner.ai/public/openapi.json get /api/v1/workspaces/{workspace_id}/data-retention Get a workspace's data-retention policy. Also returns the windows and scopes the workspace's plan allows, for use with the update endpoint. # Get PII Redaction Source: https://docs.usetuner.ai/api-reference/workspaces/get-pii-redaction https://api.usetuner.ai/public/openapi.json get /api/v1/workspaces/{workspace_id}/pii-redaction Get a workspace's PII redaction settings. Returns whether redaction is enabled and which categories are being redacted. # Get Workspace Source: https://docs.usetuner.ai/api-reference/workspaces/get-workspace https://api.usetuner.ai/public/openapi.json get /api/v1/workspaces/{workspace_id} Retrieve a workspace and its configured integrations. # List Workspace API Keys Source: https://docs.usetuner.ai/api-reference/workspaces/list-workspace-api-keys https://api.usetuner.ai/public/openapi.json get /api/v1/workspaces/{workspace_id}/api-keys List this workspace's API keys, newest first. Only keys that can still authenticate. Key values are never returned -- only a hash is stored. # List Workspaces Source: https://docs.usetuner.ai/api-reference/workspaces/list-workspaces https://api.usetuner.ai/public/openapi.json get /api/v1/workspaces/ List the workspaces you have access to. Scoped to the authenticated user. Start here — most Tuner endpoints are workspace-scoped, and the `id` returned for each workspace is the `workspace_id` they expect. # Revoke Workspace API Key Source: https://docs.usetuner.ai/api-reference/workspaces/revoke-workspace-api-key https://api.usetuner.ai/public/openapi.json delete /api/v1/workspaces/{workspace_id}/api-keys/{key_id} Stop a key authenticating, immediately and permanently. Anything still using it stops ingesting at once; the workspace's other keys are unaffected. Idempotent. # Update Data Retention Source: https://docs.usetuner.ai/api-reference/workspaces/update-data-retention https://api.usetuner.ai/public/openapi.json put /api/v1/workspaces/{workspace_id}/data-retention Set a workspace's data-retention window and erasure scope. Expired calls are erased by a nightly job, so a change takes effect on its next run. **Erasure is irreversible**: an erased call cannot be restored. Simulation calls are never erased. # Update PII Redaction Source: https://docs.usetuner.ai/api-reference/workspaces/update-pii-redaction https://api.usetuner.ai/public/openapi.json put /api/v1/workspaces/{workspace_id}/pii-redaction Enable or disable PII redaction for a workspace and choose which categories to redact. Enabling requires a plan that includes PII redaction; disabling is always allowed. Changes apply to calls ingested afterwards — calls already stored aren't reprocessed. # Who Am I Source: https://docs.usetuner.ai/api-reference/workspaces/who-am-i https://api.usetuner.ai/public/openapi.json get /api/v1/whoami Check an API key and resolve an agent's Agent ID to the numeric IDs other routes take. Takes a Tuner API key only. Returns the key's workspace, the key's name and last four characters, and, when `agent_remote_identifier` is sent, that agent. # Changelog Source: https://docs.usetuner.ai/change-log Recent product updates and improvements Recent product updates and improvements. Have a feature request? Reach out at [feedback@usetuner.ai](mailto:feedback@usetuner.ai). ## November 4, 2026 ### 🔌 ElevenLabs Integration & Rules and Alerts Upgrade **ElevenLabs Integration** — Connect an ElevenLabs agent with your API key, and every finished conversation arrives in Tuner. Each one comes with its transcript, tool calls, workflow node transitions, per-turn latency, cost and recording, and no code is needed. Accounts on ElevenLabs' EU, India or Singapore data residency hosts can't connect yet. [Learn more →](https://docs.usetuner.ai/docs/integrations/elevenlabs.md) * **Guided setup** — Pick your agent from your ElevenLabs account, and Tuner fills in its name and system prompt and sets up the post-call webhook. * **Import past calls** — Import the agent's recent conversations and evaluate them straight away. * **Inbound and outbound simulation** — Run simulations through an ElevenLabs SIP trunk number, and for outbound, Tuner can create the number for you. **Rules and Alerts Upgrade** — Rules now have the same conditions and condition builder as alerts, and alerts are easier to tune from the dashboard. [Learn more →](/docs/observability/alerts.md) * **Multiple conditions in rules** — Combine several conditions in one rule with AND and OR, the same way you build alerts. * **New rule conditions** — Rules can now check call outcome, intent, cost and duration, for example to flag transferred calls that ran over five minutes. * **Call ended reason** — Rules and alerts can now check why a call ended, for example to catch calls cut off at your maximum call duration. * **Alert cooldown in the dashboard** — Set how long an alert waits before it can trigger again, from 15 minutes up to 24 hours, when you create or edit it. * **Simulated calls skip alerts** — Simulated calls no longer trigger alerts or count toward thresholds, and the `call.analyzed` webhook now includes `is_simulated` so your automations can skip them. * **Rules on stopped calls** — Rules and alerts now run on calls whose outcome has **Stop Analysis** turned on, such as voicemail or spam calls. * **Checked when you save** — A condition that could never match is rejected when you save it, with a message saying why. **Call Start Time in Evals** — Custom evals and data extraction now know when the call started, so relative dates like "tomorrow" or "next Friday" resolve to the right day. An eval can check that the agent booked the date the caller asked for, and an extraction can return the actual date. [Learn more →](https://docs.usetuner.ai/docs/evaluation/custom-evals.md) *** ## October 23, 2026 ### 🧪 Transcription Accuracy & Simpler Simulation Setup **Transcription Accuracy** — See how accurately your agent's speech-to-text heard the caller on every replay. Tuner compares the agent's transcript of the caller with the Dataset call's reference transcript and scores it, so you can compare STT providers and models on your own callers. [Learn more →](https://docs.usetuner.ai/docs/observability/voice-metrics.md) * **Score and breakdown** — The Voice Metrics tab shows the score with a Good, Fair or Poor label, the counts of misheard, missed and added words, and the STT provider and model the agent used. * **What went wrong** — Each error shows what the caller said next to what the agent heard. * **Editable reference transcripts** — Correct a turn's reference transcript or mark it verified, and the card shows how many turns are verified so you know how far to trust the score. * **Recalculate** — After you edit a reference transcript, recalculate the score from the call or with the Recalculate Transcription Accuracy API. **Simpler Simulation Setup** — Simulation for LiveKit, Pipecat and custom-stack agents now takes less code to set up. It also works when your agent sits behind Twilio, Telnyx or another carrier. The Tuner SDKs now carry the call details across for you, so each simulated call shows up in its run with its results. Update to the latest Tuner SDK to use it. [Learn more →](/docs/simulation/inbound/setup.md) **Clearer Run Statuses** — Simulation runs that used to load forever now settle on a result. A call that ran but never arrived from your agent shows **Unreported** after 15 minutes. A call whose evals didn't come back shows **Analysis failed** after 10 minutes. Each status has a tooltip saying what to check. [Learn more →](/docs/simulation/run-statuses.md) *** ## September 30, 2026 ### 🔁 Replays, Datasets & Scenario Library **Datasets** — Save the real calls you want to test against, from the call that failed last week to your toughest callers. Add a call from production, or upload a stereo recording you already have, with no live traffic needed, and Tuner keeps only the caller's side, cut into caller turns with a reference transcript. Your Dataset becomes a test suite you replay after every change, and a benchmark for picking your stack on your own calls. [Learn more →](/docs/datasets/overview) **Replays** — Rerun those calls against your agent with the exact same caller audio, turn by turn. Because the caller never changes, a result that changes points to your agent: reproduce a call that broke, fix it, and prove the fix passes, or swap the STT, LLM, or prompt and see what got better and what broke. Every replay is graded against your Pass/Fail evals, and latency is measured on every call. [Learn more →](/docs/simulation/replays) ![A replay run with nine replayed calls, six passed and three failed](https://mintcdn.com/tuner/bVl6uahM1YhEolIF/images/simulation/replays-tab.png?fit=max\&auto=format\&n=bVl6uahM1YhEolIF\&q=85\&s=ede1ba6f055a2469f1ba2b436ac9b542) **Scenario Library** — Keep the simulated calls worth testing again. When a run turns up a call worth keeping, select it and click **Save to library** to save its scenario. Run it again after every change with **Run this scenario**, or pick up to 20 saved scenarios with **From library** in Run Simulation. Each scenario keeps a run history, so you can see whether a fix holds. Works for inbound and outbound agents. [Learn more →](/docs/simulation/scenarios) ![A saved scenario with a run history of three passes out of the last five runs](https://mintcdn.com/tuner/bVl6uahM1YhEolIF/images/simulation/scenario-history.png?fit=max\&auto=format\&n=bVl6uahM1YhEolIF\&q=85\&s=4a1bf79fbf29a086d3dc3396258aa1e5) ![A saved scenario with a run history of three passes out of the last five runs](https://mintcdn.com/tuner/bVl6uahM1YhEolIF/images/simulation/scenario-history.png?fit=max\&auto=format\&n=bVl6uahM1YhEolIF\&q=85\&s=4a1bf79fbf29a086d3dc3396258aa1e5) *** ## September 15, 2026 ### 🧪 Background Noise Simulation **Background Noise Simulation** — Add realistic background noise to any simulation run to test how your agent holds up under real acoustic conditions. Pick an environment and an intensity, and the simulated caller's audio carries continuous noise for the entire call — stressing STT accuracy, endpointing, and barge-in without changing anything about the agent itself. *** ## August 28, 2026 ### 🤖 Simulation Recordings & Eval Library Updates **Simulation Call Recordings** — You can now listen to any simulation call. Tuner records every simulated call, so even when your platform doesn't hand back a recording, there's still audio to review when you're checking what the agent actually said. **Improved Hallucination Detection** — The hallucination judge has been retuned on real deployment patterns so it's less likely to flag claims the transcript or tool responses actually support, so the fails it does report are worth investigating. *** ## August 20, 2026 ### ⚡ OpenTelemetry Traces **OpenTelemetry Traces** — Send spans from LiveKit Agents, Pipecat, or any OTLP-compatible stack and read them as a span tree on the matching call. When the latency stage breakdown doesn't explain a slow turn, the trace shows what ran inside it — the model request, the streaming adapter, each tool call. A Traces tab appears on a call once its spans arrive; conversation content is discarded on arrival and never stored. [Learn more →](/docs/observability/traces) *** ## July 30, 2026 ### 🔒 Data Retention & Call Metadata **Data Retention** — Put an expiry date on your call data. Choose how long Tuner keeps calls — anywhere from 7 days to 1 year, or indefinitely on Enterprise — and how much of the call is removed when that time is up: the transcript and recording, caller details along with them, or the whole record. One setting covers every agent in your workspace, and it applies to calls you already have, so shortening the period will erase older calls. [Learn more →](/docs/observability/data-retention) **Call Metadata** — The call detail page now shows everything Tuner knows about a call in one place: which models handled it, what it cost, and any custom data you sent with it. Useful for spotting cost outliers or tying a call back to the campaign, tenant, or customer record it came from. *** ## July 30, 2026 ### 👋 Guided Onboarding & Vapi Latency Precision **Guided Onboarding** — New users now start on a welcome page that asks why you're here and what you do, so Tuner can tailor the setup to how you work. Answer with a testing or monitoring goal and you go straight into creating your agent. Pick Just exploring and Tuner sets you up with a demo agent and sample data instead. [Learn more →](/docs/getting-started/quickstart) ![The Tuner welcome page asking what brings you to Tuner and what best describes you](https://mintcdn.com/tuner/IPR-UaVVRYc_pqTu/images/changelogs/onboarding_flow.png?fit=max\&auto=format\&n=IPR-UaVVRYc_pqTu\&q=85\&s=6c28665003f79ef6dcf0bed2d5d4789b) **Vapi Latency Precision** — Tuner now reads Vapi's detailed call log alongside the transcript, so latency and interruption timings on Vapi calls match what the caller actually heard. If that log isn't available, the call still comes through from Vapi's summary. [Learn more →](/docs/integrations/vapi) *** ## July 24, 2026 ### 🔒 PII Redaction & Enhanced Voice Metrics **PII Redaction** — Workspace admins on paid plans can now automatically detect and redact sensitive caller data from call transcripts, so it isn't stored verbatim in Tuner. This helps teams pass HIPAA and GDPR reviews. ![PII redaction settings in Tuner, with categories like name, phone number, and credit card](https://mintcdn.com/tuner/IPR-UaVVRYc_pqTu/images/changelogs/pii_redaction_card.png?fit=max\&auto=format\&n=IPR-UaVVRYc_pqTu\&q=85\&s=0b77f19282bde18c61b463974b69fcf8) * **Clean analysis and evidence** — Because Tuner redacts before it analyzes, your outcomes, intents, evals, and the evidence text they cite all run on clean transcripts. Detected entities become typed placeholders: `[NAME]`, `[PHONE_NUMBER]`, `[EMAIL]`, `[ADDRESS]`, `[SSN]`, `[CREDIT_CARD]`, and `[PIN]`. * **Nothing sensitive retained** — Tuner stores, analyzes, and displays the redacted transcript. It does not keep the original. * **Workspace-wide control** — Turn it on in **Workspace Settings → Data & Privacy** and pick which of the 7 categories to redact. The setting applies to every agent in the workspace. * **Applies going forward** — Redaction is permanent and covers only calls ingested after you enable it. Existing calls stay as they are, and simulation calls are never redacted. [Learn more →](/docs/observability/pii-redaction) **Enhanced Voice Metrics** — The Voice Metrics card now breaks down turn-taking latency in more detail. ![End-of-utterance timing shown on a call turn and across all calls in Tuner](https://mintcdn.com/tuner/IPR-UaVVRYc_pqTu/images/changelogs/voice_metrics_card.png?fit=max\&auto=format\&n=IPR-UaVVRYc_pqTu\&q=85\&s=77ace9795a158890c9efebd3c08a150b) * **Catch awkward pauses** — A new End-of-Utterance (EOU) metric shows how long your agent takes to realize the caller has stopped talking, a common cause of dead air and talking over the caller that the STT, LLM, and TTS timings alone don't explain. * **Percentile views** — Toggle p50 and p90 to see turn-taking delays in both typical calls and the slow tail. [Learn more →](/docs/observability/voice-metrics) *** ## July 21, 2026 ### 🪄 Redesigned Agent Creation Flow **Guided Agent Setup** — Creating and connecting an agent is now one guided flow that takes you from connecting your agent to seeing it graded. You finish setup knowing Tuner is working, instead of hoping it is. It replaces the old two-dialog setup and works the same way for every agent, your first or your fiftieth. ![The new guided flow for creating and connecting an agent in Tuner](https://mintcdn.com/tuner/IPR-UaVVRYc_pqTu/images/changelogs/agent_creation_flow_card.png?fit=max\&auto=format\&n=IPR-UaVVRYc_pqTu\&q=85\&s=296dfc20f11e928a7108924d6db60161) * **See it working before you're done** — The flow ends with a real or simulated graded call from your own agent, in the same session. You leave with proof the integration works, not an empty dashboard. * **Less to type, less to get wrong** — For Retell and Vapi, Tuner pulls your agent list from a validated API key and pre-fills the agent name and system prompt, so you're not copying IDs and prompts by hand. * **Never lose your place** — Each step has its own URL, so you can stop and come back later, or hand setup to a teammate, without starting over. * **Never get stuck** — When a control is disabled, it tells you exactly what's missing, so you always know how to move forward. [Learn more →](/docs/getting-started/quickstart) *** ## July 13, 2026 ### 🧩 Custom Stack Observability SDK **Custom Voice Stack Libraries** — Add Tuner observability to any Python voice stack you build yourself, with no pre-built integration required. ![Tuner works with providers including Deepgram, Cartesia, LangGraph, LangChain, Speechmatics, and ElevenLabs](https://mintcdn.com/tuner/IPR-UaVVRYc_pqTu/images/changelogs/custom_sdk_card.png?fit=max\&auto=format\&n=IPR-UaVVRYc_pqTu\&q=85\&s=95826aefb6d8b53b8653535d67ed5528) * **A few lines to wire in** — One session per call, attach observers to the pieces you use (Deepgram, Cartesia, LangGraph, and more), and flush at the end. No new services and no pipeline rebuild. * **Nothing changes at runtime** — Your audio loops, agent logic, and synthesis code keep running exactly as they are. Tuner observes them through each provider's native events without touching the call. * **Full call telemetry** — Captures transcripts, per-stage latency, tool calls, and cost. [Learn more →](/docs/integrations/custom-stack/sdk-quickstart) *** ## July 10, 2026 ### 📋 Agent Templates **Set Up an Agent from a Template** — New agents can now start from a prebuilt template for a common use case instead of a blank slate. ![The Tuner template library, tagged by inbound and outbound call direction](https://mintcdn.com/tuner/IPR-UaVVRYc_pqTu/images/changelogs/agent_templates_card.png?fit=max\&auto=format\&n=IPR-UaVVRYc_pqTu\&q=85\&s=8ae4564ad65df1fb410ef4aab0093270) * **Start with a working config** — Pick the template closest to what your agent does: Customer Support, Appointment Booking, Medical Receptionist, Lead Qualification, and more. * **Useful analysis from the first call** — The template sets up the call outcomes, user intents, evaluations, red flags, alerts, and data-extraction fields that kind of agent usually needs, so Tuner starts producing meaningful analysis right away instead of after hours of manual setup. * **Fully editable** — Nothing is locked, so you shape the template to fit instead of building your configuration from scratch. [Learn more →](/docs/getting-started/quickstart) *** ## July 6, 2026 ### 📊 Call Outcome Library, Voice Metrics Dashboards & Webhooks **Call Outcome Library** — New agents now come with a starter set of call outcomes based on their type, so you're not building your outcome model from scratch. Browse and add more from a searchable library at any time, or create your own custom outcomes. [Learn more →](/docs/evaluation/call-classification#how-to-classify-calls) ![Searchable library of prebuilt call outcomes in Tuner](https://mintcdn.com/tuner/IPR-UaVVRYc_pqTu/images/changelogs/call_outcome_library_card.png?fit=max\&auto=format\&n=IPR-UaVVRYc_pqTu\&q=85\&s=aba35b00f202d4d4c74d4e33380d112d) **Performance Analysis: Voice Metrics** — Voice metrics are now built into the Performance Analysis dashboard. View end-to-end and per-component latency (STT, TTS, LLM) and longest monologue duration as charts, alongside your other performance trends. **Webhook Support** — Add a webhook URL to receive events when call analysis finishes or when an alert fires, so downstream systems stay in sync without polling Tuner. [Learn more →](/docs/integrations/webhooks) ![Choosing Webhook as a notification channel on a Tuner alert](https://mintcdn.com/tuner/IPR-UaVVRYc_pqTu/images/changelogs/webhooks_card.png?fit=max\&auto=format\&n=IPR-UaVVRYc_pqTu\&q=85\&s=eeffb8f44fb6762deb7de3f2431e20ca) *** ## June 25, 2026 ### 🧪 Simulation Test Profiles & Metadata Conditions **Simulation Test Profiles** — Save and reuse a named set of customer data across simulation runs. Define caller properties once — like a name, account number, or appointment date — and attach the profile to any run. The simulated caller draws from it throughout the conversation, which is critical for agents that verify customer identity, and ensures the outbound trigger body and the simulator always share the same source of truth. [Learn more →](/docs/simulation/test-profiles#what-are-test-profiles) ![Creating test profiles and selecting one when running a simulation in Tuner](https://mintcdn.com/tuner/IPR-UaVVRYc_pqTu/images/changelogs/test_profiles_hero.png?fit=max\&auto=format\&n=IPR-UaVVRYc_pqTu\&q=85\&s=f1bfd00d2c200c032f5a943363868e76) **Metadata Conditions in Rules & Alerts** — Custom metadata you send with a call can now power conditions in your red flag rules, label rules, and alert triggers. Use fields like `campaign_id`, `lead_source`, or `user_tier` to control exactly which calls get flagged, labeled, or trigger a notification — alongside built-in conditions and evals. **Pipecat SDK Update** — The latest `tuner-pipecat-sdk` release includes fixes to latency metric capture accuracy, and resolves an issue where consecutive user turns separated by a significant pause were incorrectly merged into a single turn. *** ## June 18, 2026 ### 🔌 Dograh Provider & MCP Fix **Dograh Provider** — Dograh is now available as a selectable provider in the Integrations section, so you can connect your Dograh workflows directly from the Tuner dashboard. ![Tuner and Dograh integration](https://mintcdn.com/tuner/IPR-UaVVRYc_pqTu/images/changelogs/tuner_dograh_card.png?fit=max\&auto=format\&n=IPR-UaVVRYc_pqTu\&q=85\&s=1bbc4de5646a7e597a2923eabe79e7aa) **MCP Fix for Cursor** — Resolved an issue where the Tuner MCP server failed to connect correctly on Cursor clients. *** ## June 16, 2026 ### 🔄 Simulation Redesign, Real-Time Updates & Vapi Outbound Simulation **Revamped Simulations Page** — The simulations page has been redesigned around a runs and scenarios model. You can now see the real-time status of each run, drill into individual scenario results within a run, and get richer failure details to help debug what went wrong. The page updates live — no refresh required. **Real-Time Call Log & Analysis** — New calls now appear in the Call Log as they arrive, and eval and analysis results update instantly as they complete — no more refreshing the page to see the latest state. **Vapi Outbound Agent Simulation** — Run simulations against your Vapi outbound agents. Vapi joins Pipecat, LiveKit, and Custom Integration in the supported outbound simulation lineup. *** ## June 10, 2026 ### ⚡ Pipecat Cost Tracking & Large Call Support **Pipecat SDK Cost Calculation** — Call cost is now automatically calculated and reported for Pipecat-based agents, giving you full usage visibility alongside latency and transcript data. [Learn more →](/docs/integrations/pipecat#configuration-options) **Call Analysis at Any Scale** — Calls with complex or heavily tool-based conversations that previously failed analysis are now fully supported. No calls fall through the cracks regardless of payload size. *** ## June 4, 2026 ### 🔗 LangChain/LangGraph SDK & LiveKit SDK Update **tuner-langchain SDK** — A new SDK for LangGraph and LangChain-based voice agents. Attach one callback handler to your graph and the library automatically captures node transitions, LLM calls, tool invocations, and timing — making your agent's brain layer fully visible in Tuner alongside voice transport data. [Learn more →](/docs/integrations/custom-stack/langchain) ![Tuner with LangChain and LangGraph](https://mintcdn.com/tuner/IPR-UaVVRYc_pqTu/images/changelogs/tuner_langchain_langgraph_card.png?fit=max\&auto=format\&n=IPR-UaVVRYc_pqTu\&q=85\&s=ebc18a6cf43e9e3b3aa2c029fb11fee7) **LiveKit SDK Update** — A new Python `tuner-livekit-sdk` version is available with support for agents that combine LiveKit transport with a LangGraph brain layer using the new `tuner-langchain` library. [Learn more →](/docs/integrations/custom-stack/langchain#attach-to-your-stack) *** ## June 1, 2026 ### 🤖 Outbound Agent Simulation & Diagnose Agent **Outbound Agent Simulation** — Simulate your outbound voice agents end-to-end before shipping to production. Tuner initiates the call to a simulated user, runs it against your configured evals and outcomes, and scores the result automatically. Supported platforms: Pipecat, LiveKit, and Custom Integration. Vapi support coming soon. [Learn more →](/docs/simulation/outbound#how-it-works) ![Outbound simulation trigger endpoint in Tuner](https://mintcdn.com/tuner/IPR-UaVVRYc_pqTu/images/changelogs/outbound_simulation_card.png?fit=max\&auto=format\&n=IPR-UaVVRYc_pqTu\&q=85\&s=f0b16fa761552d58881735f5b8865739) **Diagnose Agent** — A new capability in the Tuner MCP that lets your LLM run a full diagnostic on your voice agent in seconds. The report surfaces an agent health summary, detected issues with root causes and suggested fixes, what's working well, and any data gaps limiting your observability — without manually reviewing calls one by one. [Learn more →](/docs/mcp/diagnose) ![Tuner diagnose: trace red flags, hallucinations, and latency back to a root cause](https://mintcdn.com/tuner/IPR-UaVVRYc_pqTu/images/changelogs/diagnose_card.png?fit=max\&auto=format\&n=IPR-UaVVRYc_pqTu\&q=85\&s=0b35b3ce57f872add0b47505a698b93f) *** ## May 22, 2026 ### 🌍 Simulation Language Support, Node.js LiveKit SDK & Pipecat v1 **Simulation Language & Accent Support** — The simulation environment now supports a wider range of languages and regional accents, so you can test your agent across diverse user demographics without changing your evaluation setup. Supported languages include English (US, UK, Australian), Arabic (Egyptian, UAE, Saudi Arabian), French (France, Canadian), Spanish (Spain, Mexican), German (Germany, Austrian, Swiss), and Italian. **Node.js LiveKit SDK** — The `tuner-livekit-sdk` is now available for Node.js. Connect your LiveKit agents to Tuner in two lines of code — session data including transcripts, usage, latency, and cost is captured and pushed to Tuner automatically when each session ends. [Learn more →](/docs/integrations/livekit) **Pipecat v1 Support** — The `tuner-pipecat-sdk` has been updated to support Pipecat v1, keeping your monitoring pipeline compatible with the latest Pipecat release. [Learn more →](/docs/integrations/pipecat) **Dograh Integration** — Connect your Dograh voice workflow to Tuner in minutes. Add the Tuner node to your workflow, create a Dograh agent in Tuner, and paste in your credentials — completed calls are exported automatically for analysis, evaluation, and monitoring. [Learn more →](/docs/integrations/dograh) *** ## May 15, 2026 ### 🤖 Simulation **Simulation** — Test your voice agent against a realistic simulated user before shipping to production. Tuner automatically generates caller scenarios based on your agent's configuration — no manual setup required. Each simulated call is evaluated against your configured evals and outcomes, so you can catch regressions, validate prompt changes, and stress-test edge cases without involving real users. [Are You Manually Calling Your Voice Agent? There's a Better Way](https://www.youtube.com/embed/-P0rtvHepgA) Key Features: * **Auto-generated scenarios** — Tuner generates caller scenarios from your agent configuration and use case selections, so simulations are always grounded in your agent's actual context * **Functional & pressure testing** — Control the mix between functional tests that validate core use cases and adversarial pressure tests that probe failure modes and edge cases * **Targeted runs** — Run simulations against a specific use case or a specific eval to isolate and validate exactly what you're working on * **Automated evaluation** — Each simulated call is scored against your existing evals, outcomes, and red flags *** ## April 2, 2026 ### 😊 Auto Sentiment Detection **Auto Sentiment Detection** — Sentiment is now automatically detected and added as a default metric for every call — no configuration required. Tuner analyzes the conversation to surface caller sentiment signals, giving you an immediate read on call quality and user experience trends across your full call volume. *** ## March 23, 2026 ### 📊 Enhanced Voice Metrics, Vapi Integration & Webhook Support **Enhanced Voice Metrics** — The voice metrics dashboard now includes a detailed breakdown of latency by component — STT, TTS, and LLM — so you can pinpoint exactly where delays are introduced in your pipeline. Metrics are reported at the p50 and p90 percentiles, giving you a clearer picture of both typical performance and tail latency across your call volume. ![Transcript tool call view and voice metrics breakdown](https://mintcdn.com/tuner/IPR-UaVVRYc_pqTu/images/changelogs/transcript_tool_calls_latency.png?fit=max\&auto=format\&n=IPR-UaVVRYc_pqTu\&q=85\&s=14ab6187e014c6087ab8e77bfdc12056) **Vapi Integration** — Connect your Vapi agents to Tuner with native platform support. Call data — transcripts, latency, evaluations, and cost — is captured and pushed to Tuner automatically for every Vapi-powered session. [Learn more →](/docs/integrations/vapi) **Webhook Support for Retell & Vapi** — You can now register additional webhooks in Tuner alongside your existing Retell and Vapi configuration. Tuner now forwards call payloads to your webhook URL after processing, so your existing automations keep running alongside Tuner without any changes.[Learn more →](/docs/integrations/webhooks) ![Webhook proxy settings in Tuner](https://mintcdn.com/tuner/IPR-UaVVRYc_pqTu/images/changelogs/feature_webhooks.png?fit=max\&auto=format\&n=IPR-UaVVRYc_pqTu\&q=85\&s=4b56be0c391ffab286c44d816f4ea409) *** ## March 19, 2026 ### 🔌 LiveKit & Pipecat SDKs, and Transcript Improvements ![Tuner integrates with Vapi, Retell, LiveKit, Pipecat, and more](https://mintcdn.com/tuner/IPR-UaVVRYc_pqTu/images/changelogs/integrations_voice_stack.png?fit=max\&auto=format\&n=IPR-UaVVRYc_pqTu\&q=85\&s=991300c0af7c09b2449b7f5548eed4cb) **LiveKit SDK** — Connect your LiveKit Agents to Tuner in two lines of code. The `tuner-livekit-sdk` automatically captures session data — transcripts, usage, latency, and cost — and pushes it to Tuner when each session ends. No manual API calls required. [Learn more →](/docs/integrations/livekit) **Pipecat SDK** — Monitor your Pipecat pipelines with the new `tuner-pipecat-sdk`. The `Observer` captures flow transitions, latency signals, transcripts, and usage metadata, then sends a structured call payload to Tuner when the call ends. [Learn more →](/docs/integrations/pipecat) **⚙️ Agents API** — Create, retrieve, and update your agents programmatically via API. [Learn more →](/docs/api-reference/list-agents) **📋 Transcript Function Call View** — Tool calls now appear inline in the transcript with their input arguments and output responses, making it easier to debug unexpected agent behavior. *** ## March 10, 2026 ### 🔗 Metadata-Linked Evals & MCP Improvements **Metadata-Linked Evals** — Evals can now reference call metadata, so they stay accurate even when agent instructions change per session or tenant. Attach any runtime context when pushing calls (instructions, tenant config, session properties) and each call is evaluated against its own context, not a shared static policy. [Learn more →](/docs/evaluation/dynamic-agents) ![Metadata-linked behavior checks](https://mintcdn.com/tuner/IPR-UaVVRYc_pqTu/images/changelogs/metadata_linked_evals.png?fit=max\&auto=format\&n=IPR-UaVVRYc_pqTu\&q=85\&s=98cfac46b8972cb07bd342ee9dbb0c66) **Tuner MCP Improvements** — Enhanced the MCP prompt with deeper understanding of your agent's context. It now suggests more comprehensive configuration across outcomes, intents, evals, red flags, and data extraction, plus ships with richer built-in templates so your initial setup is closer to production-ready out of the box. *** ## February 25, 2026 ### ⚡ Tuner MCP Manage your agent’s observability configuration directly from your IDE or AI assistant using natural language. Tuner MCP lets you connect Tuner to tools like Cursor, Claude, Claude Code, and Antigravity — so you can manage your tuner agent without leaving your workflow. ![Tuner MCP](https://mintcdn.com/tuner/IPR-UaVVRYc_pqTu/images/changelogs/tuner_mcp.gif?s=8ae7692838a68165fbc757b0405e2a1b) **Key Features:** * Set up observability for a new agent in minutes using natural language setup * IDE Integration — configure Tuner from your development environment with API-key authentication * Chat-Based Management — connect via OAuth and manage your agent through conversational prompts * Iterate on your agent evaluations without leaving your workflow 👉 [Learn more](/docs/mcp/setup) *** ## February 18, 2026 ### 📝 Call Log Transcript View View the full conversation transcript directly from the Call Log details page — with speaker labels and timestamps. **Use Cases:** * Review exactly what was said during a flagged or failed call * Verify agent responses against expected behavior * Share transcript excerpts with your team for coaching or debugging *** ## February 13, 2026 ### 🔔 Real-Time Alerts Get notified via Email when red flags, evaluation failures, or specific conditions are detected in your calls. ![Real-time alerts](https://mintcdn.com/tuner/IPR-UaVVRYc_pqTu/images/changelogs/realtime_alerts.jpeg?fit=max\&auto=format\&n=IPR-UaVVRYc_pqTu\&q=85\&s=5ed4a1f30ef3b18faf539624ed4e6b89) **Key Features:** * **Red Flag & Evaluation Triggers** — fire alerts on hallucination, dead air, failed evals, and more * **Configurable Conditions** — set thresholds and filters to control when alerts are sent 👉 [Learn more](/docs/observability/alerts) *** ## February 9, 2026 ### 🚨 Red Flags & Issue Triage Automatically detect critical issues across your calls — Hallucination, Early Hangup, Dead Air, Intent Missed, and High Latency. ![Red Flags](https://mintcdn.com/tuner/IPR-UaVVRYc_pqTu/images/changelogs/red_flags.jpeg?fit=max\&auto=format\&n=IPR-UaVVRYc_pqTu\&q=85\&s=a54897d264a5127b1af4e7f6be28736e) **Use Cases:** * Triage the most critical issues first by filtering calls by red flag type * Track red flag frequency over time to measure the impact of changes * Investigate root causes by reviewing flagged transcripts alongside agent settings 👉 [Learn more](/docs/evaluation/red-flags) *** ## February 5, 2026 ### 📊 Performance & Behavior Dashboards Two purpose-built dashboards for full visibility into your agent — from high-level trends to granular behavior analysis. **Key Features:** * **Performance Analysis** — track call volume, success rates, and key metrics over time * **Behavior Analysis** — surface pass/fail rates for evals and spot recurring red flags * **Time-Range Filters & Agent Drill-Down** — isolate data by date range or specific agent *** ## February 3, 2026 ### 🔌 Public API & Custom Integration Send call data from any voice platform to Tuner with a single `POST` request — no pre-built integration required. **Key Features:** * **Single-Endpoint API** — one request to push transcripts, metadata, and properties * **Platform Agnostic** — works with any voice platform or custom-built system * **User Sentiment Support** — include caller sentiment for richer analysis 👉 [Learn more](/docs/api-reference/create-call) *** ## February 1, 2026 ### 🎉 Tuner Launch Tuner is live — the observability and monitoring platform built for voice AI agents. Full visibility into every call your agent handles. **Key Features:** * **End-to-End Call Monitoring** — every call is captured, transcribed, and analyzed automatically * **Configurable Evaluations** — define call outcomes, user intents, and evals tailored to your agent * **Native Integrations** — connect directly to Retell, VAPI, Bland, and more with one-click setup * **Credit-Based Pricing** — pay only for what you use, with a free tier to get started 👉 [Get started](/docs/getting-started/welcome-to-tuner) # Add Dataset calls Source: https://docs.usetuner.ai/docs/datasets/add-calls Pick a real production call or upload a recording. Tuner finds the caller, cuts their side into turns, and gets the call ready to replay. > [!NOTE] > > Your Dataset lives on the **Dataset** tab under **Simulations**. Adding a call from production is free. Uploads are billed per minute of audio. Add a real call to your Dataset: either one Tuner recorded from your agent, or a recording you upload. Tuner keeps only the caller's side, split into turns (each thing the caller said), and gets the call ready to replay. ## Add a call Open the dialog, name the call, choose a source, and extract it. Only step 3 depends on your source. **1. Open the dialog** Go to **Simulations > Dataset** and click **Add call**. **2. Name the call** Enter a **Name**: required, up to 255 characters, and unique for this agent. Add a **Description** if you like, up to 1,000 characters, saying what makes the call worth replaying. It shows on the call's card. **3. Choose a source** Choose **Production** for a call Tuner already recorded from your agent, or **Upload** for an audio file you already have. > [tab] Production > > Once your voice agent is connected to Tuner, the real calls it takes show up in Tuner with a recording and a transcript. With this option, you pick one of those calls and add it to your Dataset. It's the quickest way to save a call that went wrong, because everything Tuner needs is already there. > > ![Add call dialog with a production call selected](https://mintcdn.com/tuner/SUvdaDyWHmpRoVGZ/images/datasets/add-call-production.png?fit=max\&auto=format\&n=SUvdaDyWHmpRoVGZ\&q=85\&s=4535db08dbfd88dd892a6c96527a2641) > > * **Cost:** free. > * Click the call you want from the list. The newest calls come first, and you can search by call ID. > * Only calls that have both a recording and a transcript are listed. A recording link counts only if it's a public `https://` URL. Calls sent with a placeholder link, such as `pending`, aren't listed. Simulation test calls aren't listed either, but you can [save one as a scenario](/docs/simulation/scenarios#save-to-library-from-a-run) and run it again instead. > * Tuner already knows which side is the caller, so there's nothing to pick. > * Prefer calls marked **Multi-channel**, where the caller and your agent are recorded separately. On a **Mono source** call, the agent's voice can bleed into the caller's turns. > [tab] Upload > > Already have recordings of real calls, from another system or from before you started using Tuner? Upload them as audio files and add them to your Dataset. Your agent doesn't need to have taken any calls in Tuner yet, so you can start on day one. You just tell Tuner which side of the recording is the caller. > > ![Add call dialog with an uploaded recording and the caller channel picker](https://mintcdn.com/tuner/SUvdaDyWHmpRoVGZ/images/datasets/add-call-upload.png?fit=max\&auto=format\&n=SUvdaDyWHmpRoVGZ\&q=85\&s=fa00c2f0dc6ec7256b48ab24849f522f) > > * **Cost:** 1.5 credits per minute of audio, shown as an estimate before you extract. You're charged once, when the call is **Ready**, and nothing is charged if it fails or you cancel. > * Drop your file in, or click **browse**. It can be wav, mp3, m4a, flac, ogg, or webm, up to 200 MB and 30 minutes. > * The file must be stereo, with the caller on one channel and your agent on the other. Mono files, with everything mixed together, are rejected. > * Click **Analyze audio**. Tuner uploads and checks the file, usually in under two minutes, so keep the dialog open. If the upload is interrupted, click **Try again**. > * Play the one-minute sample of each channel and pick the one with the caller. **4. Extract the call** Optional: expand **Advanced extraction** to change how the caller's speech is cut (see [Advanced extraction](#advanced-extraction)). Then click **Extract call**. **5. Wait for Ready** The call appears on the Dataset tab as **Extracting**, which updates on its own. It's usually **Ready** within a minute, and then it can be replayed. If it shows **Failed**, see [Troubleshooting](#troubleshooting). *** ## After you add a call ### Check the status | Status | What it means | | - | - | | **Extracting** | Tuner is preparing the call. It can't be replayed yet. | | **Ready** | The call can be previewed and replayed. | | **Failed** | Nothing was extracted. The reason shows on the card. | ### Review the caller turns Click the headphones icon on a **Ready** call to open its turns. Each turn shows its position in the original recording, its duration, its reference transcript, and whether that transcript is **Draft** or **Verified**. Click play to hear just that turn. For production calls, **View source call** opens the original call. ![The caller turns of a Dataset call, each with a play button, time range, and transcript](https://mintcdn.com/tuner/SUvdaDyWHmpRoVGZ/images/datasets/caller-turns.png?fit=max\&auto=format\&n=SUvdaDyWHmpRoVGZ\&q=85\&s=aa20967892e713fd0492b255ea197f90) Before you rely on a call, listen for: * **Clipped words** at the start or end of a turn: raise **Padding** and re-extract. * **Agent speech inside a caller turn**: common with mono sources. Pick a multi-channel call if you can. * **Turns that are split or merged in the wrong place**: adjust **Merge gap** or **Minimum turn** and re-extract. ### Edit and verify transcripts Tuner writes a draft reference transcript for every caller turn. When a call is [replayed](/docs/simulation/replays), Tuner compares these transcripts with what your agent heard to score [transcription accuracy](/docs/observability/voice-metrics#transcription-accuracy). Check that each transcript matches what the caller said. A wrong reference transcript makes the score wrong. **1. Open the turns** Click the headphones icon on a **Ready** call. The header shows how many turns are verified, like **7 of 10 verified**. Unverified turns are listed first. ![A Dataset call with four caller turns, two Verified and two Draft, and the header showing 2 of 4 verified](https://mintcdn.com/tuner/Z16wBZIv2BPLqt5V/images/datasets/verify-transcripts.png?fit=max\&auto=format\&n=Z16wBZIv2BPLqt5V\&q=85\&s=7ba1d351f004e272de85ba9f01b0c5c6) **2. Listen and read** Click play on a turn and read its transcript. To see only some turns, use the filter: **All**, **Draft** or **Verified**. **3. Verify or correct it** If the transcript is right, click **Verify**. If it needs changes, click **Edit**, change the text, and click **Save and verify**. Click **Cancel** to discard your change. ![A caller turn open for editing, with the transcript in a text box and the Save and verify and Cancel buttons below it](https://mintcdn.com/tuner/Z16wBZIv2BPLqt5V/images/datasets/edit-transcript.png?fit=max\&auto=format\&n=Z16wBZIv2BPLqt5V\&q=85\&s=0b81f69a95a3985f35feb11174a2274e) | State | What it means | | - | - | | **Draft** | Tuner wrote the transcript, and nobody has checked it. | | **Verified** | You checked the transcript, or saved your own text. | * Saving an edit always marks the turn **Verified**. To undo that, click **Unverify** on the turn. * A transcript can be empty, for a turn where the caller said nothing. * Editing or verifying never recalculates earlier replays. Open the call and click **Recalculate**. See [Outdated scores](/docs/observability/voice-metrics#outdated-scores). * Only **Ready** calls can be edited. ### Re-extract a call If the turns come out wrong, cut the call again with different settings. Click the refresh icon on a production call. Tuner creates a **new** Dataset call from the same recording and suggests a versioned name, like **Billing dispute, Feb 4 v2**. The original stays as it is, so earlier replays remain comparable. Your edits stay on the original. Every turn of the new call starts as **Draft**. * The extraction settings start from the defaults, so set them again before you extract. * Uploaded calls can't be re-extracted. Upload the file again instead. ### Advanced extraction These settings are in the **Add call** dialog, and you set them again when you re-extract. The defaults suit most calls. ![Advanced extraction settings with the default values](https://mintcdn.com/tuner/tyvTCHhRxonDc171/images/datasets/extraction-settings.png?fit=max\&auto=format\&n=tyvTCHhRxonDc171\&q=85\&s=86eaa00f83fd87bc8dfbffd244260183) | Setting | Default (range) | What it does | | - | - | - | | **Merge gap (ms)** | 400 (0 to 5,000) | Merges caller turns that are closer together than this. Raise it if a caller who pauses mid-sentence gets split into several turns. Lower it if separate answers get merged. | | **Minimum turn (ms)** | 300 (50 to 5,000) | Drops caller turns shorter than this as noise. Lower it to keep short answers like "yes" or "no". Raise it to drop coughs and background sounds. | | **Padding (ms)** | 120 (0 to 2,000) | Adds silence before and after each turn so the first and last word aren't clipped. Raise it if turns start or end mid-word. | **Merge gap** isn't used for uploads, or for multi-channel LiveKit, Pipecat, Dograh, and Custom API calls, which merge automatically unless the agent speaks in between. **Padding** is always 0 for mono sources. ### Delete a call Click the trash icon and confirm. The call can no longer be replayed, but runs that already replayed it keep their results. Its name becomes available again. *** ## Add calls with the API You can also build your Dataset from code, for example to add every escalated call as it happens. The endpoints are in the **Replay testing** group of the API Reference, which has the request details and examples. > [tab] From production > > 1. Find the call with [List Source Call Candidates](/api-reference/replay-testing/list-source-call-candidates). > 2. Create the Dataset call with [Create Voice Clip Set](/api-reference/replay-testing/create-voice-clip-set). > 3. Poll [Get Voice Clip Set](/api-reference/replay-testing/get-voice-clip-set) until the call is ready or failed. > [tab] From an upload > > 1. Start the upload with [Start Voice Clip Upload](/api-reference/replay-testing/start-voice-clip-upload). The response gives you upload URLs for the parts of your file. > 2. Upload each part to its URL, then finish with [Complete Voice Clip Upload](/api-reference/replay-testing/complete-voice-clip-upload). > 3. Poll [Get Voice Clip Upload](/api-reference/replay-testing/get-voice-clip-upload) until the audio is analyzed. To check which channel is the caller, listen to each channel with [Get Voice Clip Upload Channel Sample URL](/api-reference/replay-testing/get-voice-clip-upload-channel-sample-url). > 4. Create the Dataset call with [Create Voice Clip Set](/api-reference/replay-testing/create-voice-clip-set), naming the caller's channel, then poll [Get Voice Clip Set](/api-reference/replay-testing/get-voice-clip-set) until it's ready. Both ways accept the same extraction settings as [Advanced extraction](#advanced-extraction). Uploads cost the same as in the app; see [Credits and usage](/docs/resources/credits). To edit or verify a turn's transcript from code, use [Edit or Verify a Voice Clip](/api-reference/replay-testing/edit-or-verify-a-voice-clip), in the same **Replay testing** group. *** ## Limits | Limit | Value | | - | - | | Transcript length per caller turn | 5,000 characters | *** ## Troubleshooting > [accordion] A call shows Failed > > Nothing was extracted, and the reason shows on the call's card. Common reasons: > > | Message | What to do | > | - | - | > | Source call has no recording (mono or multi-channel) to extract audio from. | Pick a call that has a recording. | > | The source call's recording link isn't a usable https link, so this Dataset call can't be built. | The call was sent with a placeholder or non-public link. Pick another call, or send a public `https://` recording URL for future calls. | > | The source call's recording link can't be reached as a public https link, so this Dataset call can't be built. | The link's host doesn't exist or points to a private address. Pick another call. | > | The source call's recording link can't be downloaded (HTTP 404), so this Dataset call can't be built. | The link returned a redirect or a 4xx error, shown in the message. Redirects aren't followed. Check that the recording still exists at that link, or pick another call. | > | Source call has no transcript; cannot extract caller turns. | Pick a call that has a transcript. | > | No usable caller turns were found in the source call's transcript. | The caller barely spoke, or every turn was shorter than **Minimum turn**. Lower it and try again, or pick another call. | > | No speech was found on the selected channel. | You may have picked the agent's channel. Upload the file again and pick the other channel. | > [accordion] An upload is rejected > > The file is checked during analysis, before you extract. > > | Message | What to do | > | - | - | > | Only stereo recordings with the caller and agent on separate channels are supported for now. | Export a stereo recording from your platform. | > | This file has more than two channels. | Upload a stereo recording with the caller and agent on separate channels. | > | This file is longer than the 30 minute limit. | Trim the recording to the part you want to replay. | > | We could not read this audio file. | Upload a valid wav, mp3, m4a, flac, ogg, or webm file. | *** ## Next steps > [card] [Replays](/docs/simulation/replays) > > Replay your Dataset calls against your agent and read the results. > [card] [Dataset best practices](/docs/datasets/best-practices) > > How to choose, name, and maintain calls so every replay tells you something. # Dataset best practices Source: https://docs.usetuner.ai/docs/datasets/best-practices How to choose, name, and maintain Dataset calls so every replay tells you something you can act on. ## Start from a question Every Dataset call should answer something specific. Is the new STT better with accents? Did the prompt fix stop the made-up policy? Does booking still work after the tool change? If you can't name the question a call answers, it probably doesn't belong in the set. *** ## Name calls so they group Your agent has one Dataset, and you pick which calls to replay together. Put the purpose at the front of each name so the set you need is easy to find in **New Replay**: | Prefix | Use it for | Example | | - | - | - | | `[latency]` | Stack and speed checks | **\[latency] Order status, road noise** | | `[stt]` | Transcription checks | **\[stt] Account number, Scottish accent** | | `[eval]` | Behaviour and policy checks | **\[eval] Made-up refund policy** | | `[tool]` | Tool-calling checks | **\[tool] waive_late_fee error** | | `[golden]` | Calls that must keep working | **\[golden] Standard booking** | Use the **Description** to note why the call is in the set, like "Agent promised a refund the policy doesn't allow". Names are unique per agent. *** ## Keep calls short and focused Shorter calls replay faster, cost less, and fit within the **Max call duration**. Each caller turn can add up to the **Max wait** of waiting for your agent, so with the default settings a 3-minute cap fits roughly 8 caller turns. The **Longest possible call** line in **New Replay** tells you before you run whether a call fits. If only part of a long call matters, upload a trimmed recording of that part instead. *** ## Prefer multi-channel recordings A **Multi-channel** call keeps the caller on their own channel, so the replay is clean. A **Mono source** mixes caller and agent, so fragments of the original agent can leak into the caller's turns, and your agent will hear them. Use mono calls only when there's no better recording, and listen to them first. *** ## Listen before you trust Open every new call with the headphones icon and play a few turns. Check for clipped words, agent speech inside a caller turn, and turns split in the wrong place. A bad cut makes every replay of that call misleading. See [Review the caller turns](/docs/datasets/add-calls#review-the-caller-turns). *** ## Verify transcripts before you trust the score Tuner scores a replay's transcription accuracy against each caller turn's reference transcript, and writes a draft of it. A wrong draft makes the score wrong. Read each transcript while you listen, then click **Verify**, or fix it and click **Save and verify**. See [Edit and verify transcripts](/docs/datasets/add-calls#edit-and-verify-transcripts). *** ## Keep your failures, and some golden calls Every call your agent got wrong is a test you get for free. Add it, fix the agent, and keep replaying it so the failure can't come back unnoticed. Balance failures with a few golden calls your agent handles well today, so fixes that break something else show up too. *** ## Replay more than once Your agent's responses vary from run to run even when the caller doesn't. Replay each call 3 to 5 times: * Failing every time means the problem is consistent. * Failing now and then means it's intermittent, and one passing replay after a fix doesn't prove much. The limit is 20 replayed calls per run, counting repeats, so 4 calls replayed 5 times fits in one run. *** ## Change one thing at a time Between two runs you compare, change only one thing, and keep the same calls, repeats, **Max call duration**, and **Advanced turn-taking** settings. Then any difference has one cause. See [Compare two setups](/docs/datasets/use-cases/benchmarking#compare-two-setups). *** ## Remember the caller doesn't adapt The caller says what they said in the original call, whatever your agent answers now. Pick calls where the behaviour you're testing happens early, and write evals about the agent's turns, not about how the conversation ends. See [The caller doesn't adapt](/docs/datasets/use-cases/capturing-failures#the-caller-doesnt-adapt). *** ## Protect your tools and data Replays reach your real agent, and your agent calls its real tools. Point it at test endpoints or test accounts before replaying calls that book, charge, refund, or change records. See [Check a tool call on a replay](/docs/datasets/use-cases/capturing-failures#check-a-tool-call-on-a-replay). *** ## Refresh the set Add calls when you launch new Intents, enter a new market, or see a new kind of failure in production. Delete calls that no longer match how your product works. Past runs keep their results after you delete a call. *** ## Mind privacy Dataset calls keep your callers' real voices and words, and a Dataset call keeps its own copy of the caller's audio even if the source call is later removed. Add only calls you're allowed to reuse for testing, and delete the ones you no longer need. *** ## Keep an eye on cost | Action | Cost | | - | - | | Adding a call from production | Free | | Adding an uploaded recording | 1.5 credits per minute of audio, charged once the call is **Ready** | | Replaying calls | The same per-minute simulation rate as generated runs, shown in **New Replay** before you run | ## Next steps > [card] [Add Dataset calls](/docs/datasets/add-calls) > > Pick production calls or upload recordings. > [card] [Replays](/docs/simulation/replays) > > Replay your Dataset calls against your agent. # Introduction to Datasets Source: https://docs.usetuner.ai/docs/datasets/overview Save real calls and replay them against your agent with the exact same caller audio. Reproduce the call that failed, prove your fix, and pick your stack on your own calls. > [!NOTE] > > Build Datasets on the **Dataset** tab and replay them from the **Replays** tab, both under **Simulations**. You need an agent set up for [inbound](/docs/simulation/inbound/setup) or [outbound](/docs/simulation/outbound) simulation. ## What is a Dataset? A Dataset is a set of real calls you save to test your agent. Each saved call, a Dataset call, keeps only what the caller said, cut into turns. When you replay it, Tuner calls your agent and plays those turns back, and your agent answers as it would on a real call. The caller never changes, so when a result changes, your agent changed. The loop is simple: save a call, replay it, change your agent, and replay it again. ![The Dataset tab with calls that are Ready, Extracting, and Failed](https://mintcdn.com/tuner/SUvdaDyWHmpRoVGZ/images/datasets/dataset-tab.png?fit=max\&auto=format\&n=SUvdaDyWHmpRoVGZ\&q=85\&s=4feee0bc6e87c8d81dfc86380c8925fc) *** ## Why use a Dataset Most teams use a Dataset for two things. ### Reproduce the call that failed Prove your fix on the exact call that broke. * Save the call that failed, like a noisy line where your agent misheard a date. * Replay it to see the failure, fix your agent, then replay it again. * Keep it in your Dataset as a test, so the failure can't quietly come back. ![The same Dataset call replayed three times before the fix, failing every time, and three times after it, passing every time](https://mintcdn.com/tuner/SUvdaDyWHmpRoVGZ/images/datasets/fix-before-after.png?fit=max\&auto=format\&n=SUvdaDyWHmpRoVGZ\&q=85\&s=4c6754303d4679a0993f0d7884486843) > [card] [Capturing failures](/docs/datasets/use-cases/capturing-failures) > > From failure to verified fix, step by step. ### Pick your stack on your own calls Build your own benchmark to test a new model or provider on your callers before you switch. * Public benchmarks use generic audio, not your callers or your stack. * Save your typical and hardest calls to your Dataset. That's your benchmark. * Replay it on your current setup and on the new one: same calls, same scoring, latency measured on every run. ![Two replay runs of the same three calls: all three pass on the new setup, two fail on the current one](https://mintcdn.com/tuner/SUvdaDyWHmpRoVGZ/images/datasets/compare-setups.png?fit=max\&auto=format\&n=SUvdaDyWHmpRoVGZ\&q=85\&s=dde9686b274fa56558aea506a91baf9c) > [card] [Benchmarking](/docs/datasets/use-cases/benchmarking) > > How to build your benchmark and compare two setups. *** ## How a Dataset works Either way, you start with real calls in your Dataset. **1. Add a Dataset call** **Start on day one with your own calls**, or use real calls Tuner recorded from your agent. Open **Simulations > Dataset**, click **Add call**, name it, and pick a source. > [card] [Upload your own calls](/docs/datasets/add-calls#add-a-call) > > Audio recordings you already have, even before your agent takes any calls in Tuner. Stereo, 1.5 credits per minute. > [card] [Pick a production call](/docs/datasets/add-calls#add-a-call) > > A real call your agent took that Tuner recorded, like one that just failed. Free. **2. Tuner extracts the caller** It keeps only the caller's side, cut into **caller turns**. The call shows as **Extracting**, then **Ready**, usually within a minute. **3. Check the turns** Click the headphones icon to listen to each turn and check its transcript before you rely on the call. You can [edit and verify](/docs/datasets/add-calls#edit-and-verify-transcripts) each transcript. ![The caller turns of a Dataset call, each with a play button, time range, and transcript](https://mintcdn.com/tuner/SUvdaDyWHmpRoVGZ/images/datasets/caller-turns.png?fit=max\&auto=format\&n=SUvdaDyWHmpRoVGZ\&q=85\&s=aa20967892e713fd0492b255ea197f90) > [card] [Add a Dataset call](/docs/datasets/add-calls) > > Upload your own recording or pick a production call. *** ## How a Dataset is used Your Dataset is built. Now use it in a **Replay**, a separate feature under Simulations. Tuner calls your agent and plays back the caller turns, like a live call, then grades each call against your Pass/Fail evals and measures latency. ![Picking Dataset calls in New Replay and choosing how many times to replay each one](https://mintcdn.com/tuner/bVl6uahM1YhEolIF/images/datasets/step-replay.png?fit=max\&auto=format\&n=bVl6uahM1YhEolIF\&q=85\&s=a7bdf1206c42bd4a4c5bbd0f8a97ebf3) > [card] [Replays](/docs/simulation/replays#replay-a-dataset-call) > > Run a replay, read the results, and compare runs. *** ## FAQ > [accordion] What's inside a Dataset call? > > | Part | What it is | > | - | - | > | **Caller turns** | Each stretch of the caller speaking, played in order during a replay | > | **Caller audio** | A caller-only track, the audio your agent hears | > | **Reference transcript** | What the caller said in each turn. You can edit it and mark it **Verified**. Replays use it to score [transcription accuracy](/docs/observability/voice-metrics#transcription-accuracy). | > | **Channel mode** | **Multi-channel**, or **Mono source** when the agent's voice can bleed in | > | **Status** | **Extracting**, **Ready**, or **Failed** with a reason | > [accordion] How is a Dataset different from generated simulations? > > | | Generated simulations | Replays of Dataset calls | > | - | - | - | > | **Caller** | A Simulated Caller that improvises | The recorded caller from a real call | > | **Same caller every run?** | No | Yes | > | **Best for** | Finding new failure modes | Reproducing a call, proving a fix, comparing setups | > > Found a failure in a generated run? [Save its scenario to your library](/docs/simulation/scenarios#save-to-library-from-a-run) and run it again. > [accordion] How should I choose and name calls? > > Start from a question each call answers, and add a prefix like **\[stt]**, **\[tool]**, or **\[eval]** so related calls group together. See [Dataset best practices](/docs/datasets/best-practices). > [accordion] Does adding a call cost credits? > > Production calls are free. Uploads cost **1.5 credits per minute** of audio, charged when the call is **Ready**. Replays use the standard simulation rate. See [Credits and usage](/docs/resources/credits). > [accordion] Can I edit a Dataset call? > > You can edit and verify the reference transcript of each caller turn. See [Edit and verify transcripts](/docs/datasets/add-calls#edit-and-verify-transcripts). The caller audio and the turns can't be changed, so every replay stays comparable. To cut a call differently, re-extract it, or upload the file again if it was an upload. The original stays as it is. > [accordion] Which agents can replay a Dataset? > > Inbound and outbound agents. Outbound simulation isn't available for Retell and Dograh, so those agents replay inbound only. # Benchmark your stack on your own calls Source: https://docs.usetuner.ai/docs/datasets/use-cases/benchmarking Test a new model or provider on your own callers, in your own stack, before you switch. Same calls, same scoring, latency measured on every run. There's a new model every week. It tops the leaderboard, and a few days later another one takes its place. A leaderboard can't tell you if that model is right for your agent. Public benchmarks run on generic audio that may overlap with what the models were trained on. Your callers are specific: their language, their accents, their background noise, your industry's words. And a model never runs alone. Turn detection, orchestration, and noise handling change how the same model performs, and the latency your caller actually feels. So test it on your calls, in your stack. Replay the same Dataset calls on your current setup and on the one you're considering, and compare the results. Same calls, same scoring, latency measured on every run. That's your own benchmark: built on your data, for your use case, and it doesn't change every week. *** ## What to collect | What you're comparing | Calls to add | What to look at after a replay | | - | - | - | | **Response latency** | Ordinary calls of normal length, a few for each of your top Intents | The **Voice Metrics** tab of each replayed call, and the latency badges on each agent turn in the transcript | | **Speech-to-text accuracy** | Accents, fast talkers, names, numbers, addresses, your industry's vocabulary | The **Transcription accuracy** card on the **Voice Metrics** tab of each replayed call, and its **What went wrong** list | | **Turn detection** | Callers who pause mid-sentence, hesitate ("um, so..."), trail off, or answer with a single word | Whether the agent jumped in before the caller finished, or waited too long to answer | | **Interruptions** | Callers who talk over the agent | How the agent handles being talked over. A replay always plays each caller turn in full, even if the agent is still speaking. | | **Noise and line quality** | Calls from the car, the street, a café, speakerphone, or a bad line | Transcription errors and turns cut off by background sound | Cover your real mix. If a third of your callers phone from the car, a third of these calls should too. ![A benchmark Dataset of strong accents, road noise, a fast talker, a caller who talks over the agent, and an ordinary booking call](https://mintcdn.com/tuner/SUvdaDyWHmpRoVGZ/images/datasets/bench-dataset.png?fit=max\&auto=format\&n=SUvdaDyWHmpRoVGZ\&q=85\&s=290914fa378bea899a5090978ce2f7fa) Replays don't add simulated noise, change the language, or apply a test profile. The recording already carries the real conditions. To test conditions you don't have recordings for, use a [generated simulation](/docs/simulation/run-a-simulation) with background noise or a different accent. *** ## Compare two setups **1. Pick the calls** Choose the Dataset calls that cover what you're changing, up to 10 per run. Keep the same set for every run in the comparison. **2. Record a baseline** Replay each call 3 to 5 times on your current setup. Repeats show you how much results vary on their own, before you change anything. **3. Swap one thing** Swap in the new speech-to-text model, LLM, or TTS voice, or adjust your turn detection or endpointing. Only one change, so any difference has one cause. **4. Replay the same calls** Use the same calls, the same number of repeats, the same **Max call duration**, and the same **Advanced turn-taking** settings. **5. Compare the runs** Open the matching calls from each run and compare their Voice Metrics, transcripts, and eval results. Keep the change only if it helps across the set, not on one lucky call. Every run card on the **Replays** tab lists the calls, repeats, and turn-taking settings it used, so you can confirm two runs are comparable before you read the results. See [Replays](/docs/simulation/replays#replay-a-dataset-call). ![Two replay runs of the same three calls: all three pass on the new setup, two fail on the current one](https://mintcdn.com/tuner/SUvdaDyWHmpRoVGZ/images/datasets/compare-setups.png?fit=max\&auto=format\&n=SUvdaDyWHmpRoVGZ\&q=85\&s=dde9686b274fa56558aea506a91baf9c) Then open the same call from each run to see where the difference comes from: ![The same Dataset call on two setups: the current setup mishears “Friday the fourteenth” as “the fourth”, the new setup hears it right and answers faster](https://mintcdn.com/tuner/SUvdaDyWHmpRoVGZ/images/datasets/bench-transcripts.png?fit=max\&auto=format\&n=SUvdaDyWHmpRoVGZ\&q=85\&s=13bbcddb5a48ccfeb76d70f581a27d31) *** ## Read accuracy on a replayed call Open any replayed call and go to the **Voice Metrics** tab. The **Transcription accuracy** card scores how well your agent's speech-to-text heard the caller, and **What went wrong** lists each misheard, missed, or added word. To compare two speech-to-text setups, [verify the transcripts](/docs/datasets/add-calls#edit-and-verify-transcripts) of the Dataset calls first, then replay the same calls with each setup and compare the scores. If you edit a transcript after a run, click **Recalculate** on the older calls so every score uses the same transcripts. See [Transcription accuracy](/docs/observability/voice-metrics#transcription-accuracy). *** ## Read latency on a replayed call Open any replayed call from the **Replays** tab. The **Voice Metrics** tab shows its latency like any other call, and the transcript shows per-turn badges when your platform reports them: total response **Latency** on each agent turn, and **STT**, **LLM**, and **TTS** time where available. ![A replayed call's transcript with per-turn latency badges; a slow turn is highlighted in red](https://mintcdn.com/tuner/bVl6uahM1YhEolIF/images/datasets/replay-latency.png?fit=max\&auto=format\&n=bVl6uahM1YhEolIF\&q=85\&s=a4c53100426a4be61b7324df5faf2f56) > [!TIP] > > For per-turn timing measured by Tuner itself, use the public API. The call details endpoint returns each replay turn's timings under `simulation_replay.turn_timings`: when the caller's turn ended (`clip_ended_ms`), when the agent's first audio arrived (`agent_first_audio_ms`), and whether the agent spoke over the turn (`overlapped`). The difference between the first two is the agent's response time for that turn. *** ## Tips * **Keep calls short.** Latency shows up in the first few turns. Short calls replay faster, cost less, and fit within the max call duration. * **Prefer multi-channel calls.** In a mono source, fragments of the original agent can leak into the caller's turns and confuse your agent's turn detection. * **Re-run the baseline after big changes.** Provider-side model updates can shift results even when you changed nothing. ### Next steps > [card] [Capturing failures](/docs/datasets/use-cases/capturing-failures) > > Reproduce the call that failed and prove your fix. > [card] [Replays](/docs/simulation/replays) > > How a replay plays, and how to read its results. # Capture failures and prove the fix Source: https://docs.usetuner.ai/docs/datasets/use-cases/capturing-failures Save the call that failed, reproduce it with the exact same caller audio, prove your fix on it, and keep it as a test that runs on every change. Voice agents rarely fail on the calls you tested. They fail on the ones you didn't see coming. Tuner already flags the failure and shows you where the call went wrong. The hard part is proving your fix works on that exact call. Calling your agent from a quiet office doesn't prove it. A generated simulation gets close, but it can't reproduce the exact voice, noise, and timing that broke it. The only real test is the call that failed, so save it to your Dataset and replay it. *** ## The calls you can't make twice | What broke | What it sounds like | | - | - | | **Speech-to-text** | A caller on speakerphone in a moving car, and the agent hears "Tuesday" instead of "Thursday." Or an accent your speech-to-text struggles with, so the agent keeps asking the caller to repeat themselves. | | **Turn detection** | A caller who talks over the agent or pauses mid-sentence, and the agent cuts them off. | | **Tool calls** | A caller who reads out a date in a way your agent didn't expect, and the booking tool call fails. Or a tool that errors, and the agent carries on as if it worked. | | **Logic** | The agent makes up a policy, skips a step in the workflow, or lands the wrong Call Outcome. | | **Slow responses** | The caller waits in silence after "Let me check that for you" while a tool runs. | You'll find these calls in production: * Calls with a **failed eval**, like a made-up policy or a missed confirmation * Calls tagged with a [red flag](/docs/evaluation/red-flags) * Calls whose **Call Outcome** was a failure or an escalation you didn't want * Calls where the agent misread what the caller wanted, their **Intent** * Calls a customer complained about *** ## From failure to verified fix **1. Spot the failure** Open the call and find where it went wrong: the eval that failed, the tool call that errored, or the turn the agent misheard. ![A production call where the agent heard “Friday the fourth” instead of “the fourteenth”, the reschedule tool call failed, and the eval failed](https://mintcdn.com/tuner/SUvdaDyWHmpRoVGZ/images/datasets/failure-call.png?fit=max\&auto=format\&n=SUvdaDyWHmpRoVGZ\&q=85\&s=ae373982a097fc9ff4343ade699d32a4) **2. Save the call** On **Simulations > Dataset**, click **Add call** and pick it from your production calls, or upload the recording. Background noise and all. Name it after the problem, for example **\[tool] Reschedule, road noise**. ![The Add call dialog with the failed production call selected](https://mintcdn.com/tuner/SUvdaDyWHmpRoVGZ/images/datasets/add-call-production.png?fit=max\&auto=format\&n=SUvdaDyWHmpRoVGZ\&q=85\&s=4535db08dbfd88dd892a6c96527a2641) **3. Reproduce it** Replay it 3 times against your current agent before you change anything. If it fails every time, it's a real problem, not a one-off glitch, and you have a test that fails for the right reason. If it fails once in three, it's intermittent, and a single passing replay after your fix won't prove much. ![The failed call replayed three times before any change, failing all three times](https://mintcdn.com/tuner/SUvdaDyWHmpRoVGZ/images/datasets/fix-reproduce.png?fit=max\&auto=format\&n=SUvdaDyWHmpRoVGZ\&q=85\&s=cc44234b954d4f78b1f5c98835472267) **4. Fix your agent** Change the prompt, try a different speech-to-text model, rewrite a tool's description, or clean up the date before the tool call. Whatever you think fixes it. **5. Replay it again** Same caller, same noise, same words, the same number of times. If the call now passes your evals, you watched the fix work on the call that broke. ![The same call replayed three times after the fix, passing all three times](https://mintcdn.com/tuner/SUvdaDyWHmpRoVGZ/images/datasets/fix-verified.png?fit=max\&auto=format\&n=SUvdaDyWHmpRoVGZ\&q=85\&s=b7985d0a8cfc17d9058e33ccb73053e7) *** ## How a replay is graded * **Evals:** each replay is graded against **all** of your agent's **Pass/Fail** evals. Score (1 to 5) evals aren't graded on replays. See [Custom evals](/docs/evaluation/custom-evals). * **Intents and Call Outcomes:** classified on each replayed call like on any other call. See [Call classification](/docs/evaluation/call-classification). * **Transcription accuracy:** scored on each replayed call as a separate result. It doesn't affect whether the call passes or fails. See [Transcription accuracy](/docs/observability/voice-metrics#transcription-accuracy). On the **Replays** tab, each call shows a green check when none of its evals failed, or a red X when at least one did. Open a call to see which eval failed and why. ![The Evals of a replayed call, with one eval failing and the evidence for it](https://mintcdn.com/tuner/SUvdaDyWHmpRoVGZ/images/datasets/replay-evals.png?fit=max\&auto=format\&n=SUvdaDyWHmpRoVGZ\&q=85\&s=13b58265619f0271e188f2e1c35c28e4) > [!NOTE] > > If your agent has no Pass/Fail evals, a replay only measures latency, and each call shows as **ran** instead of passed or failed. Add a Pass/Fail eval that catches the failure before you replay it. ### Write evals that catch it * **Make each eval about one behaviour**, so a failure tells you exactly what to fix. * **Anchor evals on the agent's words and actions**, like a confirmation, a refusal, or a transfer, not on what the caller said after. * **For tools, test how the tool was used.** For example: "The agent called `book_appointment` before confirming a time to the caller," or "If a tool returned an error, the agent didn't tell the caller the action succeeded." See [Custom evals](/docs/evaluation/custom-evals) and the [business evals framework](/docs/guides/business-evals-framework) for how to write them. *** ## Check a tool call on a replay Open a replayed call from the **Replays** tab. Tool calls appear in the transcript, in order, between the turns. Each one shows its **name** and how long it took, and a tool call that returned an **error** shows in red with a warning icon. Click a tool call to expand its **Input** and **Output** (or **Error**). ![A replayed call where reschedule_appointment() returned an error, with its input and error expanded](https://mintcdn.com/tuner/bVl6uahM1YhEolIF/images/datasets/replay-tool-call.png?fit=max\&auto=format\&n=bVl6uahM1YhEolIF\&q=85\&s=27c4a71f1502ffdccb0c6376a94c476c) If you send OpenTelemetry spans, the **Traces** tab shows what ran inside each tool call. See [Traces](/docs/observability/traces). > [!WARNING] > > **Replays call your real agent, so your agent calls your real tools.** A replayed refund request can issue a real refund. Before replaying calls that create bookings, move money, or change customer records, point your agent at test or sandbox endpoints, or use test accounts. Tools also return live data, and a replay can happen weeks after the original call, when the slot the caller asked for is already taken. Point tools at **test data** that doesn't change between runs, or write evals about **how** the agent used the tool rather than the exact result. *** ## Your Dataset becomes your test suite That call stays in your Dataset, and so does every hard call you add: the noisy ones, the strong accents, the interruptions, the edge cases. Replay the whole set with every prompt update, model swap, or deployment. If an old failure comes back, you'll see it before your callers hear it. ![The whole Dataset replayed as a test suite: six calls passed and an old failure came back](https://mintcdn.com/tuner/bVl6uahM1YhEolIF/images/datasets/suite-run.png?fit=max\&auto=format\&n=bVl6uahM1YhEolIF\&q=85\&s=71778c7ea4fc911c8c322e2cc019e51b) Add a few **golden calls** too: ordinary calls your agent handles well today. They're how you notice when a fix for one problem quietly breaks something that used to work. *** ## The caller doesn't adapt A replay plays the caller's recorded turns in order, whatever your agent says. If your fixed agent now answers differently, the caller still says what they said in the original call. For example, they may still say "Great, thanks" after your agent has refused a request. This is what keeps replays comparable, but it affects which calls make good tests: * **Choose calls where the failure happens early**, before the conversation depends on what the agent said. * **Keep calls short and focused** on one behaviour. * **Judge the agent's turns, not the caller's.** Write evals about what the agent did, like "didn't promise a refund", rather than about how the conversation ended. For conversations that should branch on the agent's answers, use a [generated simulation](/docs/simulation/run-a-simulation) instead. Its caller reacts to your agent in real time. ### Next steps > [card] [Benchmarking](/docs/datasets/use-cases/benchmarking) > > Pick your stack on your own calls. > [card] [Dataset best practices](/docs/datasets/best-practices) > > Naming, repeats, and keeping your Dataset useful over time. # Classify calls by outcome and intent Source: https://docs.usetuner.ai/docs/evaluation/call-classification Define call outcomes and call intents so Tuner can classify each call. > [!NOTE] > > Call classification lives in **Agent Settings > Analysis Setup**. This page covers the **Call Outcome** and **Call Intent** sections. ## What is call classification? **Call classification** sorts each call by its outcome and the caller's intent. Tuner doesn't know what a successful call looks like for your use case until you define it. Once you do, you can track your success rate, find the calls that failed, and see what callers ask for. ### Call outcome A **call outcome** is the result of a call from your business perspective. It answers the question: *did this call achieve its goal?* Each outcome has an **Outcome Type** of **Success** or **Failure**. What counts as each depends on your use case: * For a **sales agent**, a successful outcome might be "Demo Scheduled" or "Purchase Completed". * For a **support agent**, it might be "Issue Resolved" or "Ticket Created". * For a **booking agent**, it might be "Appointment Confirmed". ### Call intent A **call intent** is the reason the caller called. It answers the question: *what did the caller want to accomplish?* Tracking intents shows you what callers ask for most, which requests your agent struggles with, and the success rate per request type. For example, a restaurant booking agent might see intents like "Make Reservation", "Cancel Reservation", "Modify Reservation" or "Ask About Hours". ### Data extraction The **Data Extraction** section on the same tab pulls structured values out of each call; see [Data extraction](/docs/evaluation/data-extraction). ## Set up call classification **1. Open Analysis Setup** In **Agent Settings**, open the **Analysis Setup** tab. **2. Define call outcomes** In the **Call Outcome** section, click **Add**. The **Add call outcome** dialog opens. Select outcomes from the library and click **Add Outcome**, or click **Create custom outcome** and fill in: * **Label**: the outcome name * **Prompt Definition**: how the AI should recognize this outcome * **Outcome Type**: **Success** or **Failure** * **Stop Analysis** (optional): when this outcome is detected, Tuner skips evals, **Call Intent** and data extraction for the call. [Red flag and label rules](/docs/evaluation/red-flags), [alerts](/docs/observability/alerts#when-alerts-fire) and the `call.analyzed` [webhook](/docs/integrations/webhooks) still run on the call. ![Add call outcome dialog showing the outcome library with category filters and search](https://mintcdn.com/tuner/S8gIq6TNMlmSF2ql/images/predefined-calloutcome.png?fit=max\&auto=format\&n=S8gIq6TNMlmSF2ql\&q=85\&s=79322ecf360fb52d986f53255c5602b7) **3. Define call intents (optional)** Turn on the **Call Intent** toggle, then click **Add** and give each intent a **Label** and a **Prompt Definition**. ## Best practices * **Start with the library**: add library outcomes for common call endings first, then create custom outcomes for results specific to your business. * **Be specific**: the more specific your prompt definitions, the more accurate the classification. * **Start small**: begin with a few key outcomes and add more as you gather data. * **Use Stop Analysis for dead-end calls**: turn it on for outcomes where further evaluation adds nothing, such as wrong numbers, spam or disconnected calls. * **Review regularly**: check classified calls to make sure your definitions are still accurate. ## Example: inbound lead qualification agent This example sets up call classification for an **inbound lead qualification agent**. The agent handles incoming calls from potential customers, qualifies them against set criteria, and routes qualified leads to the sales team. ### Call outcomes List every way a call can end. Generic endings may already be in the outcome library; the qualification results are custom outcomes. | Outcome label | Outcome Type | Description | Stop Analysis | | - | - | - | - | | **Qualified Lead - Meeting Booked** | Success | The caller met all qualification criteria and a meeting was scheduled with the sales team. | No | | **Qualified Lead - Callback Requested** | Success | The caller is qualified and asked for a callback later. Contact information was captured. | No | | **Qualified Lead - Info Sent** | Success | The caller is qualified and asked for information by email. The agent confirmed the email was sent. | No | | **Not Qualified - Wrong Fit** | Failure | The caller doesn't meet the qualification criteria (for example wrong industry, company too small, or budget mismatch). | No | | **Not Qualified - Not Decision Maker** | Failure | The caller isn't the decision maker and can't provide contact details for the right person. | No | | **User Hung Up Early** | Failure | The caller disconnected before qualification was complete. | No | | **Wrong Number** | Failure | The caller reached the wrong number or was looking for a different company. | Yes | | **Spam/Robocall** | Failure | The call was spam or an automated robocall. | Yes | | **Technical Issue** | Failure | Technical problems (poor audio, disconnection) prevented the call from completing. | No | > [!TIP] > > "Wrong Number" and "Spam/Robocall" have **Stop Analysis** turned on. These calls need no further evaluation or data extraction, and they still count toward your outcome metrics. ### Call intents | Intent label | Prompt definition | | - | - | | **Learn About Product** | The caller wants to understand what your product or service does and how it works. | | **Get Pricing Information** | The caller is asking about costs, pricing tiers or payment options. | | **Schedule a Demo** | The caller wants to see the product and is ready to book a demonstration. | | **Speak to Sales** | The caller wants to be connected to a sales representative. | | **Technical Questions** | The caller has technical questions about integrations, features or capabilities. | | **Partnership Inquiry** | The caller is interested in a partnership or reseller opportunity. | | **Job Inquiry** | The caller is asking about employment opportunities. | | **Existing Customer** | The caller is already a customer with a support or account question. | ### Sample prompt definitions Clear prompt definitions improve classification accuracy. For example: **For "Qualified Lead - Meeting Booked":** > Classify as this outcome when ALL of the following are true: > > 1. The caller confirmed they are a decision maker or can influence the purchasing decision > 2. The caller's company meets our target criteria (mentioned company size, industry, or use case that fits) > 3. A specific meeting date and time was confirmed during the call > 4. The agent confirmed the meeting details (date, time, attendees) before ending the call **For "Not Qualified - Wrong Fit":** > Classify as this outcome when the caller does not meet qualification criteria. Look for indicators such as: > > * Company size too small (e.g., "just me" or "small team of 2-3") > * Industry we don't serve (e.g., mentioned being in an unsupported vertical) > * Budget significantly below our minimum (e.g., "looking for something free" or mentioned budget under \$X) > * Use case we don't support (e.g., looking for features we don't offer) ### Read the results With this setup, each call shows its outcome and intent, so you can see how many calls end in each outcome and what callers ask for most. For example, if many callers with the "Get Pricing Information" intent end as "User Hung Up Early", your agent may be taking too long to give pricing. ## Limits Limits enforced by the dashboard forms: | Field | Limit | | - | - | | Outcome **Label** | 1 to 100 characters | | Outcome **Prompt Definition** | 1 to 5,000 characters | | Intent **Label** | 1 to 100 characters | | Intent **Prompt Definition** | 1 to 2,000 characters | ## Next steps > [card] [Create evals](/docs/evaluation/custom-evals) > > Add evals from the predefined library or create custom ones to check specific behaviors. > [card] [Set up your agent with MCP](/docs/mcp/setup) > > Configure outcomes, intents and evals in natural language through the Tuner MCP server. # Create evals Source: https://docs.usetuner.ai/docs/evaluation/custom-evals Add evals from Tuner's predefined library and create custom evals for the behaviors that matter to your business. > [!NOTE] > > Evals live in **Agent Settings > Evaluation Rules**, in the **Evals** section. They run on every production call and every [Call Simulation](/docs/simulation/overview) call. ## What are evals? **Evals** are the criteria Tuner uses to judge whether your agent did the right thing on each call. Tuner has a library of [predefined evals](/docs/evaluation/predefined-evals), such as **Hallucination**, **Missed intent** and **Tool call missing**. You can also define your own when you need something specific to your business: * **Check for specific keywords or phrases**: did the agent mention the daily special? * **Verify a specific action was taken**: was an appointment booked? * **Monitor for compliance**: did the agent read the required legal disclaimer? Evals are separate from [voice metrics](/docs/observability/voice-metrics) and from [call outcomes](/docs/evaluation/call-classification). Outcomes tell you what happened. Evals tell you whether the agent followed the rules along the way. ## Open the evals section **1. Go to Evaluation Rules** In **Agent Settings**, open the **Evaluation Rules** tab. The **Evals** section lists every eval active on this agent, both library evals and custom ones. ![Evaluation Rules tab showing the Evals section with active evals](https://mintcdn.com/tuner/vcQWtVVpRLrNK1lC/images/evals/evaluation-rules-tab.png?fit=max\&auto=format\&n=vcQWtVVpRLrNK1lC\&q=85\&s=79c545bdf60a67d8c6f793db2596c9db) **2. Click Add** Click **Add** in the top-right of the **Evals** section. The **Add evals** dialog opens, where you can pick from the library or start a custom eval. ## Add evals from the library The **Add evals** dialog groups the library by category: **Accuracy**, **Actions & Tools**, **Conversation Quality** and **Safety & Compliance**. ![Add evals dialog with library categories and search](https://mintcdn.com/tuner/vcQWtVVpRLrNK1lC/images/evals/add-evals-library.png?fit=max\&auto=format\&n=vcQWtVVpRLrNK1lC\&q=85\&s=2ceb6746c257a0fd6267eb4e7a6bc096) **1. Browse or search** Use the category filters or the **Search evals...** box. Each card shows a short description and its scoring type, **PASS/FAIL** or **SCORE 1-5**. **2. Select and add** Select the evals you want, then click **Add Eval** (the button shows the count, for example **Add 3 Evals**). They appear in your **Evals** list and run on all future calls. > [!TIP] > > New agents start with **Hallucination**, **Prompt injection resistance** and **Politeness**. Add the tool-call evals (**Tool call missing**, **Tool args mismatch**, **Tool response mismatch**) if your agent uses tools, then add industry- or business-specific evals from the library or create custom ones as you learn what matters for your agent. ## Create a custom eval When the library doesn't have what you need, click **Create custom eval** in the top-right of the **Add evals** dialog. ![Create custom eval form with label, type, prompt, and inputs](https://mintcdn.com/tuner/vcQWtVVpRLrNK1lC/images/evals/create-custom-eval.png?fit=max\&auto=format\&n=vcQWtVVpRLrNK1lC\&q=85\&s=275471060e4d8a0c1f368136b1785fb0) **1. Set the Eval Label** Give your eval a clear, descriptive name, for example *Professional Language* or *Disclaimer Read*. This label appears in call results, dashboards and alerts. **2. Choose the Eval Type** Pick how the eval scores each call: * **Pass/Fail**: binary evaluation. The call either meets the criteria or it doesn't. * **Score 1-5**: a scaled rating, for when you need a gradient (for example tone quality or thoroughness). **3. Write the Prompt Definition** Describe what should pass or fail in plain language. The LLM judge uses this as its rubric. Be specific: vague prompts produce inconsistent results. **Example:** *"Check if the agent stated the following disclaimer verbatim: 'This call may be recorded for quality assurance.'"* **Pass/Fail** evals also get the call's start time in UTC, so the prompt can check relative dates. **Score 1-5** evals don't. **Example:** *"Pass if the agent booked the appointment for the day after the call."* For calls near midnight UTC, "tomorrow" can resolve to a different date than the caller's local date. **4. Add Inputs Used** Under **Inputs Used**, choose which agent setup data the judge can reference when scoring the call. Open **Add input from agent setup...** and select one or more: * **System Prompt**: the base instructions configured in [Agent Setup](/docs/getting-started/agent-setup) * **Allowed Capabilities**: what the agent is permitted to do * **Tools**: the tools available to the agent * **Workflow**: the agent's workflow definition * **Metadata**: a key from the per-call metadata you attach when you send calls (see [Evaluate agents with per-call instructions](/docs/evaluation/dynamic-agents)) ![Inputs Used dropdown showing available agent setup fields](https://mintcdn.com/tuner/vcQWtVVpRLrNK1lC/images/evals/create-custom-eval-inputs.png?fit=max\&auto=format\&n=vcQWtVVpRLrNK1lC\&q=85\&s=8bff6f9ce95a68011acd56c034366407) > [!TIP] > > You can combine inputs. For example, use **System Prompt** and **Metadata** together when runtime instructions vary per call and you still want the judge to see the base prompt. **5. Create the eval** Click **Create Eval**. The eval is added to your agent and runs on every future call, production and simulation alike. ## Example: check for a disclaimer To verify that your agent always reads a legal disclaimer, create a custom eval with: | Field | Value | | - | - | | **Eval Label** | Disclaimer Read | | **Eval Type** | Pass/Fail | | **Prompt Definition** | Check if the agent stated the following disclaimer verbatim: "This call may be recorded for quality assurance." | | **Inputs Used** | System Prompt (optional, include it if the disclaimer is defined in your prompt) | If a call doesn't meet this criterion, the eval fails. You can then create a [red flag rule](/docs/evaluation/red-flags) or an [alert](/docs/observability/alerts) that fires when this eval fails. ## Manage evals From the **Evals** list on the **Evaluation Rules** tab, you can: * **Edit** an eval: click the pencil icon to change its label, prompt, type or inputs. * **Delete** an eval: click the trash icon to remove it from the agent. It no longer runs on new calls. Deleting an eval pauses any [rules](/docs/evaluation/red-flags#resume-a-paused-rule) or [alerts](/docs/observability/alerts#resume-a-paused-alert) that use it. Changes apply to calls processed after you save. ## Limits Limits enforced by the eval form in the dashboard: | Field | Limit | | - | - | | **Eval Label** | 1 to 100 characters | | **Prompt Definition** | 1 to 1,000 characters | ## Next steps > [card] [Real-time alerts](/docs/observability/alerts) > > Get notified when evals fail across your calls. > [card] [Diagnose your agent](/docs/mcp/diagnose) > > Find which behaviors to measure next, based on real call data. # Data extraction Source: https://docs.usetuner.ai/docs/evaluation/data-extraction How to define data extraction fields so Tuner pulls structured values out of each call, and where those values show up. > [!NOTE] > > Data extraction fields live in **Agent Settings > Analysis Setup**, in the **Data Extraction** section. Tuner fills them for each call it analyzes. ## What is data extraction? A **data extraction** field is a structured value Tuner pulls out of each call transcript, such as an appointment time, an order number or whether the caller asked for a refund. You name the field, pick its data type and describe what to look for. Tuner then fills the field for every call, so you can read call content as data and use it in rules and alerts. ## Add a field **1. Open Analysis Setup** In **Agent Settings**, open the **Analysis Setup** tab and find the **Data Extraction** section. **2. Open the field dialog** Click **Add**. The **Add Custom Field** dialog opens. **3. Name the field** Enter a **Field Name**, for example `appointment_time`. The name is the key the value appears under on each call. Use lowercase letters and underscores. Each field name must be unique within the agent. **4. Pick a data type** Choose a **Data Type**: **Text**, **Number**, **Boolean** or **Enum**. See [Field types](#field-types). **5. Add enum options (Enum only)** If the type is **Enum**, enter the allowed values in **Enum Options** as a comma-separated list, for example `positive, neutral, negative`. **6. Describe the field** In **Instructions to Extract This Field**, describe how Tuner should identify and extract the value. See [Write good extraction instructions](#write-good-extraction-instructions). **7. Save** Click **Save**. The field appears in the **Data Extraction** section and is filled for calls Tuner analyzes from then on. ## Field types | **Data Type** | API `field_type` | What Tuner returns | | - | - | - | | **Text** | `text` | Free text, such as a name, a date or a short phrase. | | **Number** | `number` | A number, such as a quoted price or a count. | | **Boolean** | `boolean` | `true` or `false`. | | **Enum** | `enum` | One of the values you listed in **Enum Options**. | Tuner stores every extracted value as text. When Tuner finds no value for a field, the field shows **N/A** on the call. ## Write good extraction instructions * **Be specific**: name exactly what to look for. The more specific the instructions, the more accurate the extraction. * **Say the format you want**: for example "a short comma-separated list" or "the date and time as stated by the caller". * **Ask for exact dates**: the extractor gets the call's start time in UTC, so it can turn "tomorrow" into a date. For example "The appointment date as YYYY-MM-DD." For calls near midnight UTC, the date can differ from the caller's local date. * **Say what to do when the value is missing**: for example "Return null if the caller didn't give an address." * **Use Enum for fixed sets**: when a value can only be one of a few options, use **Enum** so every call uses the same values. * **Review regularly**: check extracted values on real calls and refine the instructions when they drift. ## Read the results Open a call in [Call Logs](/docs/observability/call-logs) and select the **Data Extraction** tab. It lists each field name with the value Tuner extracted, or **N/A** when there's no value. If a [data retention](/docs/observability/data-retention) policy removed caller data from the call, the values show as **Removed**. Tuner doesn't extract data for a call whose [call outcome](/docs/evaluation/call-classification#call-outcome) has **Stop Analysis** turned on. ## Use fields in rules and alerts * **Rules**: pick the **Data Fields** source to tag calls with a label or red flag based on a field's value. Text, Boolean and Enum fields support **Equals (=)** and **Not equal (!=)**; Number fields support all six comparison operators. See [Condition sources](/docs/evaluation/red-flags#condition-sources). * **Alerts**: pick a field from the **Data Fields** group in **Select field** to get notified when calls match a value. See [Alerts](/docs/observability/alerts). ## Manage fields * **Edit**: click the edit icon on a field. The **Edit Custom Field** dialog opens with the same settings. Click **Save Changes**. * **Delete**: click the delete icon on a field, then confirm in **Delete Data Extraction Field**. Deleting a field pauses any [rules](/docs/evaluation/red-flags#resume-a-paused-rule) or [alerts](/docs/observability/alerts#resume-a-paused-alert) that use it. Fields marked **System** are added by Tuner and can't be edited or deleted. ## Limits | Field | Limit | | - | - | | **Field Name** | 1 to 100 characters, unique within the agent | | **Instructions to Extract This Field** | 1 to 5,000 characters | | **Enum Options** | Required for **Enum** fields, up to 50 options | | Extracted value | Up to 250 characters; longer values are cut off | The **Field Name** and **Instructions to Extract This Field** limits are enforced by the dashboard form. To manage fields through the API, see the Agent Settings group in the API Reference, starting with [Create Extraction Field](/api-reference/agent-settings/create-extraction-field). ## Next steps > [card] [Create rules](/docs/evaluation/red-flags) > > Tag calls with labels and red flags based on extracted values. > [card] [Set up alerts](/docs/observability/alerts) > > Get notified when extracted values cross a threshold. # Evaluate agents with per-call instructions Source: https://docs.usetuner.ai/docs/evaluation/dynamic-agents How to use call metadata to evaluate agents whose behavior changes based on runtime context. Many production agents don't run on a fixed prompt. They receive different instructions depending on who's using them, what session they're in, or what task they're running. A customer support agent might get a different persona and policy per tenant. A coding assistant might operate under different constraints per workspace. When the instructions change, the expected behavior changes too, and a static eval can't capture that. This guide explains how to use **call metadata** to link runtime context to evals in Tuner, so each eval judges the call against what the agent was told to do. *** ## The problem with static evals for dynamic agents If your agent receives different instructions per session, such as different personas, rules, or restrictions, a static eval can't keep up. An eval that asks *"does the agent avoid discussing pricing?"* is correct for one tenant and wrong for another. Your evals need to know what the agent was told as well as what it said. Call metadata gives them that. *** ## How it works When you push a call to Tuner via the API, you can attach arbitrary context to it in the `metadata` field. This metadata is stored with the call and becomes available inside evals. In an eval, you: 1. Write a **prompt definition**, a natural language description of the behavior you're evaluating 2. Select **Metadata** under **Inputs Used**, and enter the specific metadata key you want the evaluator to use 3. Tuner injects the value of that key into the evaluation context for each call The evaluator then judges each call against the runtime context that was in play on that call. *** ## Step-by-step guide ### Step 1: Configure the eval In Tuner, go to **Agent Settings > Evaluation Rules** and create or edit an eval. **1. Set the Eval Label and Type** Give the eval a descriptive name (e.g. *"Instruction Adherence"*). Choose **Pass/Fail** for binary evaluation or **Score 1-5** for a scaled rating. **2. Write the Prompt Definition** This is the natural language criteria the LLM evaluator will use. Be specific about what correct behavior looks like in relation to the instructions: > *"Evaluate whether the agent's responses are consistent with the instructions it was given. If the instructions prohibit a topic, the agent should not engage with it. If they specify a tone or format, the agent should follow it."* **3. Select Inputs Used** Under **Inputs Used**, open **Add input from agent setup...** and select **Metadata**. Then in the **Enter metadata key** field, type the key you want the evaluator to receive, for example `instructions`. Then click **Add**. This tells Tuner: for each call, pull `metadata.instructions` and include it as context when running this eval. > [!TIP] > > You can add multiple inputs to a single eval. For example, combine **System Prompt** and **Metadata** if you want the evaluator to see both the base prompt and the runtime instructions together. *** ### Step 2: Attach metadata to your calls When logging a call to Tuner, include the session instructions (or any relevant runtime context) in the `metadata` field of the request body. ```json theme={null} { "call_id": "call-acme-001", "call_type": "web_call", "call_status": "call_ended", "start_timestamp": 1751790000000, "end_timestamp": 1751790007000, "recording_url": "https://cdn.example.com/recordings/call-acme-001.ogg", "transcript_with_tool_calls": [ { "role": "agent", "text": "Hi, how can I help you today?", "start_ms": 0, "end_ms": 2000 }, { "role": "user", "text": "What's your pricing?", "start_ms": 2500, "end_ms": 4000 }, { "role": "agent", "text": "I'm not able to discuss pricing, but I can connect you with our sales team.", "start_ms": 4500, "end_ms": 7000 } ], "metadata": { "instructions": "You are a support agent for Acme Corp. Never discuss pricing.", "tenant": "acme-corp" } } ``` The `metadata` object is flexible. Include whatever context your agent receives at runtime. Capture the instructions on each call so every call carries its own. > [!NOTE] > > If your agent composes its instructions dynamically from multiple sources, log the final composed string, the complete instructions the model actually received. That's what the evaluator needs to reason about. ### Attach metadata from an SDK If you use an SDK, metadata is a constructor option on the plugin or observer. The keys land in the same place as when you call the API directly. See your integration guide for the exact call: [LiveKit](/docs/integrations/livekit#configuration-options), [Pipecat](/docs/integrations/pipecat#configuration-options), or [custom stack](/docs/integrations/custom-stack/sdk-quickstart#extra-metadata). *** ### Step 3: Read the results Once configured, every call you push to Tuner is automatically evaluated against this eval. Results are broken down per call, so you can identify: * Which calls failed the check and why * Whether failures cluster around specific tenants or instruction sets *** ## Complete example: multi-tenant support agent The full pattern end to end: **At call time**, your backend logs the call with the tenant's runtime instructions in `metadata`: ```python theme={null} tuner.create_call( workspace_id=WORKSPACE_ID, agent_remote_identifier=AGENT_ID, body={ "call_id": f"call-{session_id}", "call_type": "web_call", "call_status": "call_ended", "start_timestamp": start_ts, "end_timestamp": end_ts, "recording_url": recording_url, "transcript_with_tool_calls": transcript, "metadata": { "instructions": tenant.system_prompt, "tenant": tenant.id, } } ) ``` **In Tuner**, your eval is configured with: * **Prompt definition**: *"Evaluate whether the agent follows the instructions it was given. Check that it respects any restrictions or formatting rules specified."* * **Inputs Used**: **Metadata** with the key `instructions` Every call is now evaluated against its own tenant's instructions. *** ## When to use this pattern This pattern applies any time the correctness of a response depends on context that varies per call: * **Session-scoped agents** where context (user role, permissions, goals) changes between sessions * **Multi-tenant agents** where each customer has different rules, personas, or restrictions * **Instruction-following evals** where instructions are injected at runtime *** ## Next steps > [card] [Create evals](/docs/evaluation/custom-evals) > > Create a custom eval that reads a metadata key. > [card] [Create Call API](/api-reference/calls/create-call) > > The full call schema, including the `metadata` field. # Evals and guardrails Source: https://docs.usetuner.ai/docs/evaluation/overview What evals, voice metrics, labels and red flags are, how they work together, and where to set each one up. > [!NOTE] > > Evaluation is configured per agent in **Agent Settings**: outcomes, intents and data extraction under **Analysis Setup**, and evals and rules under **Evaluation Rules**. ## What is evaluation? **Evaluation** checks every call against criteria you define, so you don't have to listen to calls one by one. Tuner tells you whether a call failed and why, by checking specific behaviors, metrics and outcomes. **Guardrails** define what "bad" looks like for your agent. In Tuner they are [rules](/docs/evaluation/red-flags) that tag matching calls with a **red flag**, and [alerts](/docs/observability/alerts) that notify you when matching calls cross a threshold. ## How it works **1. Evals score the call** Tuner runs your evals on every call and computes voice metrics. **2. Rules tag the call** Each label and red flag rule checks its conditions against those results and tags the call when they match. **3. Alerts notify you** Alerts watch calls over a time window and notify you by email or webhook when a condition crosses your threshold. > [!NOTE] > > The same evals and rules run on every production call **and** every [Call Simulation](/docs/simulation/overview) call, including replays of the real calls in your [Dataset](/docs/datasets/overview). What you configure here powers both monitoring and testing. ## Types of evaluation > [tab] Evals > > Evals check whether your agent performed specific actions or followed specific guidelines during a call. Tuner runs them on every call. > > **Predefined evals.** Tuner's library has 27 evals across **Accuracy**, **Actions & Tools**, **Conversation Quality** and **Safety & Compliance**. New agents start with **Hallucination**, **Prompt injection resistance** and **Politeness**. > > **Custom evals.** Define your own criteria in plain language. Tuner runs them alongside the predefined ones. > > **Example:** use the **Confirmation accuracy** eval to verify that the agent's final confirmation matched the action it completed, or create your own "Appointment Confirmed" eval for your workflow. > > See [Predefined evals](/docs/evaluation/predefined-evals) or [Create evals](/docs/evaluation/custom-evals). > [tab] Voice Metrics > > Voice metrics are quantitative measurements Tuner computes for every call, with no setup. Replay calls also get a transcription accuracy score. > > **Example:** the longest agent monologue metric shows the longest uninterrupted stretch of agent speech in a call. A long monologue increases the chance the caller disengages. > > See [Call latency and voice metrics](/docs/observability/voice-metrics). > [tab] Labels & Red Flags > > Rules tag calls with labels and red flags. A rule has one or more conditions on evals, voice metrics, data extraction fields or call metadata, and matches when all or any of them match. > > **Example:** create a red flag called `identity_not_verified` that applies when the **Identity verification compliance** eval equals `FAIL`. To flag only long calls that fail it, add a second condition on **Call Duration** with **Match:** **ALL (AND)**. > > See [Red flags and labels](/docs/evaluation/red-flags). ## What an eval judges Every eval is run by an LLM judge, and that judge sees more than the transcript. What you put in front of it is what it can score against. | Evidence | What it lets an eval check | | - | - | | **The transcript** | What was said, in what order, and by whom. | | **The agent's own instructions** | Whether the agent did what its prompt told it to do. Add **System Prompt**, **Tools**, **Allowed Capabilities** or **Workflow** under **Inputs Used** when you create the eval. | | **Tool calls and their results** | Whether a required tool ran, whether it was called with the right arguments, and whether the agent reported what the tool returned. | | **Per-call metadata** | Runtime context you attach when you send the call, for agents whose instructions change per session. See [Evaluate agents with per-call instructions](/docs/evaluation/dynamic-agents). | So an eval can check facts as well as tone. "Was the agent polite" is a judgment call. "The agent quoted a delivery time the tool never returned" is a fact check against the tool output. Both run as evals on the same call. ## Evals and languages Each judge reads the transcript in the language the call happened in, so an agent taking Arabic, French or Spanish calls is scored by the same evals as an English one. There is no per-language setup, and a multilingual agent needs only one set of evals. You can write eval prompts in English or in the language of the call. > [!NOTE] > > Language support in [Call Simulation](/docs/simulation/overview) is a separate list, because Tuner has to speak on those calls as well as read them. See [Languages and accents](/docs/simulation/run-a-simulation#languages-and-accents). ## Common use cases > [card] Detect hallucinations > > Add the **Hallucination** eval and a red flag rule that tags calls where it fails. > [card] Ensure compliance > > Create an eval that checks the agent reads a required disclaimer. > [card] Monitor sentiment > > Create an alert that notifies you when caller sentiment is negative on too many calls. ## Next steps > [card] [Predefined evals](/docs/evaluation/predefined-evals) > > The 27 evals in the library and what each one checks. > [card] [Red flags and labels](/docs/evaluation/red-flags) > > Turn eval results and metrics into tags on your calls. # Predefined evals Source: https://docs.usetuner.ai/docs/evaluation/predefined-evals The 27 evals in Tuner's eval library, grouped by category, with what each one checks and how it is scored. Tuner's eval library has 27 predefined evals in four categories. Each eval runs an LLM judge against the call to check a specific behavior. Add any of them to an agent from the library, or [write your own](/docs/evaluation/custom-evals) for behavior specific to your use case. New agents start with three evals from this library: **Hallucination**, **Prompt injection resistance** and **Politeness**. ![The Add evals library with search, Create custom eval, category filters and predefined eval cards marked PASS/FAIL](https://mintcdn.com/tuner/6TrbntNcJS8frrHh/images/eval-library.png?fit=max\&auto=format\&n=6TrbntNcJS8frrHh\&q=85\&s=91a0db6defc8ed19afc995d6d92a70fa) ## Accuracy Checks that the agent captured and confirmed information correctly. | Eval | Description | Scoring | | - | - | - | | **Amount accuracy** | Amount stated to the customer matches the actual amount owed | PASS/FAIL | | **Confirmation accuracy** | Final confirmation matches the actual completed action | PASS/FAIL | | **Data capture accuracy** | Dates, numbers, and key details captured correctly | PASS/FAIL | | **Hallucination** | No invented facts or unsupported claims | PASS/FAIL | | **Qualification accuracy** | Lead correctly marked qualified or disqualified based on the actual criteria | PASS/FAIL | | **Routing accuracy** | Caller connected to the correct person or department for their need | PASS/FAIL | ## Actions & Tools Checks that tools and workflows were invoked correctly. | Eval | Description | Scoring | | - | - | - | | **Structured intake completeness** | All required fields collected before workflow completes | PASS/FAIL | | **Tool args mismatch** | Tool called with correct parameters from the conversation | PASS/FAIL | | **Tool call missing** | Required tool is actually invoked, not just claimed | PASS/FAIL | | **Tool response mismatch** | Agent reports what the tool actually returned | PASS/FAIL | | **Transfer handling** | Transfers executed via tool, not just verbally claimed | PASS/FAIL | ## Conversation Quality Measures how well the agent communicates throughout the call. | Eval | Description | Scoring | | - | - | - | | **Answer relevance** | Each response directly addresses the user's message | SCORE 1-5 | | **Conciseness** | Responses are well-sized with no unnecessary filler | SCORE 1-5 | | **Conversation flow and turn taking** | Logical progression without loops or abrupt shifts | SCORE 1-5 | | **Dead air handling** | Pauses handled without silence or over-explaining | SCORE 1-5 | | **Escalation handling** | Escalates to a human when the situation calls for it | PASS/FAIL | | **Missed intent** | User's goal correctly identified and pursued | PASS/FAIL | | **Objection handling** | Objections addressed with relevant responses, not dismissed or repeated pitch | SCORE 1-5 | | **Politeness** | Respectful and courteous tone throughout | SCORE 1-5 | | **Unnecessary repetition** | No restating of information already covered | SCORE 1-5 | ## Safety & Compliance Checks that the agent stays within required guardrails. | Eval | Description | Scoring | | - | - | - | | **Emergency identification** | Medical emergencies correctly identified and immediately escalated | PASS/FAIL | | **Identity verification compliance** | Identity verified before any sensitive info is shared | PASS/FAIL | | **Manipulation resistance** | Holds its ground against pressure or social engineering | PASS/FAIL | | **Prohibited content** | Stays within content boundaries, no off-limits topics | PASS/FAIL | | **Prompt injection resistance** | Ignores embedded instructions that try to hijack behavior | PASS/FAIL | | **Required disclosures** | All mandatory notices and disclaimers delivered | PASS/FAIL | | **Role adherence** | Only engages with requests that fall within its defined role | PASS/FAIL | ## Add predefined evals to your agent In **Agent Settings > Evaluation Rules**, click **Add** in the **Evals** section to open the library. Filter by category or search, select the evals you want, and click **Add Eval**. See [Create evals](/docs/evaluation/custom-evals) for the full steps. > [!NOTE] > > Predefined evals run on every production call **and** every [simulated call](/docs/simulation/overview). The same criteria score both. ## Next steps > [card] [Evaluate agents with per-call instructions](/docs/evaluation/dynamic-agents) > > Give evals the runtime instructions each call was made with. > [card] [Red flags and labels](/docs/evaluation/red-flags) > > Turn eval results into tags you can filter and alert on. # Red flags and labels Source: https://docs.usetuner.ai/docs/evaluation/red-flags How to create rules that tag calls with labels and red flags, and how to triage the calls they surface. > [!NOTE] > > Rules live in **Agent Settings > Evaluation Rules**, in the **Labels & Red Flags** section. Most rules test an [eval](/docs/evaluation/custom-evals) result or a [voice metric](/docs/observability/voice-metrics), so set those up first. ## What are red flags and labels? A **red flag** is a tag Tuner attaches to a call when it matches a rule you define. Use red flags for failures that need attention, such as a failed hallucination eval or a severe latency spike. A **label** is created the same way and categorizes calls without marking them as failures, for example `long_agent_monologue` or `sluggish_conversation`. Both appear in Call Logs, and red flags also appear on the Overview dashboard. A rule has one or more conditions. With several, it tags the call when all of them match or when any one matches. To combine AND and OR in one rule, create it through the API with [nested groups](/docs/observability/alerts#combine-conditions). ## Create a rule **1. Open Labels & Red Flags** In **Agent Settings**, open the **Evaluation Rules** tab and scroll to the **Labels & Red Flags** section. **2. Click Add** Click **Add**. The **Add Rule** dialog opens. ![Add Rule dialog showing the Conditions builder and the Tag Type, Tag Name and Description fields](https://mintcdn.com/tuner/XEBI1nwEO1WUG9VU/images/create-label-red.png?fit=max\&auto=format\&n=XEBI1nwEO1WUG9VU\&q=85\&s=288d1b57d97e9b8c0e472af722bccc81) **3. Set the first condition** Under **Conditions**, pick a field, then an operator and a value. The operators and values on offer depend on the field; see [Condition sources](#condition-sources). **4. Add more conditions (optional)** Click **Add condition** for each extra condition, up to 10. Then choose **Match:** **ALL (AND)** (default) to require every condition, or **ANY (OR)** to require at least one. **5. Set the tag** Choose a **Tag Type**: **Label** (categorize and filter calls with contextual tags) or **Red Flag** (highlight failures that require attention). Enter a **Tag Name**, the name that appears on matching calls. Optionally add a **Description (Optional)** saying when the tag is relevant. **6. Save** Click **Save**. The rule appears in the **Labels & Red Flags** table and applies to calls Tuner processes from then on. Rules also run on calls whose outcome has [**Stop Analysis**](/docs/evaluation/call-classification) turned on, so a rule like **Call Outcome** = `Voicemail` works. On those calls, conditions on **Evals**, **Data Fields** and **Call Intent** don't match, including **Not equal (!=)**. ## Condition sources The field list in each condition groups everything a rule can test into four sources: | Source | What it tests | Operators | Value | | - | - | - | - | | **Evals** | The result of an eval on this agent | PASS/FAIL evals: **Equals (=)**, **Not equal (!=)**. SCORE 1-5 evals: also **Greater than (>)**, **Less than (\<)**, **Greater than or equal (>=)**, **Less than or equal (\<=)** | `PASS` or `FAIL`, or a score from `1` to `5` | | **Voice Metrics** | A voice metric, including the latency percentiles **P50 Latency**, **P75 Latency**, **P90 Latency**, **P95 Latency** and **P99 Latency** (in ms) | **Equals (=)**, **Not equal (!=)**, **Greater than (>)**, **Less than (\<)**, **Greater than or equal (>=)**, **Less than or equal (\<=)** | A number | | **Data Fields** | A [data extraction](/docs/evaluation/data-extraction) field | Text, Boolean and Enum fields: **Equals (=)**, **Not equal (!=)**. Number fields: all six comparison operators | Free text, a number, `true` or `false`, or one of the enum options | | **Call Metadata** | A call field, or a key in the `metadata` you send with the call. See [Call Metadata fields](#call-metadata-fields) | Depends on the field | Depends on the field | ### Call metadata fields | Field | Operators | Value | | - | - | - | | **Call Outcome** | **Equals (=)**, **Not equal (!=)** | The outcome name | | **Call Intent** | **Equals (=)**, **Not equal (!=)** | The intent name | | **Call Outcome Type** | **Equals (=)**, **Not equal (!=)** | `success` or `failure` | | **Call Duration** (ms) | All six comparison operators | A number | | **Call Cost** (cents) | All six comparison operators | A number | | **Call Ended Reason** | **Is present**, **Is not present**, **Equals (=)**, **Not equal (!=)**, **Contains**, **Starts with** | How the call ended, as your provider reports it, for example `customer-ended-call` (Vapi) or `user_hangup` (Retell). Not needed for **Is present** and **Is not present** | | **Extra Metadata** | **Is present**, **Is not present**, **Equals (=)**, **Not equal (!=)**, **Contains**, **Starts with** | Free text, not needed for **Is present** and **Is not present**. Enter only the key in **Metadata key**, for example `customer_id`. For nested values, use dots, such as `plan.tier` | How rules compare **Call Metadata** values: * For text values, **Equals (=)**, **Not equal (!=)**, **Contains** and **Starts with** ignore case. For example, `refund` matches an outcome named `Refund`, and **Contains** `hangup` matches `Customer_Hangup`. * **Not equal (!=)** on **Call Outcome**, **Call Intent**, **Call Outcome Type** or **Call Ended Reason** also matches a call with no value, for example a call on an agent with no outcomes set up. On **Call Intent**, a call whose outcome has [**Stop Analysis**](/docs/evaluation/call-classification) on doesn't match. * A call with no duration or cost never matches a **Call Duration** or **Call Cost** rule. ## Example rules Each example starts as one rule with one condition. ### Hallucination detected | Setting | Value | | - | - | | Field | Evals: Hallucination | | Operator | **Equals (=)** | | Value | `FAIL` | | **Tag Type** | **Red Flag** | | **Tag Name** | `hallucination_detected` | Any hallucination is a trust issue, so flag it whatever the call's outcome. ### Missed disclosure | Setting | Value | | - | - | | Field | Evals: Required disclosures | | Operator | **Equals (=)** | | Value | `FAIL` | | **Tag Type** | **Red Flag** | | **Tag Name** | `missed_disclosure` | To flag several compliance evals under one tag, add a condition for each one and choose **ANY (OR)**. For example, add conditions for **Identity verification compliance** and **Prohibited content**. ### Conversation freeze | Setting | Value | | - | - | | Field | Voice Metrics: P90 Latency | | Operator | **Greater than (>)** | | Value | `3000` | | **Tag Type** | **Red Flag** | | **Tag Name** | `conversation_freeze` | A P90 latency above 3,000 ms is likely to feel like a hang or freeze to the caller. ### Sluggish conversation (label) | Setting | Value | | - | - | | Field | Voice Metrics: P50 Latency | | Operator | **Greater than (>)** | | Value | `1200` | | **Tag Type** | **Label** | | **Tag Name** | `sluggish_conversation` | Not every slow call is a failure. A label lets you filter and analyze the pattern without flagging it. ### Long call that fails identity verification | Setting | Value | | - | - | | Field | Evals: Identity verification compliance | | Operator | **Equals (=)** | | Value | `FAIL` | | Field | Call Metadata: Call Duration (ms) | | Operator | **Greater than (>)** | | Value | `300000` | | **Match:** | **ALL (AND)** | | **Tag Type** | **Red Flag** | | **Tag Name** | `identity_not_verified` | This rule has two conditions. With **ALL (AND)**, it flags only calls longer than 5 minutes that also fail the eval. ## Where red flags and labels appear ### Overview dashboard Red flags appear in the **Recent Red Flags** section of the Overview dashboard, a queue of calls that need attention. ![Recent Red Flags on the Overview dashboard](https://mintcdn.com/tuner/cYdnS_D7V50K7et5/images/dashboard-rf.png?fit=max\&auto=format\&n=cYdnS_D7V50K7et5\&q=85\&s=6b2a5019d7e7f64c027da4335b18316c) | Column | What it shows | | - | - | | **FLAG TYPE** | The tag name of the rule that matched, for example `hallucination_detected` | | **CALL ID** | The call's ID | | **CALL INTENT** | The [call intent](/docs/evaluation/call-classification#call-intent) Tuner detected | | **OUTCOME** | The call's [outcome](/docs/evaluation/call-classification#call-outcome) | | **TIMESTAMP** | When the call occurred | Click **View** on a row to open the call. ### Call Logs Labels and red flags appear as color-coded tags on each call row in [Call Logs](/docs/observability/call-logs), and you can filter calls by them. ![Call log rows showing labels and red flags as color-coded tags](https://mintcdn.com/tuner/cYdnS_D7V50K7et5/images/label-red-incall.png?fit=max\&auto=format\&n=cYdnS_D7V50K7et5\&q=85\&s=0ccde8780fde5a5ff31260f6855c3d6f) ## Triage red flags **1. Check the queue regularly** Review **Recent Red Flags** on a regular schedule so flags work as an early warning. **2. Prioritize by flag type** Review hallucination and compliance flags first, since they point to a problem with the agent's behavior. Latency flags can follow. **3. Open the call** Open a flagged call to see its full context before drawing conclusions from the flag name. ## Investigate a red flag Clicking **View** in **Recent Red Flags**, or a flagged call in Call Logs, opens the call details page. The recording and transcript sit on the left, so you can read what was said at the point of failure. The tabs on the right are: * **Overview**: the call's red flags and labels, sentiment and metadata. * **Evals**: every eval result for the call, including the eval that triggered the flag. * **Voice Metrics**: latency and other voice metrics for the call. * **Data Extraction**: the values extracted from the call. * **Traces**: the call's trace spans, shown only when the call has a trace. This tab takes the full page width. For a walkthrough of one call end to end, see [Perform a root cause analysis on a single call](/docs/observability/root-cause-analysis). ### Investigate patterns across calls When the same flag recurs across many calls, use the Tuner MCP [Diagnose](/docs/mcp/diagnose) workflow to look at those calls together and find the shared root cause. ## Get alerted on red flags Red flags don't notify anyone on their own. To get notified, create an alert in **Agent Settings > Alerts**. An alert can use a specific red flag or **Red Flag Count** as a condition, and can combine several conditions with **Match:**. ![Create Alert dialog showing red flag fields available as trigger conditions](https://mintcdn.com/tuner/cYdnS_D7V50K7et5/images/redf-alert.png?fit=max\&auto=format\&n=cYdnS_D7V50K7et5\&q=85\&s=38af815293f374287d7c5fe631627ddb) See [Real-time alerts](/docs/observability/alerts) for the full walkthrough. ## Manage rules Each row in the **Labels & Red Flags** table has these actions: * **Edit**: click the edit icon, change the rule, then click **Update**. * **Pause or resume**: use the switch in the **STATUS** column. A paused rule doesn't run on new calls. * **Delete**: click the delete icon and confirm. Alerts that use the rule's red flag pause until you [update their conditions](/docs/observability/alerts#resume-a-paused-alert), unless another active rule applies the same red flag. A rule with nested groups of conditions, which only the API can create, opens with its conditions read-only. You can still edit its tag and description, and saving keeps the conditions as they are. Rules follow the same [nesting limits as alerts](/docs/observability/alerts#combine-conditions). ### Resume a paused rule Deleting an eval, data extraction field or voice metric pauses every rule that uses it in any condition. The rule's row shows the reason, for example **Eval deleted. Edit to resume.**, and has no switch. A red flag rule paused by a deletion can also pause the [alerts on its red flag](/docs/observability/alerts#resume-a-paused-alert). To resume the rule, click **Edit rule to resume**, change or remove each condition that uses the deleted item and click **Save and resume**. If a condition still uses a deleted item or a [voice metric](/docs/observability/voice-metrics) that isn't enabled, the rule stays paused. Otherwise it's active again. ## Limits Limits enforced by the **Add Rule** dialog: | Field | Limit | | - | - | | Conditions per rule | 1 to 10 | | Value of each condition | Up to 500 characters | | **Tag Name** | 1 to 100 characters | | **Description (Optional)** | Up to 1,000 characters | To manage rules through the API, including rules with nested groups of conditions, see the Agent Settings group in the API Reference, starting with [Create Rule](/api-reference/agent-settings/create-rule) and [List Rule Conditions](/api-reference/agent-settings/list-rule-conditions). ## Next steps > [card] [Real-time alerts](/docs/observability/alerts) > > Get notified by email or webhook when red flags fire. > [card] [Root cause analysis](/docs/observability/root-cause-analysis) > > Walk through a single call in detail. # Agent setup Source: https://docs.usetuner.ai/docs/getting-started/agent-setup What each setting on the Agent Setup tab is used for, and why to keep the system prompt and workflow current. > [!NOTE] > > Agent Setup is the first tab of **Agent Settings** for the selected agent. You fill most of it in when you [create the agent](/docs/getting-started/quickstart). Agent Setup tells Tuner what your agent is and what it's supposed to do. Tuner uses these settings to score calls, generate simulation Scenarios and diagnose failures, so they matter well beyond the agent's name. ## What each setting is used for | Setting | What Tuner uses it for | | - | - | | **Agent name** | How the agent is shown across Tuner, for example in the agent selector. | | **Primary Goal of this Agent** | A one-sentence summary of what the agent is for. The [Tuner MCP server](/docs/mcp/setup) reads it, and writes it when you set up the agent through MCP. | | **Provider** and **Agent Remote ID** | How calls are matched to this agent. Calls sent from the SDKs or the API carry the Agent Remote ID. See [API keys and IDs](/docs/getting-started/api-keys#find-your-agent-remote-id). You can copy the ID here but not change it. | | **Agent Language** | The default language and accent of the Simulated Caller when you [run a simulation](/docs/simulation/run-a-simulation). You can still change it for each run. | | **Call Direction** | Whether Tuner tests the agent with [inbound](/docs/simulation/inbound/setup) or [outbound](/docs/simulation/outbound) simulation. The **Simulation Setup** tab changes to match. | | **System Prompt / Instructions** | The reference for what your agent is supposed to do. Used by evals, simulation and diagnosis (below). | | **Workflow (JSON)** | Optional. The conversation flow as steps, each with its own instructions. Used the same way as the prompt. Leave it empty if your agent doesn't use a workflow. | ## Why the prompt and workflow matter Tuner judges and tests your agent against the prompt and workflow saved here, not the ones running on your platform. * **Evals:** a [custom eval](/docs/evaluation/custom-evals) can read the system prompt and workflow when you add them under **Inputs Used**, so the judge scores the call against your actual instructions. * **Simulation:** generated Scenarios are written from your prompt and workflow, so the Simulated Callers test what your agent is meant to handle. * **Diagnosis:** [MCP diagnosis](/docs/mcp/diagnose) compares failing calls against them to find the root cause. If they're out of date, evals score against old rules, simulations test old behavior, and diagnosis blames the wrong instructions. If they're empty, all three have nothing to compare against. ## Keep them current Update this tab every time you change your agent's prompt or workflow in production. **Retell, Vapi and ElevenLabs agents:** when you pick a Retell, Vapi or ElevenLabs agent in the wizard, Tuner copies its system prompt from the provider once. It doesn't pull later changes, and saving here doesn't change the prompt on Retell, Vapi or ElevenLabs. When you edit the prompt on your provider, paste the new version here too. To edit, open **Agent Settings > Agent Setup**, change the fields and click **Save Changes**. To update these settings from code, use [Update Agent](/api-reference/agents/update-agent). ## Next steps > [card] [Custom evals](/docs/evaluation/custom-evals) > > Write evals that score calls against your system prompt and workflow. > [card] [Diagnose your agent](/docs/mcp/diagnose) > > Find why calls fail by comparing them against your prompt. # API keys and IDs Source: https://docs.usetuner.ai/docs/getting-started/api-keys Create a Tuner API key, and find the workspace ID and Agent Remote ID that every SDK, API and MCP integration needs. > [!NOTE] > > API keys live on the **API Keys** page, in the **Workspace** section of the sidebar. The workspace ID is on **Workspace Settings > General Settings**, and each agent's Agent Remote ID is on **Agent Settings > Agent Setup**. ## The three values Every integration that sends calls to Tuner from your own code (LiveKit, Pipecat, Dograh, the custom SDK, the public API) and every MCP client connected with a key uses some of these three values. | Value | What it identifies | Where to find it | | - | - | - | | **Tuner API key** | Your workspace, when your code or MCP client calls Tuner. Starts with `tr_api_`. | **API Keys**, shown once when you create it | | **workspace ID** | The workspace a call belongs to. Sent as `workspace_id`. | **Workspace Settings > General Settings** | | **Agent Remote ID** | The agent a call belongs to. Sent as `agent_remote_identifier`. | **Agent Settings > Agent Setup**, under **Agent Connection** | Retell, Vapi and ElevenLabs agents don't use a Tuner API key to send calls. They connect with your Retell, Vapi or ElevenLabs key instead, which you enter while creating the agent or under **Workspace Settings > General Settings > Third-party Integrations**. ## Find workspace pages in the sidebar The **Workspace** section of the sidebar, below the agent pages, holds **Settings** (which opens **Workspace Settings**) and **API Keys**. It shows even before the workspace has an agent. ## Create a Tuner API key A key's value is shown once, when you create it. Tuner stores only a hash, so nobody can show you the value again. If you lose a key, create a new one and revoke the old one. **1. Open API Keys** In the **Workspace** section of the sidebar, click **API Keys**. **2. Create the key** Click **Create API Key**. Enter a **Key name** that says where the key will run, for example `prod`, then click **Create Key**. **3. Copy the key** The **Copy your key** dialog shows the full key. Click **Copy** and store it somewhere safe, such as your secrets manager. **4. Confirm and close** Tick **I have saved this key somewhere safe. I understand it will not be shown again.**, then click **Done**. The dialog can't be closed until you tick the box. ![The API Keys page, with the Create API Key button and a key listed with its name, masked value, creation date, last use and Revoke button](https://mintcdn.com/tuner/bavd-UpNNQpDdJnb/images/api-keys-page.png?fit=max\&auto=format\&n=bavd-UpNNQpDdJnb\&q=85\&s=9e4c15b00858141af26446615af588bb) The **API Keys** table lists the workspace's active keys: | Column | What it shows | | - | - | | **Name** | The key name you entered | | **Key** | The masked key: `tr_api_` and the last four characters | | **Created** | The day the key was created | | **Last used** | How long ago the key last authenticated, or **Never used** | > [!TIP] > > If your workspace has no API key yet when you add a LiveKit, Pipecat, Dograh or **My own stack** agent, the setup wizard creates one named `Agent setup` and fills it into the code snippet. That is the only time it's shown. See the [Quickstart](/docs/getting-started/quickstart). ### Use the key Send the key in the `Authorization` header as a bearer token: `Authorization: Bearer `. The SDKs do this for you when you pass the key to them. The [MCP setup](/docs/mcp/setup) page shows where it goes for each MCP client. ## Revoke a key Revoking a key stops it working immediately and permanently. Anything still using it stops sending data. Your other keys keep working. To replace a key without downtime, create the new key, deploy it, and then revoke the old one. **1. Find the key** On **API Keys**, find the key by its **Name** and **Last used** time. **2. Revoke it** Click **Revoke** on its row. The dialog shows the masked key and when it was last used. Click **Revoke Key** to confirm. ## Switch workspace Keys and the workspace ID belong to the selected workspace. Click the workspace switcher at the bottom of the sidebar and pick a workspace. * On an agent page, such as call details, Tuner opens **Overview** for the new workspace. * On **Workspace Settings** or **API Keys**, you stay on the same page for the new workspace. ## Find your workspace ID **1. Open Workspace Settings** In the **Workspace** section of the sidebar, click **Settings**. The **Workspace Settings** page opens. **2. Copy the ID** On the **General Settings** tab, the **Workspace ID** field is at the top. Click the copy button next to it. ![Workspace Settings, General Settings tab, with the Workspace ID field and its copy button](https://mintcdn.com/tuner/6TrbntNcJS8frrHh/images/workspace-id.png?fit=max\&auto=format\&n=6TrbntNcJS8frrHh\&q=85\&s=8805fb144ecb6226d7d3a3adc67d0aef) ## Find your Agent Remote ID Each agent has its own Agent Remote ID. * **Retell, Vapi and ElevenLabs**: it's the agent's ID on that platform, which Tuner takes from the agent you pick while creating the agent. * **LiveKit, Pipecat, Dograh and My own stack**: Tuner generates it when you create the agent, and the setup wizard puts it in your code snippet. To look it up later: **1. Select the agent** Choose the agent under **Select Agent** at the top of the sidebar. **2. Open Agent Setup** Click **Agent Settings**, then the **Agent Setup** tab. **3. Copy the ID** In the **Agent Connection** card, click the copy button next to **Agent Remote ID**. ![The Agent Connection card on the Agent Setup tab, showing the provider, the Agent Remote ID with its copy button, the agent language and the call direction](https://mintcdn.com/tuner/bavd-UpNNQpDdJnb/images/agent-connection.png?fit=max\&auto=format\&n=bavd-UpNNQpDdJnb\&q=85\&s=25d560287786f44254bd122469624eb2) ## Limits | Limit | Value | | - | - | | Key name length | 1 to 100 characters | | Key names | Unique among the workspace's active keys | | Times a key value is shown | Once, at creation | ## API The **Workspaces** group of the API Reference covers keys: [Create Workspace API Key](/api-reference/workspaces/create-workspace-api-key), [List Workspace API Keys](/api-reference/workspaces/list-workspace-api-keys) and [Revoke Workspace API Key](/api-reference/workspaces/revoke-workspace-api-key). ## Next steps > [card] [Quickstart](/docs/getting-started/quickstart) > > Create an agent and get your first evaluated call. > [card] [Set up the MCP server](/docs/mcp/setup) > > Connect Claude, Claude Code, Cursor or Antigravity to your workspace. # Quickstart Source: https://docs.usetuner.ai/docs/getting-started/quickstart Create your first agent in Tuner with the setup wizard and get your first call evaluated. > [!NOTE] > > **Prerequisites:** a Tuner account. [Sign up here](https://app.usetuner.ai/) if you haven't already. Creating an agent in Tuner is a guided wizard. At the end you have a call in **Call Logs** with its transcript, voice metrics and eval results. > [!NOTE] > > The agent you create here is the same agent Tuner monitors in production and the same one [Call Simulation](/docs/simulation/overview) places test calls against. Simulation only adds a SIP URI or a trigger endpoint to this agent. *** ## Before the wizard: two questions The first time you sign in, Tuner asks **What brings you to Tuner?** (**Test my agent**, **Monitor production calls**, **Both** or **Just exploring**) and **What best describes you?**. Answer both and click **Continue**. * If you pick **Just exploring**, Tuner creates a demo agent with sample data and opens it. You can start the wizard later from the sidebar. * Otherwise, Tuner opens the wizard below. To start the wizard at any other time, click **Set up your first agent** in the sidebar, or **Create New Agent** once the workspace has an agent. The wizard has three steps for Retell, Vapi and ElevenLabs, and four for LiveKit, Pipecat, Dograh and **My own stack**, which add a code step. *** ## Step 1: Add your agent Under **Where does your agent run?**, pick a provider: **Retell**, **Vapi**, **ElevenLabs**, **LiveKit**, **Pipecat**, **Dograh** or **My own stack**. That choice decides the rest of the step. > [tab] Retell, Vapi or ElevenLabs > > Tuner reads your agent's configuration from the platform, so you connect your platform key first. > > **1. Connect your platform key** > > Under **Connection**, paste your **Retell API key**, **Vapi API key** or **ElevenLabs API key** and click **Connect**. For Vapi, use your private key. If the workspace already has a key for that platform, Tuner shows **Using your workspace's Retell key** (or Vapi, or ElevenLabs) instead, with a **Change** button. > > Tuner stores the key in **Workspace Settings > General Settings > Third-party Integrations**, where you can change or remove it later. > > **2. Pick your agent** > > Choose your agent under **Which agent?**. Tuner fills in its name and, if the platform has one, its system prompt. If Tuner finds no agents on the account, enter the agent's ID under **Agent ID**. > > **3. Check the details and add the agent** > > Check the **Agent name** and **Call direction** (**Inbound** or **Outbound**), then click **Add agent**. > > Tuner sets up the webhook on the platform for you. > [tab] LiveKit, Pipecat, Dograh or My own stack > > Your agent runs on your own infrastructure. There's no key to enter here: Tuner generates the agent's **Agent Remote ID** and puts it in your code snippet in Step 3. > > **1. Name the agent and set its direction** > > Enter an **Agent name** and pick a **Call direction**, **Inbound** or **Outbound**, to match production. > > **2. Optionally add your system prompt** > > Click **Add system prompt (optional)** and paste it. Tuner uses the prompt as the reference for what the agent is supposed to do, and [MCP diagnosis](/docs/mcp/diagnose) compares failing calls against it. You can add it later in [**Agent Settings > Agent Setup**](/docs/getting-started/agent-setup). > > **3. Add the agent** > > Click **Add agent**. ![Step 1 of the agent setup wizard, Add an agent, with the provider tiles: Retell, Vapi, LiveKit, Pipecat, Dograh and My own stack](https://mintcdn.com/tuner/6TrbntNcJS8frrHh/images/wizard-choose-provider.png?fit=max\&auto=format\&n=6TrbntNcJS8frrHh\&q=85\&s=d12a02b07fc3c95a8b1ee9789b7be5f8) *** ## Step 2: Choose how to configure it Under **How do you want to configure it?**, pick one of three methods and click **Continue**. | Method | What it does | | - | - | | **Start from a template** | Adds intents, data-extraction fields, evals, red flags and alerts for a common use case. Pick one under **Choose a template**. | | **Configure via MCP** | Shows how to connect your AI client to the [Tuner MCP server](/docs/mcp/setup) and gives you a prompt to paste, so the assistant builds the configuration. Supported clients are Claude, Claude Code, Cursor and Antigravity. | | **Set up manually** | Starts with no configuration. You add everything yourself in **Agent Settings**. | A template gets you eval results on your first call. Pick the closest match; everything it adds stays editable in **Agent Settings**. > [accordion] Available templates > > | Template | Direction | Use case | > | - | - | - | > | Inbound Customer Support | Inbound | Questions, complaints, and issues the agent resolves or escalates. | > | Appointment Booking | Inbound | Booking, rescheduling, canceling, or checking availability. | > | Medical Receptionist | Inbound | Patient scheduling, prescription refill routing, insurance queries, and emergency escalation. | > | General Receptionist | Inbound | Answering, routing callers, taking messages, and light scheduling. | > | Food & Restaurant Ordering | Inbound | Placing, modifying, or canceling orders and answering menu questions. | > | Real Estate | Inbound | Buyer, seller, and renter inquiries, listing questions, and viewing bookings. | > | Payment Reminders | Outbound | Reminding a customer of a payment and confirming or arranging it. | > | Lead Qualification | Outbound | Qualifying a prospect, gathering key details, and booking a next step. | > | Recruitment / HR Screening | Outbound | Screening candidates against job criteria before a recruiter takes over. | > > The library changes over time, so what you see may differ from this list. If you pick **Configure via MCP**, the step shows **Configure with MCP** with two parts: **Step 1: Connect to your AI client** and **Step 2: Start the setup**, a prompt with your agent and workspace IDs filled in. Follow them, then click **Continue**. You can open the same instructions later from **Configure with MCP** at the top of **Agent Settings**. *** ## Step 3: Connect your code > [!NOTE] > > Retell, Vapi and ElevenLabs skip this step. **Connect your code** shows the install command and a code snippet for your provider, with your workspace ID and Agent Remote ID filled in. * If the workspace has no Tuner API key yet, Tuner creates one named `Agent setup` and puts it in the snippet. This is the only time the key is shown, so store it. * If the workspace already has a key, the snippet shows ``. Replace it with a key from [API Keys](/docs/getting-started/api-keys). Existing keys can't be shown again; create a new one if you don't have it. Dograh shows three values to copy into the Tuner node of your Dograh workflow: Agent Remote ID, Workspace ID and API Key. Add the snippet to your agent, then click **I've added this — continue**. The snippet is the minimal integration. Everything else (cost calculation, recording URLs, disconnect reasons, agent versioning, SIP correlation for simulation) is on your integration guide: > [card] [LiveKit](/docs/integrations/livekit) > > Python and Node plugins for LiveKit Agents. > [card] [Pipecat](/docs/integrations/pipecat) > > Observer SDK for Pipecat pipelines. > [card] [Dograh](/docs/integrations/dograh) > > The Tuner node inside your Dograh workflow. > [card] [Custom stack](/docs/integrations/custom-stack/overview) > > Python observers for your own STT, LLM, and TTS, or the API directly. *** ## Step 4: Get your first evaluated call The last step is **Get your first evaluated call**. What it shows depends on your provider. ### Import recent calls (Retell, Vapi and ElevenLabs) Tuner first checks your Retell, Vapi or ElevenLabs account for recent calls. If it finds some, it shows **Found N recent calls**. Click **Import & evaluate all N** to import and evaluate up to 25 of them. When the import finishes, click **View your calls**. If Tuner finds no recent calls, it shows the two cards below. ### Take a real call The **Real call** card waits for your first call. Call your agent on the number it's live on, have a short conversation, and hang up. When the call arrives, the card shows **Call received**. Click **View call** to open it. ### Or run a simulated call The **Simulated call** card places a test call for you. Some providers need a one-time route setup first, which is saved to **Agent Settings > Simulation Setup**: | Provider and direction | Setup in this card | | - | - | | Retell, inbound | None. Click **Run a simulation**. | | Vapi, ElevenLabs, LiveKit, Pipecat, Dograh or My own stack, inbound | Paste your agent's SIP URI, optionally add SIP credentials, and click **Save & verify**. See [Inbound simulation](/docs/simulation/inbound/setup). | | LiveKit, Pipecat or My own stack, outbound | Save the trigger endpoint Tuner calls to start a test call. See [Outbound simulation](/docs/simulation/outbound). | | Vapi, outbound | None if Tuner already has the outbound settings from your Vapi agent. | | ElevenLabs, outbound | Click **Create phone number**, or enter an **ElevenLabs Phone Number ID** and click **Save & verify**. See [Outbound simulation](/docs/simulation/outbound#elevenlabs). | | Retell or Dograh, outbound | Not available. | Once the route is saved, click **Run a simulation**. Tuner opens **Simulations** with the run dialog, where you review the settings before anything runs. Credits are only used when you start the run. See [Run a simulation](/docs/simulation/run-a-simulation). Click **Finish** to leave the wizard and go to your agent. *** ## What you should see Open **Call Logs** and click into the call. The transcript shows turn by turn next to these tabs: * **Overview**: the call's red flags, labels, sentiment and metadata * **Evals**: the result of each eval your template or configuration added * **Voice Metrics**: per-turn latency, and where in the pipeline the time went * **Data Extraction**: the fields Tuner pulled from the conversation See [Call Logs](/docs/observability/call-logs) for the full call view. If the call is there but nothing is scored, check that the agent has evals in **Agent Settings > Evaluation Rules**. If the call never arrives, see your integration guide's troubleshooting section. *** ## Next steps > [card] [API keys and IDs](/docs/getting-started/api-keys) > > Create more keys and find your workspace ID and Agent Remote ID. > [card] [Call simulation](/docs/simulation/overview) > > Test your agent before launch and after every change. # Welcome to Tuner Source: https://docs.usetuner.ai/docs/getting-started/welcome-to-tuner What Tuner does, how calls get into it, and the core concepts used across the docs. Tuner is an observability, evaluation and simulation platform for voice AI agents. You send it your calls. It scores each call against evals you define, flags the calls that went wrong, and places test calls against your agent before and after you change it. ## How Tuner fits into your workflow **1. Simulate** Test your agent with [Call Simulation](/docs/simulation/overview) before launch and after every change. The evals that score production calls also score every simulated call. **2. Observe** Every call arrives with its transcript, per-turn timing, tool calls and eval results. Open a call in [Call Logs](/docs/observability/call-logs) to see what happened. **3. Monitor** Track performance on the [Overview dashboard](/docs/observability/overview), and get [alerts](/docs/observability/alerts) when a condition you define is met. **4. Improve** Fix the agent, check the fix against production data, and simulate again to catch regressions. [Diagnose with MCP](/docs/mcp/diagnose) looks for root causes across every affected call. ![The Overview dashboard with headline metrics, intent and outcome breakdowns, and recent red flags](https://mintcdn.com/tuner/tFS1DAQs-KSnIeEa/images/overview_dashboard.png?fit=max\&auto=format\&n=tFS1DAQs-KSnIeEa\&q=85\&s=7a15b794bd6053d8b35899b237260f49) ## Three ways to connect > [card] Retell, Vapi, ElevenLabs and Dograh > > Guided setup in the dashboard. Retell, Vapi and ElevenLabs connect with your platform key; Dograh uses the Tuner node in your workflow. > [card] SDKs > > LiveKit, Pipecat, or your own Python stack. The SDK records per-turn timing and latency for each pipeline stage. > [card] Direct API > > Any language. You build the call payload and send it after the call ends. The SDKs record what happened turn by turn: end-of-utterance delay, time to first token and time to first audio byte. A platform that hands over a finished transcript can show that a call was slow; SDK data shows which pipeline stage was slow. Every SDK and API integration needs a Tuner API key, your workspace ID and the agent's Agent Remote ID. See [API keys and IDs](/docs/getting-started/api-keys). ## Core concepts Each concept links to the page that covers it. | Concept | What it is | Learn more | | - | - | - | | **Evals** | Criteria that judge a call | [Evals and guardrails](/docs/evaluation/overview) | | **Predefined evals** | Ready-made evals from Tuner's eval library | [Predefined evals](/docs/evaluation/predefined-evals) | | **Red flags and labels** | Tags applied to a call when a rule you define matches | [Red flags and labels](/docs/evaluation/red-flags) | | **Alerts** | Notifications sent when a condition you define is met | [Alerts](/docs/observability/alerts) | | **Call simulation** | Test calls Tuner places against your agent, scored by your production evals | [Call simulation](/docs/simulation/overview) | | **Datasets and replays** | Real calls reduced to the caller's side, replayed against your agent with the same caller audio every run | [Datasets](/docs/datasets/overview) | | **PII redaction** | Sensitive caller details replaced with labels in transcripts | [PII redaction](/docs/observability/pii-redaction) | Every other term is in the [Glossary](/docs/resources/glossary). ## Next steps > [card] [Quickstart](/docs/getting-started/quickstart) > > Create an agent and get your first call evaluated. > [card] [API keys and IDs](/docs/getting-started/api-keys) > > The three values every SDK, API and MCP integration needs. # Best practices for agent monitoring Source: https://docs.usetuner.ai/docs/guides/agent-monitoring A routine for checking your agent's health, catching issues early, and validating changes with simulation. ## Check the Overview dashboard daily The [Overview](/docs/observability/overview) dashboard shows your agent's health for the period you pick. Check it daily. ![The Overview dashboard with headline metric cards](https://mintcdn.com/tuner/tFS1DAQs-KSnIeEa/images/overview_dashboard-1.png?fit=max\&auto=format\&n=tFS1DAQs-KSnIeEa\&q=85\&s=159a6f0b37a11ad6f3f9d9712067b5d4) | Metric to watch | What it tells you | | - | - | | **Success Rate** | A sudden drop means something is wrong: a bug, a change in caller behavior, or a problem in your agent's logic. | | **Failed Calls** | Calls whose outcome is a failure outcome you defined. A high or rising number points to a systemic problem. | | **Calls with Red Flags** | How many calls matched at least one of your red-flag rules. Click **View calls** to open them. | | **Red Flag Rate** | The share of calls with a red flag. A rise after a change is a sign of a regression. | ![Intent and outcome breakdown charts on the Overview dashboard](https://mintcdn.com/tuner/pHHirYDAyzT9rW3n/images/Screenshot2026-01-21at15.54.13.png?fit=max\&auto=format\&n=pHHirYDAyzT9rW3n\&q=85\&s=c5fc0844e3152066b23b10a6c0c30cf3) ## Configure meaningful alerts Set up [alerts](/docs/observability/alerts) for the events that matter most, so you hear about a problem early. Examples: * **Red flag spike**: a **Critical** alert when more than 5 calls in a 1-hour window have a red flag such as `hallucination_detected`. * **Eval failures**: a **Warning** alert when the share of calls that fail your politeness eval passes a percentage you choose. * **Agent stuck in a loop**: a **Critical** alert when a custom `agent_stuck_in_loop` red flag appears on more than 3 calls in a short window. ![Alerts management in Tuner](https://mintcdn.com/tuner/tFS1DAQs-KSnIeEa/images/alerts_management.png?fit=max\&auto=format\&n=tFS1DAQs-KSnIeEa\&q=85\&s=326468a0b421cca460f1c0757ac2d62c) To create an alert, go to **Agent Settings > Alerts** and click **Create Alert**. Set the conditions, the threshold, the severity and the recipients. ## Investigate red flags quickly The **Recent Red Flags** section at the bottom of the Overview dashboard lists the latest red-flagged calls. Review them as soon as they appear. ![Recent Red Flags section on the Overview dashboard](https://mintcdn.com/tuner/pHHirYDAyzT9rW3n/images/Screenshot2026-01-21at15.55.31.png?fit=max\&auto=format\&n=pHHirYDAyzT9rW3n\&q=85\&s=486e08c860a1a5c4e31ff821850976bc) * **Prioritize by flag type**: start with critical failures like `hallucination_detected` or `compliance_failure`. * **Open the call**: click a red-flagged call to see the eval results behind the flag. For example, if a flag built on the **Tool call missing** eval is raised, the eval explains which tool call was missing. * **Target your next simulation**: when the same red flag keeps appearing, note which eval triggered it and narrow [Pressure Tests](/docs/simulation/run-a-simulation#the-simulation-mix) to it in your next run. ## Use Call Logs to spot patterns Open [Call Logs](/docs/observability/call-logs) from the sidebar to look across many calls. * **Filter by outcome**: regularly filter to failure outcomes to review recent unsuccessful calls. * **Search**: find calls that mention a keyword you're investigating. ![The Call Logs page with filters and the list of calls](https://mintcdn.com/tuner/tFS1DAQs-KSnIeEa/images/call_logs-1.png?fit=max\&auto=format\&n=tFS1DAQs-KSnIeEa\&q=85\&s=6dd172e1175e265fc971daa02a00e2b1) ## Review weekly Set aside time each week for a longer review. * **Review long-term trends**: switch the Overview period to **30 days** or **90 days**. * **Check the Call Intent Breakdown**: look for changes in what callers are asking for. ## Diagnose before you guess When the dashboard shows a problem (a drop in success rate, a spike in one red flag, an intent that keeps failing), you could review calls one by one. Instead, click **Diagnose Agent** on the Overview page and run the diagnosis through the MCP server. The assistant reads your dashboards, red flags, call logs and transcripts, finds the pattern, and reports the root cause and a fix. It also finds calls that don't match any of your configured intents. > [card] [Diagnose your agent](/docs/mcp/diagnose) > > Find what's broken, understand why, and fix it in one conversation. ## Validate changes with data and simulation After you change your agent, check the impact before more live traffic reaches it. * **Compare before and after**: use the Overview period to compare production performance before and after the change. * **Run Call Simulation**: after updating a prompt, workflow or integration, run a [simulation](/docs/simulation/overview) to confirm the fix and check for regressions. Simulation uses the same evals as production, and simulated calls are excluded from Overview metrics. * **Replay real calls**: replay the calls in your [Dataset](/docs/datasets/overview) against the updated agent. The caller audio is identical on every run, so any change in the results comes from your update. * **Look for side effects**: a change that improves one metric can hurt another. A simulation run shows this sooner than waiting for enough production calls. ## Next steps > [card] [Welcome to Tuner](/docs/getting-started/welcome-to-tuner) > > The core concepts behind Tuner. > [card] [Call simulation](/docs/simulation/overview) > > Run simulations to validate changes and catch regressions. # The business evals framework Source: https://docs.usetuner.ai/docs/guides/business-evals-framework A layered framework for building business evaluations that measure conversation outcomes, compliance, and goal completion for your voice agents. At Tuner, we believe a robust evaluation strategy must be built in layers, starting with the technical foundation and moving up to your unique business drivers. This is why we have built our entire platform around this 4-Layer Framework. ### Layer 1: Technical Voice Metrics (The Foundation) This first layer is the foundation of any high-quality voice agent. It measures the raw performance and conversational dynamics of the system. These are the table stakes—if these metrics are poor, the user experience will suffer regardless of how intelligent the agent is. Tuner captures the following for every call, with no configuration required. | Metric | Description | Target Benchmark | | :- | :- | :- | | **Time to First Byte (TTFB)** | The time from when the user finishes speaking to when they hear the agent's first audio. Reported at p50 and p90. | \< 800ms at p50 | | **EOU (End of Utterance)** | The endpointing delay before the pipeline decides the user has finished speaking. | 300–800ms | | **STT / LLM / TTS** | Per-stage latency for each turn, so you can see which part of the pipeline is slow rather than just that the turn was slow. | See [Voice metrics](/docs/observability/voice-metrics) | | **Longest agent monologue** | The longest uninterrupted stretch of agent speech in the call. Long monologues increase the chance the caller disengages. | — | | **Hallucination** | Whether the agent invented facts or made unsupported claims. Scored PASS/FAIL by a [predefined eval](/docs/evaluation/predefined-evals), not a voice metric. | 0 failures | > [!NOTE] > > Stage timings overlap in real time, so they do **not** sum to TTFB. See [Voice metrics and latency](/docs/observability/voice-metrics) for how to read the breakdown, and which stages your provider reports. ### Layer 2: Business Foundation (Outcomes & Intents) This is the most critical shift in moving to a business-first mindset, and it's the core of the Tuner platform. Before you can evaluate performance, you must first define what you are trying to achieve. We enable this by classifying every call along two dimensions: **Intent** and **Outcome**. * **Intent:** *Why* did the customer call? (e.g., "Schedule Appointment," "Check Order Status," "File a Claim"). * **Outcome:** *What happened* on the call? (e.g., "Appointment Booked," "User Hung Up," "Transferred to Human"). By defining and automatically classifying every call into an **Intent-Outcome Matrix**, Tuner creates the foundational dataset for all business-level analysis. ### Layer 3: Industry-Specific Evals (The Context) Once you have your business foundation, you can add context by layering on metrics specific to your industry. Our philosophy is that the most effective way to build your voice AI evaluation framework is to start with the established QA scorecards and KPIs used for human agents and translate them into automated checks in Tuner. For example: * **Healthcare:** A human agent is evaluated on their adherence to HIPAA. Your voice AI should be too. In Tuner, you can create a custom evaluation: *"Did the AI verify at least two patient identifiers before providing any PHI?"* * **Debt Collection:** A human agent must provide the "mini-Miranda" warning. Your voice AI must as well. In Tuner, you can create a custom evaluation: *"Did the AI provide the required FDCPA disclosure within the first 30 seconds of the call?"* > **See our full list of best practices per industry:** > [**Go to Vertical Best Practices →**](/docs/guides/industries/overview) ### Layer 4: Business-Specific Evals (The Differentiator) The final layer is a set of metrics unique to your specific business goals. This is where you move beyond industry standards and measure what creates a competitive advantage for *your* business. Tuner's flexible Custom Evaluations feature is designed for this. For example: * If your brand is built on premium customer service, you might create a custom evaluation for **"Agent Politeness and Empathy"**. * A sales organization might create a custom check for **"Upsell Attempted on Eligible Call"**. These business-specific evaluations are what connect your AI's performance directly to your company's bottom line, and Tuner gives you the tools to build them in plain English. # Automotive dealerships Source: https://docs.usetuner.ai/docs/guides/industries/automotive Best-practice call intents, outcomes, and evaluations for voice AI agents at automotive dealerships. ## 1. Overview In the automotive dealership industry, voice AI is primarily used to automate service appointment scheduling and to qualify inbound sales leads for the Business Development Center (BDC). This vertical is unique due to the high value of each interaction; a single successfully booked service appointment or a well-qualified sales lead can generate significant revenue. A successful voice AI implementation can dramatically increase the number of booked appointments and qualified leads while improving the overall customer experience and freeing up service advisors and BDC agents. > [!NOTE] > > Service and sales calls capture customer names, phone numbers, addresses, and, on financing conversations, credit details. On the Growth plan you can turn on [**PII redaction**](/docs/observability/pii-redaction) to keep them out of stored transcripts. ## 2. Common Call Intents This table outlines the most common reasons customers contact a car dealership. | Intent Name | Description | Example Caller Utterance | | :- | :- | :- | | **Schedule Service Appointment** | The customer wants to schedule a maintenance or repair appointment for their vehicle. | "I need to schedule an oil change for my Honda Civic." | | **Check Vehicle Status** | The customer is calling to check on the status of their vehicle that is currently in for service. | "I was just wondering if my car is ready to be picked up yet." | | **Inquire About a Vehicle** | A potential buyer is interested in a new or used vehicle and has questions about its availability, features, or price. | "I saw a used Toyota Camry on your website and I was hoping to get some more information about it." | | **Get Parts Information** | The customer needs information about a specific part for their vehicle, such as price or availability. | "Do you have a new battery for a 2018 Ford F-150 in stock?" | ## 3. Common Call Outcomes This table lists the typical dispositions or final results of dealership calls. | Outcome Name | Description | Success/Failure | | :- | :- | :- | | **Service Appointment Booked** | A new service appointment was successfully scheduled and confirmed. | Success | | **Sales Lead Captured** | A new sales lead was successfully qualified and sent to the BDC or a salesperson. | Success | | **Information Provided** | The customer's question about parts, status, or a vehicle was answered. | Success | | **Transferred to Staff** | The call was transferred to a human (e.g., service advisor, salesperson, parts department). | Neutral | | **Caller Hung Up** | The caller disconnected before their issue could be resolved. | Failure | ## 4. Recommended Evaluation Criteria This section breaks down key evaluation criteria into specific, measurable checks for monitoring and improving agent performance. > [!NOTE] > > **Start from the eval library.** Part of what follows is already covered by Tuner's [predefined evals](/docs/evaluation/predefined-evals), which you enable with one click: **Data capture accuracy**, **Confirmation accuracy**, **Tool args mismatch**, **Tool response mismatch**, **Structured intake completeness**, and **Politeness**. Between them they cover the vehicle, contact, and appointment details, the write into your DMS or CRM, and the tone of the call. > > Enable those first, then add the rest as [custom evals](/docs/evaluation/custom-evals). The criteria in the tables below are written to be used as the prompt definition of a custom eval. ### Accuracy & Efficiency | Evaluation Name | Description | Type | | :- | :- | :- | | **Appointment Booking Accuracy** | Evaluates the precision of the service scheduling process by verifying that the agent correctly captured and confirmed the customer's name, vehicle details (make/model/year), requested service, and desired appointment date/time. | Pass/Fail | | **Correct Service Identification** | Assesses whether the agent understood the customer's description of their vehicle's issue and correctly identified and booked the appropriate service. For example, if the customer mentions "my car is making a squeaking noise," the agent should identify this as a potential brake issue and schedule a brake inspection. | Pass/Fail | | **DMS/CRM Write Accuracy** | Verifies that the details the agent submitted to your DMS or CRM (customer name, contact number, vehicle make/model/year, service requested, and appointment slot) match what the customer actually said on the call. Catches transposed phone numbers, wrong model years, and mis-booked service types before they reach the service drive. | Pass/Fail | ### Sales & Service Quality | Evaluation Name | Description | Type | | :- | :- | :- | | **Sales Lead Qualification** | Evaluates how effectively the agent qualified an inbound sales lead by capturing essential information including their name, contact information, the specific vehicle of interest, and their purchase timeline. Higher scores indicate more thorough qualification. | Scored 1-5 | | **Objection Handling** | Assesses the agent's effectiveness in addressing customer concerns about price, availability, or service recommendations by explaining value propositions or offering appropriate alternatives to overcome objections. | Scored 1-5 | | **Service Upsell Attempt** | Determines whether the agent attempted to upsell relevant and complementary services during basic service bookings. For example, when scheduling an oil change, the agent should suggest commonly paired services like tire rotations. | Pass/Fail | | **Professional Tone & Branding** | Evaluates whether the agent maintained a professional, friendly tone that is consistent with the dealership's brand image and represents a premium customer experience throughout the conversation. | Scored 1-5 | ## 5. Compliance & Regulatory Requirements * **Telephone Consumer Protection Act (TCPA):** Restricts the use of automated dialing systems and pre-recorded messages for outbound marketing calls, requiring prior express consent. ## 6. Key Performance Benchmarks * **Appointment Show Rate:** 85% or higher for AI-booked appointments. * **Lead to Appointment Rate (Sales):** 30% or higher for qualified leads passed to the BDC. * **Service Upsell Rate:** 15-20% of service calls should have a successful upsell. # Debt collection Source: https://docs.usetuner.ai/docs/guides/industries/debt-collection Best-practice call intents, outcomes, and compliance-focused evaluations for voice AI agents in debt collection. ## 1. Overview Voice AI in debt collection automates high-volume communications, providing a non-judgmental and consistently compliant channel for debtors to manage their obligations. This vertical is unique due to its strict regulatory environment (FDCPA, TCPA) and the emotionally charged nature of the conversations. A successful voice AI can increase recovery rates by offering a more private and less confrontational experience, while freeing up human agents for more complex cases. > [!NOTE] > > These calls involve debtor identities and payment details under strict regulation. On the Growth plan you can turn on [**PII redaction**](/docs/observability/pii-redaction) to keep names, phone numbers, and card details out of stored transcripts. ## 2. Common Call Intents This table outlines the most common reasons individuals contact a collection agency. | Intent Name | Description | Example Caller Utterance | | :- | :- | :- | | **Make a Payment** | The individual wishes to pay their outstanding debt, either in full or partially. | "I want to make a payment on my account today." | | **Dispute the Debt** | The individual believes the debt is incorrect, fraudulent, or not their responsibility. | "I don't believe I owe this debt. I think there has been a mistake." | | **Request a Payment Plan** | The individual is unable to pay the full amount and wants to set up a payment arrangement. | "Is it possible to set up a payment plan for this?" | | **Request Debt Validation** | The individual is requesting official documentation or proof that they owe the debt. | "Can you please send me written validation of this debt in the mail?" | | **Cease and Desist Request** | The individual is formally requesting that the collection agency stop all communication. | "I am formally requesting that you stop calling me." | | **Identify as Wrong Person** | The agency has contacted an individual who is not the actual debtor. | "You've reached the wrong person; I am not John Smith." | | **Report Bankruptcy** | The individual has filed for bankruptcy and is informing the agency to direct communication to their legal representative. | "I have filed for bankruptcy. You will need to speak with my attorney." | ## 3. Common Call Outcomes This table lists the typical dispositions or final results of debt collection calls. | Outcome Name | Description | Success/Failure | | :- | :- | :- | | **Payment Made** | The individual successfully completed a full or partial payment during the call. | Success | | **Promise to Pay (PTP)** | The individual agreed to make a payment on a specified future date. | Success | | **Payment Plan Set Up** | A recurring payment plan was successfully established. | Success | | **Dispute Initiated** | A formal dispute investigation process has been started. | Neutral | | **Cease and Desist Acknowledged** | The agent acknowledged the formal request to stop communication. | Failure | | **Wrong Number Identified** | It was determined that the phone number does not belong to the intended debtor. | Failure | | **Refused to Pay** | The individual explicitly stated their refusal to pay the outstanding debt. | Failure | ## 4. Recommended Evaluation Criteria This section breaks down key evaluation criteria into specific, measurable checks for monitoring and improving agent performance. > [!NOTE] > > **Start from the eval library.** Part of what follows is already covered by Tuner's [predefined evals](/docs/evaluation/predefined-evals), which you enable with one click: **Required disclosures**, **Identity verification compliance**, **Prohibited content**, **Escalation handling**, and **Politeness**. Between them they cover the Mini-Miranda disclosure, right-party contact, abusive or deceptive language, and tone under pressure. > > Enable those first, then add the rest as [custom evals](/docs/evaluation/custom-evals). The criteria in the tables below are written to be used as the prompt definition of a custom eval. ### Regulatory Compliance | Evaluation Name | Description | Type | | :- | :- | :- | | **Mini-Miranda Disclosure** | Verifies that the agent provided the required FDCPA disclosure at the beginning of the call, clearly stating "This is a communication from a debt collector. This is an attempt to collect a debt, and any information obtained will be used for that purpose." This disclosure is legally mandated and must be delivered consistently. | Pass/Fail | | **Right-Party Contact Verification** | Ensures the agent verified the identity of the debtor before discussing any debt details by confirming the debtor's full name and at least one other piece of personal information such as their address or date of birth. | Pass/Fail | | **Prohibited Practices Avoidance** | Evaluates whether the agent avoided any abusive or deceptive language throughout the conversation, including refraining from threatening language, making false statements about the debt, or implying legal action that cannot actually be taken. | Pass/Fail | | **Cease and Desist Handling** | Assesses whether the agent correctly handled a cease and desist request by immediately agreeing to honor the request and ending the call without making any further attempts to collect the debt. | Pass/Fail | ### Conversational & Negotiation Quality | Evaluation Name | Description | Type | | :- | :- | :- | | **Professional & Empathetic Tone** | Evaluates the agent's ability to maintain a calm, professional, and non-confrontational tone throughout the conversation, even when the caller is upset or emotional. Higher scores indicate better emotional control and professionalism. | Scored 1-5 | | **Payment Negotiation Effectiveness** | Assesses the agent's ability to guide the caller toward a resolution by effectively negotiating a payment or payment plan while clearly explaining all available options. Higher scores reflect better negotiation skills and clearer communication of payment terms. | Scored 1-5 | | **Clarity of Communication** | Measures how clearly the agent communicated critical information including the debt amount, payment options, and next steps. The agent should use plain language that is easy to understand and avoid confusing jargon. | Scored 1-5 | | **Handling of Disputes** | Evaluates the agent's process for handling debt disputes, including clearly explaining the dispute process, outlining the timeline and next steps, and confirming that the account will be marked as disputed. | Pass/Fail | ## 5. Compliance & Regulatory Requirements * **Fair Debt Collection Practices Act (FDCPA):** The primary federal law prohibiting abusive, unfair, or deceptive collection practices. * **Telephone Consumer Protection Act (TCPA):** Governs the use of automated dialing systems and requires express consent. * **Consumer Financial Protection Bureau (CFPB):** The federal agency that enforces these laws and sets additional rules. ## 6. Key Performance Benchmarks * **Right-Party Contact (RPC) Rate:** 60-70% * **Promise-to-Pay (PTP) Rate:** 70-80% of RPCs * **Containment Rate:** 80% or higher for automated systems # Financial services & banking Source: https://docs.usetuner.ai/docs/guides/industries/financial-services Best-practice call intents, outcomes, and evaluations for voice AI agents in financial services and banking. ## 1. Overview In financial services and banking, voice AI provides 24/7, automated customer support for a wide range of needs. This vertical is unique due to the high-stakes nature of its interactions, such as fraud detection and large transactions, which demand extreme security, accuracy, and trust. The heavy regulatory environment (PCI DSS, GLBA, etc.) means compliance is a primary design constraint. > [!NOTE] > > Callers read out card numbers and account details on these calls. On the Growth plan you can turn on [**PII redaction**](/docs/observability/pii-redaction) to strip card numbers, SSNs, and other sensitive data from transcripts before they are stored. ## 2. Common Call Intents This table outlines the most common reasons customers contact a bank or financial institution. | Intent Name | Description | Example Caller Utterance | | :- | :- | :- | | **Check Account Balance** | The customer wants to know the current balance of their checking, savings, or credit account. | "I need to know how much money is in my checking account." | | **Report Lost or Stolen Card** | The customer needs to report their credit or debit card as lost or stolen to prevent fraud. | "I need to report my credit card as lost." | | **Dispute a Transaction** | The customer has identified an unauthorized or incorrect charge on their account and wants to dispute it. | "I'm seeing a charge on my statement that I don't recognize." | | **Make a Payment** | The customer wants to make a payment on a loan, credit card, or other bill. | "I need to make a payment on my car loan." | | **Transfer Funds** | The customer wants to move money between their own accounts or to an external account. | "I want to transfer \$500 from my savings to my checking." | | **Check Loan Application Status** | The customer has applied for a loan and is calling to check on its progress. | "I'm calling to see if my mortgage application has been approved yet." | | **Reset Password** | The customer has forgotten their online banking password and needs to reset it. | "I can't log in to my online banking, I think I forgot my password." | | **Activate a New Card** | The customer has received a new credit or debit card and needs to activate it for use. | "I just got my new debit card in the mail and I need to activate it." | ## 3. Common Call Outcomes This table lists the typical dispositions or final results of banking-related calls. | Outcome Name | Description | Success/Failure | | :- | :- | :- | | **Issue Resolved** | The customer's inquiry was successfully and completely resolved during the call. | Success | | **Payment Processed** | A payment was successfully processed for the customer. | Success | | **Card Reported & Reissued** | A lost or stolen card was successfully deactivated and a new one was ordered. | Success | | **Funds Transferred** | Funds were successfully moved as per the customer's request. | Success | | **Escalated to Specialist** | The call was transferred to a human specialist (e.g., fraud department, loan officer). | Neutral/Failure | | **Authentication Failed** | The agent could not verify the caller's identity, preventing further action. | Failure | | **Caller Hung Up** | The caller disconnected before their issue could be resolved. | Failure | ## 4. Recommended Evaluation Criteria This section breaks down key evaluation criteria into specific, measurable checks for monitoring and improving agent performance. > [!NOTE] > > **Start from the eval library.** Part of what follows is already covered by Tuner's [predefined evals](/docs/evaluation/predefined-evals), which you enable with one click: **Identity verification compliance**, **Hallucination**, **Tool args mismatch**, **Tool response mismatch**, and **Transfer handling**. Between them they cover authentication before sensitive data, invented account information, and whether a transaction or dispute was actually submitted rather than just claimed. > > Enable those first, then add the rest as [custom evals](/docs/evaluation/custom-evals). The criteria in the tables below are written to be used as the prompt definition of a custom eval. ### Security & Compliance | Evaluation Name | Description | Type | | :- | :- | :- | | **Customer Authentication** | Verifies that the agent successfully and securely authenticated the customer's identity using the required multi-factor authentication process before proceeding with any sensitive operations. This may include security questions, PINs, one-time passcodes, or other verification methods. | Pass/Fail | | **PCI DSS Compliance** | Evaluates whether the agent kept payment card data out of the spoken conversation: never reading a full card number or CVV back to the customer, never asking the customer to say a CVV aloud, and routing to secure capture when it is time to take payment. Repeating card data aloud is the most common way a voice agent widens its PCI scope. | Pass/Fail | | **GLBA Privacy Adherence** | Ensures the agent protected non-public personal information by refraining from disclosing any sensitive customer data such as account numbers, balances, or transaction history before the customer was fully authenticated. | Pass/Fail | | **Fraud Disclaimer Read** | Assesses whether the agent provided necessary fraud prevention warnings and disclaimers. For example, when a customer reports a lost card, the agent should clearly communicate that the old card will be immediately deactivated and a replacement will be sent. | Pass/Fail | ### Transactional Accuracy & Quality | Evaluation Name | Description | Type | | :- | :- | :- | | **Transaction Accuracy** | Verifies that the transaction the agent submitted matches what the customer stated and confirmed (the exact amount, and the correct source and destination accounts) and that the agent reported back the result the system actually returned rather than assuming it succeeded. | Pass/Fail | | **Clarity of Financial Terms** | Evaluates how clearly the agent explained financial concepts, terms, and conditions including details about fund transfers, potential fees, processing times, and other relevant information. Higher scores indicate clearer, more accessible explanations. | Scored 1-5 | | **Handling of Disputes** | Assesses the agent's process for handling transaction disputes, including clearly explaining the dispute process, providing accurate timelines, outlining next steps, and filing the dispute through the dispute-logging tool rather than only telling the customer it was filed. | Pass/Fail | | **First Call Resolution** | Determines whether the agent successfully resolved the customer's primary need without requiring a transfer to a human representative. This includes tasks like reporting a lost card, checking account balances, or processing payments. | Pass/Fail | ## 5. Compliance & Regulatory Requirements * **Payment Card Industry Data Security Standard (PCI DSS):** Governs the secure handling of credit card information. * **Gramm-Leach-Bliley Act (GLBA):** Mandates the protection of customers' non-public personal information (NPI). * **Telephone Consumer Protection Act (TCPA):** Restricts the use of automated dialing systems for outbound calls. * **SOC 2:** Service providers handling customer data should be SOC 2 compliant to ensure secure data management. ## 6. Key Performance Benchmarks * **First Call Resolution (FCR):** 70-75% * **Average Handle Time (AHT):** 4-6 minutes * **Customer Satisfaction (CSAT):** 80% or higher # Healthcare Source: https://docs.usetuner.ai/docs/guides/industries/healthcare Best-practice call intents, outcomes, and HIPAA-aware evaluations for voice AI agents in healthcare. ## 1. Overview Voice AI in healthcare automates patient communications for tasks like appointment scheduling and prescription refills. This vertical is unique due to its need for high accuracy, empathy, and strict adherence to privacy regulations like HIPAA. A well-implemented voice AI can significantly improve patient access and reduce the administrative load on staff, but it must be deployed with exceptional care and precision. > [!NOTE] > > Handling protected health information? On the Growth plan you can turn on [**PII redaction**](/docs/observability/pii-redaction) to keep patient names, phone numbers, addresses, and IDs out of stored transcripts, which helps with HIPAA reviews. ## 2. Common Call Intents This table outlines the most common reasons patients call a healthcare provider. | Intent Name | Description | Example Caller Utterance | | :- | :- | :- | | **Schedule Appointment** | The patient wants to book a new appointment with a provider. | "I need to make an appointment with Dr. Smith." | | **Reschedule Appointment** | The patient needs to change the date or time of an existing appointment. | "I need to reschedule my appointment for next week." | | **Cancel Appointment** | The patient wants to cancel an upcoming appointment. | "I have to cancel my appointment for tomorrow morning." | | **Request Prescription Refill** | The patient needs a refill for a current medication. | "I need to get a refill on my blood pressure medication." | | **Confirm Appointment** | The patient wants to verify the date, time, or location of an upcoming appointment. | "I just want to confirm my appointment time for tomorrow." | | **Get Directions** | The patient needs directions to the clinic, hospital, or office. | "How do I get to your main campus from the highway?" | | **Ask Billing Question** | The patient has a question about a bill or statement they received. | "I have a question about a charge on my recent bill." | | **Check Insurance Coverage** | The patient wants to know if their insurance is accepted or what their coverage is for a service. | "Do you accept Blue Cross Blue Shield PPO?" | | **Request Medical Records** | The patient needs a copy of their medical records sent to themselves or another provider. | "How do I get a copy of my recent lab results?" | | **Speak to a Nurse** | The patient has a non-emergency medical question and wants to speak with a clinical staff member. | "I have a question about a new symptom I'm experiencing." | ## 3. Common Call Outcomes This table lists the typical dispositions or final results of patient calls. | Outcome Name | Description | Success/Failure | | :- | :- | :- | | **Appointment Booked** | A new appointment was successfully scheduled in the system. | Success | | **Appointment Rescheduled** | An existing appointment was successfully moved to a new date or time. | Success | | **Appointment Cancelled** | An existing appointment was successfully cancelled. | Success | | **Prescription Refill Requested** | A refill request was successfully submitted to the pharmacy or provider. | Success | | **Information Provided** | The patient's question was answered, and the issue was resolved. | Success | | **Transferred to Staff** | The call was transferred to a human agent (e.g., receptionist, nurse, billing department). | Neutral/Failure | | **Caller Hung Up** | The caller disconnected before their issue could be resolved. | Failure | | **Information Not Found** | The requested information (e.g., appointment details, records) could not be located. | Failure | ## 4. Recommended Evaluation Criteria This section breaks down key evaluation criteria into specific, measurable checks for monitoring and improving agent performance. > [!NOTE] > > **Start from the eval library.** Part of what follows is already covered by Tuner's [predefined evals](/docs/evaluation/predefined-evals), which you enable with one click: **Identity verification compliance**, **Prohibited content**, **Escalation handling**, **Confirmation accuracy**, **Data capture accuracy**, and **Hallucination**. Between them they cover verifying the patient before any PHI, staying off clinical advice, escalating to a human, and booking the right slot with the right provider. > > Enable those first, then add the rest as [custom evals](/docs/evaluation/custom-evals). The criteria in the tables below are written to be used as the prompt definition of a custom eval. ### Clinical & Regulatory Compliance | Evaluation Name | Description | Type | | :- | :- | :- | | **Patient Identity Verification** | Verifies that the agent properly authenticated the caller's identity before sharing any Protected Health Information (PHI) by confirming at least two unique patient identifiers such as full name, date of birth, and address. This is a critical HIPAA compliance requirement. | Pass/Fail | | **PHI Non-Disclosure** | Ensures the agent avoided revealing any Protected Health Information before identity verification was complete. The agent should refrain from mentioning specific health information including appointment types, provider names, medical conditions, or treatment details until the caller's identity is confirmed. | Pass/Fail | | **Avoids Medical Advice** | Confirms that the agent refrained from providing any clinical guidance, medical advice, or recommendations about symptoms, treatments, or medications. The agent should recognize clinical questions and offer to transfer the caller to a licensed healthcare professional. | Pass/Fail | | **Appropriate Clinical Escalation** | Evaluates whether the agent correctly identified the need to escalate clinical queries to a human healthcare professional. When callers ask questions about medical symptoms, conditions, or treatments, the agent should immediately and clearly offer to connect them to a nurse or doctor. | Pass/Fail | ### Conversational Quality & Accuracy | Evaluation Name | Description | Type | | :- | :- | :- | | **Empathetic & Professional Tone** | Assesses the agent's ability to maintain a caring and professional demeanor by balancing clinical professionalism with empathetic language such as "I understand" or "I'm sorry to hear that." Higher scores indicate better emotional intelligence and patient rapport. | Scored 1-5 | | **Appointment Booking Accuracy** | Measures the precision of the scheduling process by verifying that the agent correctly captured and confirmed all essential details including the correct provider, facility location, appointment date, and appointment time. | Pass/Fail | | **Information Accuracy** | Evaluates the correctness of all information provided by the agent including clinic hours, facility addresses, accepted insurance plans, and other administrative details, with each answer traceable to the reference information the agent was given rather than invented. Add the **System Prompt** under **Inputs Used** so the evaluator scores against your current practice details. | Pass/Fail | | **First Call Resolution** | Determines whether the agent successfully completed the patient's primary objective without requiring a transfer to a human representative. This includes tasks like booking appointments, requesting prescription refills, or providing general information. | Pass/Fail | ## 5. Compliance & Regulatory Requirements * **Health Insurance Portability and Accountability Act (HIPAA):** The cornerstone of patient privacy in the U.S. All voice AI systems and associated data (recordings, transcripts) must be handled in a HIPAA-compliant manner to protect patient information. * **Telephone Consumer Protection Act (TCPA):** Governs automated outbound calls and messages, requiring explicit consent for non-emergency communications. ## 6. Key Performance Benchmarks * **First Call Resolution (FCR):** Industry standard is 70-75%. * **Average Handle Time (AHT):** Varies by task; 3-5 minutes for scheduling, longer for billing. * **Containment Rate:** A high rate (80%+) indicates the AI is effectively handling calls without human intervention. # Insurance Source: https://docs.usetuner.ai/docs/guides/industries/insurance Best-practice call intents, outcomes, and evaluations for voice AI agents in the insurance industry. ## 1. Overview In the insurance sector, voice AI automates and personalizes customer service for tasks like claims processing (FNOL), policy renewals, and payments. Its unique value comes from its ability to securely handle sensitive policyholder data in real-time and provide multilingual support, which boosts both operational efficiency and customer satisfaction. > [!NOTE] > > Policyholder calls carry names, addresses, and payment details. On the Growth plan you can turn on [**PII redaction**](/docs/observability/pii-redaction) to remove this sensitive data from transcripts before they are stored. ## 2. Common Call Intents This table outlines the most common reasons customers contact an insurance provider. | Intent Name | Description | Example Caller Utterance | | :- | :- | :- | | **File a Claim (FNOL)** | The policyholder is initiating a new claim, known as the First Notice of Loss. | "Hi, I need to file a new claim for a car accident I was in this morning." | | **Check Claim Status** | The policyholder wants an update on a previously filed claim. | "I'm calling to check on the status of my claim, number 12345." | | **Make a Payment** | The policyholder wishes to pay their insurance premium. | "I need to make a payment for my auto policy." | | **Get Policy Details** | The policyholder is asking for information about their current policy, like coverage limits or deductibles. | "Can you tell me what my deductible is for my homeowner's insurance?" | | **Update Policy Information** | The policyholder needs to change their policy, such as adding a new vehicle or updating their address. | "I need to add my new car to my insurance policy." | | **Request a Quote** | A potential customer is inquiring about the price for a new insurance policy. | "I'd like to get a quote for car insurance." | | **Request Policy Documents** | The policyholder needs a copy of their insurance documents, like an ID card or declarations page. | "I need a new copy of my proof of insurance card." | | **Request Roadside Assistance** | The policyholder requires emergency roadside help, such as a tow or jump start. | "I've had a flat tire and I need someone to come and help me." | ## 3. Common Call Outcomes This table lists the typical dispositions or final results of insurance-related calls. | Outcome Name | Description | Success/Failure | | :- | :- | :- | | **Claim Filed** | A new insurance claim was successfully created and a claim number was provided. | Success | | **Claim Status Provided** | The policyholder received the current status of their existing claim. | Success | | **Payment Processed** | A premium payment was successfully made by the policyholder. | Success | | **Policy Updated** | The policyholder's insurance policy was successfully modified. | Success | | **Quote Provided** | A potential customer received a price quote for a new policy. | Success | | **Documents Sent** | Requested policy documents were successfully sent to the policyholder via their preferred method. | Success | | **Transferred to Agent** | The call was transferred to a human agent (e.g., claims adjuster, underwriter). | Neutral/Failure | | **Caller Hung Up** | The caller disconnected before their issue could be resolved. | Failure | ## 4. Recommended Evaluation Criteria This section breaks down key evaluation criteria into specific, measurable checks for monitoring and improving agent performance. > [!NOTE] > > **Start from the eval library.** Part of what follows is already covered by Tuner's [predefined evals](/docs/evaluation/predefined-evals), which you enable with one click: **Required disclosures**, **Hallucination**, **Data capture accuracy**, and **Transfer handling**. Between them they cover the recording and CMS disclaimers, invented coverage or policy terms, and the completeness of what was captured on an FNOL. > > Enable those first, then add the rest as [custom evals](/docs/evaluation/custom-evals). The criteria in the tables below are written to be used as the prompt definition of a custom eval. ### Compliance & Accuracy | Evaluation Name | Description | Type | | :- | :- | :- | | **Call Recording Disclosure** | Verifies that the agent provided the legally required disclosure that the call may be recorded for quality assurance or training purposes at the beginning of the conversation. This disclosure is mandated in many jurisdictions. | Pass/Fail | | **CMS Medicare Disclaimer** | For Medicare-related calls only, ensures the agent provided the required CMS disclaimer within the first minute of the call, stating that they do not offer every plan available in the area. This is a specific regulatory requirement for Medicare sales. | Pass/Fail | | **Avoids Claim Guarantees** | Confirms that the agent refrained from making any guarantees or promises about claim outcomes, including whether a claim would be approved or the amount that would be paid out. Agents should set realistic expectations without making commitments. | Pass/Fail | | **FNOL Data Accuracy** | Evaluates the accuracy and completeness of data captured during a First Notice of Loss (FNOL) by verifying that the agent accurately captured and confirmed all critical details including date of loss, parties involved, location, and a complete description of the incident. | Pass/Fail | | **Policy Information Accuracy** | Measures the correctness of policy details communicated to the caller, ensuring that coverage, deductibles, limits, and other policy terms match the policy reference the agent was working from, with nothing approximated or invented. Add the **System Prompt** under **Inputs Used** so the evaluator has your policy details to score against. | Pass/Fail | ### Conversational Quality | Evaluation Name | Description | Type | | :- | :- | :- | | **Empathetic Tone in Claims** | Assesses the agent's ability to demonstrate empathy and provide reassurance during sensitive claim calls, particularly when the caller is describing stressful events like accidents or property damage. Higher scores indicate better emotional support and rapport building. | Scored 1-5 | | **Clarity of Explanation** | Evaluates how clearly the agent explained complex insurance terms and concepts such as deductibles, coverage limits, and policy exclusions. The agent should avoid overly technical jargon and use plain language that policyholders can easily understand. | Scored 1-5 | | **First Call Resolution** | Determines whether the agent successfully completed the policyholder's primary objective without requiring a transfer to a human representative. This includes tasks like filing claims, making payments, or updating policy information. | Pass/Fail | ## 5. Compliance & Regulatory Requirements * **State-Specific Regulations:** Insurance is regulated at the state level, so compliance with local laws regarding disclosures, licensing, and call recording is critical. * **CMS Guidelines for Medicare:** For agents handling Medicare Advantage or Part D, strict rules apply, including call recording and specific disclaimers. * **PCI DSS & GLBA:** These regulate the handling of payment card information and non-public personal information, respectively. * **TCPA:** Governs automated outbound calls and messages. ## 6. Key Performance Benchmarks * **First Call Resolution (FCR):** Industry standard is 70-79%. * **Average Handle Time (AHT):** Highly variable. A simple payment may be 2-3 minutes, while a complex FNOL call could be 10-15 minutes. * **Containment Rate:** A high rate (80%+) is a strong indicator of success. # Evals by industry Source: https://docs.usetuner.ai/docs/guides/industries/overview How to design vertical-specific evaluations for your voice AI agents, with best-practice guides for eight industries. ## Introduction to Vertical Best Practices Every industry has unique characteristics, regulatory requirements, and success metrics that shape how voice AI agents should be evaluated. While the foundational principles of evaluation remain consistent, the specific metrics and compliance requirements vary significantly across different sectors. The following vertical-specific guides provide industry-tailored best practices for implementing and evaluating voice AI agents. Each guide includes common call intents, outcomes, recommended evaluation criteria, compliance requirements, and performance benchmarks relevant to that industry. **Important Note:** The data, metrics, and benchmarks provided in these guides represent common industry standards and best practices. However, your specific implementation may vary based on your business model, regional regulations, and unique operational requirements. Use these as starting points and adapt them to fit your organization's needs. **How to read the evaluation tables:** each guide opens its evaluation section by naming the [predefined evals](/docs/evaluation/predefined-evals) that already cover ground in that industry, then lists the industry-specific checks to add on top as [custom evals](/docs/evaluation/custom-evals). Anything Tuner ships in the library is referred to by its exact name, so you can find it in the **Add evals** modal. Everything else is a prompt you write yourself in the custom eval builder. ## Available Vertical Guides * [**Automotive Dealerships**](/docs/guides/industries/automotive) - Service appointment scheduling and sales lead qualification * [**Debt Collection**](/docs/guides/industries/debt-collection) - Compliant debt recovery communications and payment arrangements * [**Financial Services & Banking**](/docs/guides/industries/financial-services) - Secure account management and transaction processing * [**Healthcare**](/docs/guides/industries/healthcare) - HIPAA-compliant patient scheduling and communications * [**Insurance**](/docs/guides/industries/insurance) - Claims processing, policy management, and customer service * [**Real Estate**](/docs/guides/industries/real-estate) - Lead qualification, property tours, and tenant support * [**Restaurants & Food Service**](/docs/guides/industries/restaurants) - Order taking and reservation management * [**Travel & Hospitality**](/docs/guides/industries/travel-hospitality) - Booking, concierge services, and guest support # Real estate Source: https://docs.usetuner.ai/docs/guides/industries/real-estate Best-practice call intents, outcomes, and evaluations for voice AI agents in real estate. ## 1. Overview In real estate (property management, leasing, and brokerages), voice AI automates communication-heavy operations like lead qualification and tenant support. This vertical is unique due to the high value and time-sensitive nature of its interactions. A positive and efficient experience directly influences leasing success, resident retention, and sales conversions, making the quality of every call critical. > [!NOTE] > > Leasing and tenant calls capture names, phone numbers, home addresses, and financial qualification details. On the Growth plan you can turn on [**PII redaction**](/docs/observability/pii-redaction) to keep them out of stored transcripts. ## 2. Common Call Intents This table outlines the most common reasons individuals contact a real estate or property management company. | Intent Name | Description | Example Caller Utterance | | :- | :- | :- | | **Request Maintenance** | A current tenant is reporting a maintenance issue in their unit or a common area. | "Hi, my garbage disposal is making a weird noise and won't turn on." | | **Inquire About Rent** | A tenant has a question about their rent payment, including the amount, due date, or payment methods. | "I just want to double-check when my rent is due this month." | | **Check Availability** | A prospective tenant or buyer is calling to inquire about available units or properties. | "I'm looking for a two-bedroom apartment, do you have anything available for next month?" | | **Schedule a Tour/Showing** | A prospective tenant or buyer wants to schedule a time to see a property. | "I'd like to schedule a tour of the one-bedroom you have listed online." | | **Make a Complaint** | A tenant is reporting a complaint about a neighbor, noise, or other property-related issue. | "My upstairs neighbor has been playing loud music late at night again." | | **Ask About Lease Terms** | A tenant has a question about their current lease agreement. | "I was wondering what the policy is on having guests stay over for a week." | ## 3. Common Call Outcomes This table lists the typical dispositions or final results of real estate-related calls. | Outcome Name | Description | Success/Failure | | :- | :- | :- | | **Tour/Showing Booked** | A property viewing was successfully scheduled with a prospective tenant or buyer. | Success | | **Maintenance Request Created** | A new maintenance ticket was successfully logged in the property management system. | Success | | **Qualified Lead Captured** | A new prospective tenant/buyer's contact information and needs were recorded and passed to an agent. | Success | | **Issue Resolved** | The caller's question or problem was fully addressed on the call. | Success | | **Escalated to Manager/Agent** | The call was transferred to a human (e.g., property manager, leasing agent) for further assistance. | Neutral | | **Voicemail Left** | The caller was sent to voicemail because the AI could not handle the request or no one was available. | Failure | ## 4. Recommended Evaluation Criteria This section breaks down key evaluation criteria into specific, measurable checks for monitoring and improving agent performance. > [!NOTE] > > **Start from the eval library.** Part of what follows is already covered by Tuner's [predefined evals](/docs/evaluation/predefined-evals), which you enable with one click: **Prohibited content**, **Hallucination**, **Data capture accuracy**, **Structured intake completeness**, and **Politeness**. Between them they cover discriminatory language, invented listing details, and whether the qualification and maintenance intake captured everything it needed. > > Enable those first, then add the rest as [custom evals](/docs/evaluation/custom-evals). The criteria in the tables below are written to be used as the prompt definition of a custom eval. ### Accuracy & Compliance | Evaluation Name | Description | Type | | :- | :- | :- | | **Fair Housing Act Compliance** | Ensures the agent avoided any discriminatory language or questions throughout the conversation. The agent must refrain from asking questions or making statements related to the caller's race, color, religion, sex, familial status, or national origin, as mandated by the Fair Housing Act. | Pass/Fail | | **Accurate Property Information** | Verifies that the agent provided correct and current details about the property including price, availability, amenities, pet policies, and parking arrangements, with every claim traceable to the listing data the agent was given rather than filled in from assumption. Add the **System Prompt** under **Inputs Used** so the evaluator scores against your current listing details. | Pass/Fail | | **Accurate Maintenance Intake** | Evaluates the precision of maintenance request creation by confirming that the agent accurately captured the nature of the maintenance issue, the correct unit number, and the best contact information for the tenant to ensure proper follow-up. | Pass/Fail | ### Conversational & Sales Quality | Evaluation Name | Description | Type | | :- | :- | :- | | **Lead Qualification Effectiveness** | Assesses how well the agent qualified prospective tenants or buyers by asking key questions about their specific needs (such as number of bedrooms, desired features), budget constraints, and desired move-in date or purchase timeline. Higher scores indicate more thorough qualification. | Scored 1-5 | | **Tour Scheduling Efficiency** | Measures the agent's ability to book property tours cleanly: offering available times that fit the caller's stated preferences and confirming one specific slot, without repeated back-and-forth or leaving the caller without a booked time. | Pass/Fail | | **Empathetic Tone (Complaints)** | Evaluates the agent's ability to demonstrate empathy and build positive rapport with callers who are expressing complaints or maintenance concerns. Higher scores indicate better emotional intelligence and tenant relationship management. | Scored 1-5 | | **Professionalism & Etiquette** | Assesses the agent's overall professionalism including professional language, courteous phrasing, appropriate greetings and closings, and adherence to proper call handling procedures throughout the entire conversation. | Scored 1-5 | ## 5. Compliance & Regulatory Requirements * **Fair Housing Act (FHA):** Prohibits any form of housing discrimination. * **Telephone Consumer Protection Act (TCPA):** Requires prior consent for automated marketing calls and texts. * **State and Local Regulations:** Many states and cities have specific laws governing licensing, disclosures, and rental agreements that must be followed. ## 6. Key Performance Benchmarks * **First Call Resolution (FCR):** 70-75% for tenant and prospect inquiries. * **Call Abandonment Rate:** Should be kept below 5%. * **Service Level:** 80% of calls answered within 20 seconds is a common industry goal. # Restaurants & food service Source: https://docs.usetuner.ai/docs/guides/industries/restaurants Best-practice call intents, outcomes, and evaluations for voice AI agents in restaurants and food service. ## 1. Overview In the restaurant and food service industry, voice AI is primarily used to automate the order-taking process, both over the phone and in drive-thrus. This vertical is unique due to its demand for high speed and accuracy in often noisy environments. A successful voice AI can significantly reduce wait times, improve order accuracy, and increase average order value through automated, consistent upselling. > [!NOTE] > > Phone and delivery orders capture customer names, phone numbers, delivery addresses, and card details. On the Growth plan you can turn on [**PII redaction**](/docs/observability/pii-redaction) to keep them out of stored transcripts. ## 2. Common Call Intents This table outlines the most common reasons customers call a restaurant. | Intent Name | Description | Example Caller Utterance | | :- | :- | :- | | **Place an Order** | The customer wants to place a new order for pickup or delivery. | "I want to order a large pepperoni pizza and a side of wings." | | **Check Order Status** | The customer is calling to check on the status of an existing order. | "I placed an order about 20 minutes ago and I was just wondering if it is ready for pickup." | | **Make a Reservation** | The customer wants to book a table at a sit-down restaurant. | "I would like to make a reservation for two people at 7 PM tonight." | | **Ask About a Menu Item** | The customer has a question about a specific menu item, such as ingredients, price, or allergens. | "Does your cheeseburger have onions on it? And is it gluten-free?" | | **Get Store Hours or Location** | The customer wants to know the restaurant's hours of operation or address. | "What time do you close tonight?" | ## 3. Common Call Outcomes This table lists the typical dispositions or final results of restaurant calls. | Outcome Name | Description | Success/Failure | | :- | :- | :- | | **Order Placed** | A new order was successfully placed and confirmed with the customer. | Success | | **Reservation Made** | A new reservation was successfully booked and confirmed. | Success | | **Information Provided** | The customer's question was answered, and the issue was resolved. | Success | | **Transferred to Staff** | The call was transferred to a human employee for further assistance (e.g., for a complex issue). | Neutral/Failure | | **Caller Hung Up** | The caller disconnected before their order or inquiry was completed. | Failure | | **Order Not Placed** | The caller decided not to proceed with placing an order. | Failure | ## 4. Recommended Evaluation Criteria This section breaks down key evaluation criteria into specific, measurable checks for monitoring and improving agent performance. > [!NOTE] > > **Start from the eval library.** Part of what follows is already covered by Tuner's [predefined evals](/docs/evaluation/predefined-evals), which you enable with one click: **Data capture accuracy**, **Confirmation accuracy**, **Hallucination**, **Tool args mismatch**, **Unnecessary repetition**, and **Conversation flow and turn taking**. Between them they cover the items and modifications as captured, the read-back at the end, invented menu or price details, what was sent to your ordering system, and how many turns the order took. > > Enable those first, then add the rest as [custom evals](/docs/evaluation/custom-evals). The criteria in the tables below are written to be used as the prompt definition of a custom eval. ### Order & Transactional Accuracy | Evaluation Name | Description | Type | | :- | :- | :- | | **Order Item Accuracy** | Verifies that the agent correctly identified and added every food and drink item the customer requested to the order without omissions or incorrect items. This is fundamental to order accuracy and customer satisfaction. | Pass/Fail | | **Order Modification Accuracy** | Evaluates whether the agent accurately captured all special requests and modifications such as "no onions," "extra cheese," "sauce on the side," or other customizations. Accurate modification capture is critical for customer satisfaction. | Pass/Fail | | **Price Calculation Accuracy** | Confirms that the agent quoted the correct total price for the order, including all items, modifications, applicable taxes, and any additional fees. Price accuracy builds customer trust and prevents billing disputes. | Pass/Fail | ### Conversational Quality & Efficiency | Evaluation Name | Description | Type | | :- | :- | :- | | **Upsell Effectiveness** | Assesses the agent's ability to make relevant and contextually appropriate upsell attempts, such as suggesting a drink with a combo meal or dessert with an entree. Higher scores indicate better sales techniques and successful upsells that enhance revenue. | Scored 1-5 | | **Ordering Efficiency** | Evaluates whether every turn moved the order forward. Penalize re-asking for details the customer already gave, repeating the full order more often than needed, and detours that add turns without adding information. Wasted turns are the largest controllable driver of handle time on high-volume phone and drive-thru orders. | Scored 1-5 | | **Handling of Ambiguity** | Measures the agent's ability to recognize and clarify unclear customer requests by asking appropriate clarifying questions (such as "Did you say large or medium?") rather than making assumptions that could lead to order errors. | Pass/Fail | | **Misrecognition Recovery** | Evaluates whether the agent caught and repaired a mis-heard item instead of carrying it into the order. Look for the customer correcting the agent ("no, I said *large*") or a read-back that doesn't match what was asked for, and whether the agent re-confirmed before moving on. Phone and drive-thru orders are noisy, and recovery is what separates a corrected order from a wrong one. | Pass/Fail | ## 5. Compliance & Regulatory Requirements * **Payment Card Industry Data Security Standard (PCI DSS):** For any phone orders involving credit card payments, the voice AI and payment processing system must be PCI DSS compliant to ensure the secure handling of cardholder information. ## 6. Key Performance Benchmarks * **Order Accuracy:** 95% or higher * **Upsell Acceptance Rate:** 40-50% * **Average Handle Time (AHT):** Under 2 minutes for typical phone orders # Travel & hospitality Source: https://docs.usetuner.ai/docs/guides/industries/travel-hospitality Best-practice call intents, outcomes, and evaluations for voice AI agents in travel and hospitality. ## 1. Overview In the travel and hospitality industry, voice AI automates a wide range of guest interactions, from booking reservations to providing 24/7 virtual concierge services. This vertical is unique due to the high value of each interaction and the critical importance of providing a personalized, seamless, and high-end guest experience. A successful voice AI can not only increase direct bookings and ancillary revenue but also significantly improve guest satisfaction and loyalty. > [!NOTE] > > Reservation calls capture guest names, contact details, and payment card data. On the Growth plan you can turn on [**PII redaction**](/docs/observability/pii-redaction) to strip card numbers and guest identifiers from transcripts before they are stored. ## 2. Common Call Intents This table outlines the most common reasons customers contact a hotel, airline, or travel agency. | Intent Name | Description | Example Caller Utterance | | :- | :- | :- | | **Make a Reservation** | The customer wants to make a new reservation for a hotel room, flight, or rental car. | "I want to book a king room for two nights, checking in on Friday." | | **Modify a Reservation** | The customer needs to make a change to an existing reservation, such as dates or room type. | "I need to change my flight to a later time on the same day." | | **Cancel a Reservation** | The customer wants to cancel an existing reservation. | "I need to cancel my hotel reservation for this weekend." | | **Inquire About Amenities** | The customer has a question about the amenities offered by the hotel, resort, or airline. | "Do you have a swimming pool and is it open now?" | | **Request Concierge Service** | The guest needs assistance with a concierge service, such as booking a tour, making a dinner reservation, or arranging transportation. | "Can you recommend a good Italian restaurant near the hotel and book a table for two?" | | **Ask About Loyalty Program** | The customer has a question about their loyalty program account, points balance, or benefits. | "I wanted to check how many points I need to book a free night." | ## 3. Common Call Outcomes This table lists the typical dispositions or final results of hospitality-related calls. | Outcome Name | Description | Success/Failure | | :- | :- | :- | | **Reservation Booked** | A new reservation was successfully booked and a confirmation number was provided. | Success | | **Reservation Modified** | An existing reservation was successfully changed and confirmed. | Success | | **Reservation Cancelled** | An existing reservation was successfully cancelled and a cancellation number was provided. | Success | | **Information Provided** | The customer's question about amenities, loyalty, or services was answered. | Success | | **Transferred to Staff** | The call was transferred to a human agent (e.g., front desk, group sales, concierge). | Neutral | | **Caller Hung Up** | The caller disconnected before their inquiry was completed. | Failure | ## 4. Recommended Evaluation Criteria This section breaks down key evaluation criteria into specific, measurable checks for monitoring and improving agent performance. > [!NOTE] > > **Start from the eval library.** Part of what follows is already covered by Tuner's [predefined evals](/docs/evaluation/predefined-evals), which you enable with one click: **Data capture accuracy**, **Confirmation accuracy**, **Required disclosures**, **Hallucination**, **Tool response mismatch**, and **Politeness**. Between them they cover the booking details as captured and confirmed, the cancellation policy, invented rates or availability, and what the booking system actually returned. > > Enable those first, then add the rest as [custom evals](/docs/evaluation/custom-evals). The criteria in the tables below are written to be used as the prompt definition of a custom eval. ### Booking & Transactional Accuracy | Evaluation Name | Description | Type | | :- | :- | :- | | **Reservation Booking Accuracy** | Evaluates the precision of the booking process by verifying that the agent correctly captured and confirmed all essential details including the guest's name, contact information, dates of stay, room or flight type, and number of guests. Accuracy in this area prevents booking errors and guest frustration. | Pass/Fail | | **Cancellation Policy Communication** | Assesses whether the agent clearly communicated the cancellation policy during the booking process, including specific deadlines, any applicable fees, and the process for making changes. Clear policy communication prevents disputes and sets proper expectations. | Pass/Fail | | **Payment Processing Compliance** | Verifies that the agent kept card data out of the spoken conversation when taking payment for a booking: never reading a full card number back to the guest, never asking the guest to say a CVV aloud, and routing to secure capture at the point of payment. This is what keeps reservation calls inside PCI scope. | Pass/Fail | ### Guest Experience & Quality | Evaluation Name | Description | Type | | :- | :- | :- | | **Personalization** | Measures the agent's ability to create a personalized guest experience by using the guest's name throughout the conversation and referencing their loyalty program status, past stay history, or stated preferences. Higher scores indicate better relationship building and guest engagement. | Scored 1-5 | | **Upsell & Cross-Sell Effectiveness** | Evaluates the agent's ability to identify and present relevant opportunities to drive ancillary revenue through upsells and cross-sells such as room upgrades, spa packages, dining reservations, or late check-out options. Higher scores indicate better revenue optimization. | Scored 1-5 | | **Brand Voice Adherence** | Assesses whether the agent's tone, language, and communication style align with the property's brand positioning, whether luxury high-end, mid-range business travel, or budget-friendly accommodation. Consistency with brand voice reinforces brand identity. | Scored 1-5 | | **Local Knowledge (Concierge)** | Evaluates the quality and relevance of the agent's concierge recommendations for local restaurants, attractions, and activities based on the guest's stated preferences, interests, and needs. Higher scores indicate more helpful and personalized recommendations. | Scored 1-5 | ## 5. Compliance & Regulatory Requirements * **Payment Card Industry Data Security Standard (PCI DSS):** Essential for securely handling credit card information during bookings. * **General Data Protection Regulation (GDPR):** Critical for businesses with customers in the European Union, governing the handling of personal data. ## 6. Key Performance Benchmarks * **Look-to-Book Ratio:** 10% or higher for direct voice channels. * **Average Daily Rate (ADR) & Revenue Per Available Room (RevPAR):** These vary significantly by market and property type, but the voice AI's performance should be measured against the property's overall goals. * **Ancillary Revenue Per Booking:** Track the revenue generated from upsells and cross-sells made by the voice AI. # Technical vs. business evals Source: https://docs.usetuner.ai/docs/guides/technical-vs-business-evals Why technical metrics like WER and latency aren't enough, and how business evals measure whether your voice agent actually achieves its goal. When evaluating a voice AI agent, it's easy to get lost in a sea of technical metrics like Word Error Rate (WER), latency, and transcription accuracy (Tuner scores the last one on [replays](/docs/observability/voice-metrics#transcription-accuracy)). These metrics are important—they form the technical foundation of a good conversational experience. However, at Tuner, we believe they are not enough. Think about it this way: an agent can have a perfect WER and still fail to understand a user's intent. It can have flawless grammar and still violate a critical industry regulation. It can respond in under 500 milliseconds and still leave the customer without a booked appointment. This is why our philosophy at Tuner is built on a simple truth: **a technically perfect agent that doesn't achieve the business goal is a business failure.** This is the critical distinction between **Technical Evals** and **Business Evals**: * **Technical Evals** measure *how* the agent works. They focus on the performance of the underlying STT, LLM, and TTS models. * **Business Evals** measure *what* the agent accomplishes. They focus on the outcomes of the conversation and whether the business goal was achieved. To truly understand agent performance, you need both. But the focus must shift from a purely technical view to a business-first approach. This is the core of our direction at Tuner. **Ready to build a business-first evaluation strategy?** > **Next:** Learn how to implement the 4-Layer Framework we've built into the core of the Tuner platform. > [**Go to The Business Evals Framework →**](/docs/guides/business-evals-framework) # Test your agent before every change Source: https://docs.usetuner.ai/docs/guides/testing-strategy A testing workflow for voice agents: what to test before launch, how to build a regression suite, what to rerun after every change, and how production failures become tests. > [!NOTE] > > Testing in Tuner happens under **Simulations**. You need an agent set up for [inbound](/docs/simulation/inbound/setup) or [outbound](/docs/simulation/outbound) simulation. Replays of Dataset calls work with either. This guide ties together [generated runs](/docs/simulation/run-a-simulation), the [Scenario Library](/docs/simulation/scenarios) and [replays](/docs/simulation/replays) of [Dataset](/docs/datasets/overview) calls. It covers four stages: before launch, building a regression suite, after every change, and turning production failures into tests. For the production side, see [Best practices for agent monitoring](/docs/guides/agent-monitoring). ## Which tool for which question | Question | Tool | Why | | - | - | - | | Where does my agent break that I haven't seen yet? | Generated run (**AI generated** Scenarios) | Tuner writes new Scenarios each run: Routine callers from your Intents, Pressure tests from your Pass/Fail evals. | | Did this change break something that used to work? | Scenario Library (a Regression Run) | You rerun the same saved Scenarios. Each one keeps a **Run history**. | | Does my fix work on the exact call that failed? | Replay of a Dataset call | The caller is the real recorded audio, identical on every run. | | Is a new model or provider better on my callers? | Replay of a Dataset call | Same calls and same scoring on both setups, with latency measured on every run. See [Benchmarking](/docs/datasets/use-cases/benchmarking). | | Does my agent hold up with an accent, a language or noise I have no recordings of? | Generated run or Scenario Library | You choose the language, accent, background noise and test profile on every run. Replays use whatever the real call had. | | Does the conversation branch correctly on my agent's answers? | Generated run or Scenario Library | The Simulated Caller reacts to your agent. In a replay, [the caller doesn't adapt](/docs/datasets/use-cases/capturing-failures#the-caller-doesnt-adapt). | ## Before launch Simulation grades calls on your **Pass/Fail** evals, so set those up first. Pressure tests are generated from them, the Scenario Library needs at least one, and a replay without any only measures latency. * **Add Pass/Fail evals** in **Agent Settings > Evaluation Rules**. New agents start with **Hallucination**, **Prompt injection resistance** and **Politeness**. Add the tool-call evals if your agent uses tools, and [custom evals](/docs/evaluation/custom-evals) for your business rules. Score (1 to 5) evals don't decide a call's result. * **Set up your Intents**, since Routine callers are generated from them. See [Call classification](/docs/evaluation/call-classification). * **Create [test profiles](/docs/simulation/test-profiles)** for the data your agent needs from a caller, such as a name, an account detail or an appointment date. Without a profile, the Simulated Caller has no caller-specific context. * **Run a generated simulation** with a mix of Routine callers and Pressure tests. The default is 10 calls with 30% Pressure tests. Read the failures, fix your agent, and run again. * **Match your callers' conditions.** Set **Language:** to the languages and accents your callers use, and **Environment:** to the noise they call from (**Café**, **Office**, **Street** or **Car**, at **Low**, **Medium** or **High**). Each setting applies to the whole run, so run once per condition you care about. * **Narrow the targets** with **Narrow down ›** when you change one Intent or one eval, so the run spends its calls there. * **Upload recordings you already have.** If you have real calls from another system, [upload them](/docs/datasets/add-calls#add-a-call) to your Dataset and replay them before your agent takes a call in Tuner. ## Build a regression suite Your suite is two sets: Scenarios in the Scenario Library and calls in your Dataset. Add to both every time something fails. * **Save the Scenarios that caught a failure.** On the **Runs** tab, expand the run, tick the calls and click **Save to library**. The call you saved from becomes the first entry in the Scenario's **Run history**. See [Save to library from a run](/docs/simulation/scenarios#save-to-library-from-a-run). * **Write Custom Scenarios** for edge cases you know about but haven't seen in a run. For a Pressure Scenario, set a **Target eval** so it passes or fails on that eval alone. See [Write a Custom Scenario](/docs/simulation/scenarios#write-a-custom-scenario). * **Tag your Scenarios** (for example by Intent or by the eval they target) so you can find the right set for a change. * **Add real failing calls to your Dataset.** On **Simulations > Dataset**, click **Add call** and pick the call from **Production**. Name it after the problem. See [Capturing failures](/docs/datasets/use-cases/capturing-failures). * **Add golden calls**: ordinary calls your agent handles well today. They show when a fix for one problem breaks something that used to work. Saved Scenarios keep the situation, goal, type, Intent and **Target eval**. They don't keep the language, background noise or test profile, so choose those on each rerun. ## After every change Rerun your suite after a prompt edit, a model swap, a new STT or TTS provider, or a deployment. **1. Rerun the Scenario Library** In **Run Simulation**, click **Change** next to **Scenarios**, choose **From library**, and tick up to 20 Scenarios. Use the same language, noise and test profile as the runs you're comparing with. See [Rerun after every change](/docs/simulation/scenarios#rerun-after-every-change). **2. Replay your Dataset** Go to **Simulations > Replays** and click **New Replay**. Pick the Dataset calls that cover what you changed, and replay each one more than once so you can tell a real change from normal variation. See [Replay a Dataset call](/docs/simulation/replays#replay-a-dataset-call). **3. Run a generated simulation** Generated runs write new Scenarios, so they look for failures your suite doesn't cover yet. Narrow the targets to the Intents or evals you changed. **4. Compare the runs** * **Scenario Library:** on the **Scenarios** tab, **Last result** shows each Scenario's latest result. Open a Scenario to see its **Run history**, for example "Passed 3 of last 5 runs". * **Replays:** keep the same calls, repeats, **Max call duration** and **Advanced turn-taking** settings between runs, then compare the run cards and open matching calls. There's no side-by-side view. Only one simulation run can be in progress per agent at a time, shared by generated runs, library runs and replays. A run whose calls have all ended doesn't block the next one. When you compare two setups, change one thing at a time so any difference has one cause. See [Compare two setups](/docs/datasets/use-cases/benchmarking#compare-two-setups). ## Turn production failures into tests When [monitoring](/docs/guides/agent-monitoring) finds a failure, such as a failed eval, a [red flag](/docs/evaluation/red-flags) or a failure outcome, add it to your suite before you fix it. | What you found | Add it as | How | | - | - | - | | A production call that failed on audio, timing or STT (noise, accent, interruptions) | A Dataset call | **Add call** > **Production**, then replay it to reproduce the failure before you change anything. See [From failure to verified fix](/docs/datasets/use-cases/capturing-failures#from-failure-to-verified-fix). | | A failure that depends on how the conversation goes, or an outbound call | A Custom Scenario | Write the caller's situation from the call in **Situation**, and set the eval that failed as the **Target eval** for a Pressure Scenario. | | A red flag or eval that keeps failing | A narrowed generated run | Narrow **Pressure tests target:** to that eval, then save the Scenarios that fail to your library. | Simulation calls don't appear in the **Production** list when you add a Dataset call. To keep a failing simulated call, save its Scenario to the library. ## Read the results Each call shows one result. What to do depends on which one. See [Run statuses](/docs/simulation/run-statuses) for every status. | Result | What it means | What to do | | - | - | - | | **Passed** | No Pass/Fail eval that decides the result failed. | Nothing. For a Scenario that used to fail, check its **Run history** to confirm the fix held across runs. | | **Failed** | An eval that decides the result failed, or the call didn't run. | Open the call to see which eval failed and why. Fix your agent, save the Scenario or add the call to your Dataset, and rerun it. | | **Unreported** | The call ran, but no matching call arrived from your agent within 15 minutes. | This is an integration problem, not an agent failure. Follow [Fix an Unreported run](/docs/simulation/run-statuses#fix-an-unreported-run). | | **Analysis failed** | The call arrived, but its evals didn't come back within 10 minutes. | Run the Scenario again. If it keeps happening, contact support. See [Fix Analysis failed](/docs/simulation/run-statuses#fix-analysis-failed). | The Simulated Caller improvises, so the same Scenario can pass once and fail once. Rerun a failing Scenario before you treat it as fixed or broken, and use a replay when you need the exact same caller. A replay call also shows [transcription accuracy](/docs/observability/voice-metrics#transcription-accuracy) on its **Voice Metrics** tab. ## Limits | Limit | Value | | - | - | | Generated run | 5 to 20 calls, default 10 | | Scenarios from library per run | 1 to 20, each runs once | | Replay run | 1 to 10 calls, each 1 to 20 times, at most 20 calls in total | | Max call duration | 1 to 12 minutes (default 3 for simulation runs) | | Runs in progress per agent | 1, shared by all simulation runs | ## Next steps > [card] [Scenario Library](/docs/simulation/scenarios) > > Save Scenarios and rerun them after every change. > [card] [Capturing failures](/docs/datasets/use-cases/capturing-failures) > > Reproduce the call that failed and prove your fix. # Tuner features Source: https://docs.usetuner.ai/docs/guides/tuner-features Every feature in Tuner, what it does, when it is useful, and how the pieces fit together. This page lists every Tuner feature, what it does and when it's useful, with a link to the page that covers it. You connect an agent once and define what a good call looks like. That definition scores your production calls and the test calls Tuner places against your agent, so testing needs no second configuration. > [card] [New here?](/docs/getting-started/quickstart) > > The Quickstart connects an agent and gets your first call evaluated. > [card] [Want the vocabulary first?](/docs/resources/glossary) > > The glossary defines every term used across the product. *** ## Connecting your agent The only job of an integration is to **get the finished call to Tuner**. Once Tuner has it, everything on this page happens on Tuner's side: transcript, per-turn timing, classification, evals, red flags, and alerts. Which route you take depends only on what you build on, and every route produces the same result once the call lands. | Feature | What it does | When you want it | | - | - | - | | [**Retell integration**](/docs/integrations/retell) | Connect your Retell API key in the setup wizard and pick an agent. Tuner sets up the webhook for you. | You run on Retell and want no code at all. | | [**Vapi integration**](/docs/integrations/vapi) | Same one-key setup using your Vapi private key. | You run on Vapi. | | [**Vapi transient assistants**](/docs/integrations/vapi-transient-assistants) | Handles Vapi assistants defined per call instead of stored in the Vapi dashboard, including exact interruption data from the call log. | Your assistant config is generated at call time. | | [**Dograh node**](/docs/integrations/dograh) | A Tuner node you drop into your Dograh workflow. | You build in Dograh. | | [**LiveKit SDK**](/docs/integrations/livekit) | Python and Node plugins for LiveKit Agents that capture turns, per-stage latency, tool calls, usage, and cost. | You run LiveKit Agents, self-hosted or on LiveKit Cloud. | | [**Pipecat SDK**](/docs/integrations/pipecat) | An observer you attach to your Pipecat pipeline, capturing the same detail. | You run Pipecat. | | [**Custom stack**](/docs/integrations/custom-stack/overview) | Two ways to send a call from anything else. The [custom SDK](/docs/integrations/custom-stack/sdk-quickstart) attaches Python observers to your own [speech-to-text](/docs/integrations/custom-stack/speech-to-text), [text-to-speech](/docs/integrations/custom-stack/text-to-speech), LLM, or [LangChain](/docs/integrations/custom-stack/langchain) components and sends everything in one `flush()` at call end. The [Custom API](/docs/integrations/custom-stack/direct-api) takes a call payload you build yourself, from any language. | You are on any other platform, for example Plivo, Bland, or Twilio, or on a stack you built yourself. | | [**Webhooks**](/docs/integrations/webhooks) | Tuner sends events out: `call.analyzed` and `alert.fired`. For Retell it also forwards the `call_analyzed` payload, and for Vapi the `end-of-call-report` payload. | You want Tuner events in Slack, PagerDuty, n8n, or your own service. | | [**Templates**](/docs/getting-started/quickstart#step-2-choose-how-to-configure-it) | Starting configurations (support, appointment booking, medical receptionist, food ordering, real estate, payment reminders, lead qualification, and more) that add intents, data-extraction fields, evals, red flags and alerts. | You want eval results on your first call. | | [**API keys**](/docs/getting-started/api-keys) | Workspace keys that SDKs, the public API and MCP clients use. Each key is shown once and can be revoked. | You send calls from your own code or connect an MCP client with a key. | **Worth knowing:** for monitoring, traffic goes one way, from your stack to Tuner over HTTPS. Tuner needs no route into your network, so a fully self-hosted agent connects the same way a managed one does. *** ## Seeing what happened on a call | Feature | What it does | When you want it | | - | - | - | | [**Overview dashboard**](/docs/observability/overview) | Headline metrics, intent and outcome breakdowns, and the recent red flag queue over the period you pick. | Your daily pulse check. Is this broadly healthy, or degraded across the board? | | [**Call Logs**](/docs/observability/call-logs) | Every call in a list you can filter and search. Open a call for its transcript and its **Overview**, **Evals**, **Voice Metrics**, **Data Extraction** and **Traces** tabs. | You need to read exactly what was said and what the agent did. | | [**Voice metrics and latency**](/docs/observability/voice-metrics) | Per-turn latency split by pipeline stage: end of utterance, STT, LLM, TTS, and time to first byte. Plus conversation shape metrics like longest agent monologue, and transcription accuracy on replay calls. | The agent feels slow and you need to know which stage is responsible, or you want to know how well its speech-to-text hears a replayed caller. | | [**Root cause analysis**](/docs/observability/root-cause-analysis) | A structured way to work a single failing call from symptom to cause using the Call Details view. | One call went wrong and you need to understand why before changing anything. | | [**OpenTelemetry traces**](/docs/observability/traces) | The LiveKit Python and Pipecat SDKs forward OpenTelemetry spans for you; any other stack can send them over OTLP/HTTP to `https://api.usetuner.ai/api/v1/traces`. Tuner shows them as a span tree on the matching call. | You run OpenTelemetry and want your spans next to the transcript. | **Worth knowing:** the depth of the latency breakdown depends on how you connected. Platforms that hand over a finished transcript can only tell you a call was slow. The SDKs record each stage as it happens, which is what turns "slow" into "the LLM stage added 900ms on turn four". *** ## Judging every call This is where you tell Tuner what a good call looks like. Everything defined here runs on production calls and simulated calls alike. | Feature | What it does | When you want it | | - | - | - | | [**Call outcomes and intents**](/docs/evaluation/call-classification) | Classify each call by what the caller wanted and how it ended, with your own definitions of success and failure. | You want to know how often the agent books the appointment, in addition to how many calls came in. | | **Data extraction** | Pull structured fields out of the conversation, for example the appointment date or the quoted price, and file them against the call. | You need call content as data you can filter and report on. | | [**Predefined evals**](/docs/evaluation/predefined-evals) | 27 ready-to-use evals in four categories. Add any of them from the eval library. | You want coverage of the common failure modes without writing anything. | | [**Custom evals**](/docs/evaluation/custom-evals) | Write your own criteria in plain language, scored Pass/Fail or 1 to 5, and choose what evidence the judge can see under **Inputs Used**: system prompt, tools, allowed capabilities, workflow, or per-call metadata. | You have a rule specific to your business, like a disclaimer that must be read verbatim. | | [**Evals for dynamic agents**](/docs/evaluation/dynamic-agents) | Score agents whose instructions change per call by passing those instructions as metadata and evaluating against them. | Multi-tenant agents, or personas that vary per session. | | [**Red flags and labels**](/docs/evaluation/red-flags) | Rules that tag a call when its conditions match, on an eval, a voice metric, a data field or call metadata. Red flags mark a call as a problem; labels categorize it. | You want problem calls marked so someone looks at them. | | [**Alerts**](/docs/observability/alerts) | A notification when calls matching your conditions reach a threshold in a time window. An alert can combine several conditions, including red flags. Delivered by email or to your webhook. | You want to hear about a problem without checking the dashboard. | **Worth knowing:** an eval judge can read the tool calls and results and the agent's own instructions, as well as the transcript. So an eval can check facts, for example "The agent quoted a delivery time the tool never returned". See [What an eval judges](/docs/evaluation/overview#what-an-eval-judges). Evals also run in whatever language the call happened in, so a multilingual agent needs one set of evals. *** ## Testing before your customers do [Call Simulation](/docs/simulation/overview) places real voice calls against your agent and scores them with the evals you already configured. It is available on every plan, starting with Pay as You Go. Simulated calls use credits. | Feature | What it does | When you want it | | - | - | - | | [**Inbound simulation**](/docs/simulation/inbound/setup) | Tuner dials into your agent over SIP, like a customer calling in. Guides for [Vapi](/docs/simulation/inbound/setup#vapi), [Retell](/docs/simulation/inbound/setup#retell), and [SIP providers](/docs/simulation/inbound/other-platforms). | Your agent receives calls. | | [**Outbound simulation**](/docs/simulation/outbound) | Tuner triggers your endpoint with a SIP URI, and your agent dials Tuner's Simulated Caller. Guides for Vapi, LiveKit, Pipecat, and Custom API. | Your agent places calls. | | **Routine Callers** | Cooperative, on-topic callers generated from your configured intents. | Checking the happy path still works after a change. | | **Pressure Tests** | Difficult callers auto-generated from your evals: hallucination bait, scope boundary pushing, escalation demands, offensive language, personal data requests. | Finding the breaking point before a real customer does. | | **Intent and eval targeting** | Narrow a run to specific intents or specific failure modes. | You changed one workflow and want to test that one workflow. | | [**Test profiles**](/docs/simulation/test-profiles) | Give the simulated caller an identity and context before the call: name, account details, urgency, whatever your agent needs. Snapshotted at run time so past results stay valid. | Your agent behaves differently for a new user than a returning one. | | **Languages and accents** | Run simulations in English (US, UK, AU), Spanish (ES, MX), French (FR, CA), German (DE, AT, CH), Arabic (SA, EG, AE), Italian (IT) or Hindi (IN). | Testing a multilingual agent, or how yours handles an accent it was not tuned on. | | **Max call duration** | Caps how long any single simulated call can run: 1 to 12 minutes, 3 by default. | Keeping a stuck agent from looping, and keeping batch cost predictable. | | **Simulation runs** | 5 to 20 calls per run, 10 by default, each with its own Scenario. | The same request phrased ten ways produces ten different conversations, and more calls cover more of them. | | [**Datasets**](/docs/datasets/overview) | The caller's side of your real calls, from production or an uploaded stereo recording, cut into caller turns and ready to replay. | You want to keep your hardest real calls as tests: to prove fixes and to compare setups on your own callers. | | [**Replays**](/docs/simulation/replays) | Plays a Dataset call's caller turns into a live call with your agent, with the same caller audio every run, graded against your Pass/Fail evals and scored for transcription accuracy. | Reproducing a call that broke, proving a fix, or comparing two setups with nothing else moving. | *** ## Configuring, diagnosing, and automating | Feature | What it does | When you want it | | - | - | - | | [**MCP server**](/docs/mcp/setup) | Connects your Tuner workspace to Claude, Claude Code, Cursor or Antigravity, with read and write access. Describe the agent you want and the assistant creates the outcomes, intents, evals, red flags, and alerts. In beta. | You would rather describe a configuration than fill in forms. | | [**Diagnose your agent**](/docs/mcp/diagnose) | Reads your real call data, finds what is failing and why, then adds the evals and data capture that measure it and drafts the prompt change. | The dashboard shows something is wrong across many calls and you want the pattern. | | [**Public API**](/api-reference/calls/create-call) | Create and update agents, push calls, read them back. | Provisioning agents programmatically, or building Tuner into your own tooling. | *** ## Data and compliance controls | Feature | What it does | When you want it | | - | - | - | | [**PII redaction**](/docs/observability/pii-redaction) | Detects names, phone numbers, addresses, national IDs, card numbers, and spoken PINs in each transcript and replaces them with labels. Recordings are not redacted. Each call shows its redaction status: **Redacted**, **Partial** or **Failed**. Workspace-wide, on the Growth plan. | Regulated data on your calls, or a policy against storing caller details. | | [**Data retention**](/docs/observability/data-retention) | Sets how long call data is kept and what is erased when it expires, from 7 days to 1 year, plus **Never** on Enterprise. Workspace-wide. | Any compliance policy with a fixed data lifetime. | Where your agent runs and where Tuner runs are separate questions. Your agent can be entirely self-hosted on any plan. Tuner itself runs as a hosted cloud service, with **on-premise deployment available on Enterprise**, alongside SOC 2 and HIPAA compliance, custom integrations, and a DPA on request. See the [FAQ](/docs/resources/faq) for both. *** ## How Tuner compares Useful when you are comparing tools. > [accordion] One configuration for testing and production > > In Tuner the evals, outcomes, and intents you define score both simulated and production calls, so you write your criteria once. A behavior you catch in simulation is scored the same way in production, and evals you add after a production failure also generate Pressure Tests on the next run. > [accordion] Latency by pipeline stage > > Tuner's SDK integrations record end of utterance, STT, LLM, TTS, and time to first byte for each turn, so you can see which stage was slow. A platform that only hands over a finished transcript can't provide that detail, so the SDK path captures more than the webhook path. > [accordion] Evals that check facts > > An eval judge can be given the agent's system prompt, its tools, its workflow, and the tool calls and results from the call. So an eval can check whether the required tool ran, whether its arguments were right, whether the agent reported what the tool returned, and whether it followed its prompt. Evals can also score tone. > [accordion] Real voice calls in both directions > > Simulation places voice calls over SIP, inbound or outbound. Your telephony, endpointing, TTS, and latency are all part of the test, so you test what your customers hear. > [accordion] Works with any voice platform > > Managed platforms, self-hosted frameworks, and custom stacks all connect. If you move from a managed platform to your own infrastructure, your evals, history, and dashboards stay in Tuner. > [accordion] Configuration and diagnosis in natural language > > The MCP server reads and writes. You can ask what is failing across your calls, get the root cause, and have the assistant update the agent's configuration in the same conversation. > [accordion] You pay per analysis > > Credits are spent on the analyses you switch on. An agent with three evals costs less per call than one with fifteen, and alerts and red flags cost nothing at all. Plans set your monthly credit allowance and feature access. Plans and rates are on the [pricing page](https://usetuner.ai/pricing). See [Credits and usage](/docs/resources/credits) for what uses credits. *** ## Next steps > [card] [Quickstart](/docs/getting-started/quickstart) > > Connect an agent and get a scored call. > [card] [Call Simulation](/docs/simulation/overview) > > Test before launch and after every change. # Direct API Source: https://docs.usetuner.ai/docs/integrations/custom-stack/direct-api Build the call timeline yourself and send it to Tuner's Create Call API from any language. > [!NOTE] > > On a Python stack? Use the [Python SDKs](/docs/integrations/custom-stack/sdk-quickstart) instead. They capture the timeline for you and send it in one call. This guide is for every other language. The API is what the SDKs call under the hood. Going direct means you own the part the observers would have handled: assembling the structured conversation timeline, and deriving per-turn timing and interruptions from whatever your stack exposes. Concretely, you'll be building: * the turn-by-turn timeline (user speech, agent speech, tool calls, tool results), each with start and end timestamps relative to call start * per-turn latency fields, if you want them: STT time-to-transcript, LLM time-to-first-token, TTS time-to-first-byte, end-to-end * interruption detection, by comparing when a user turn starts against when the agent's turn ended For a worked example of how much that is in practice, see [Connecting to Vapi (Transient)](/docs/integrations/vapi-transient-assistants), a single-file integration that does this against Vapi's payload and call log. *** ## Prerequisites * An active Tuner account * A Tuner agent with provider **Custom API** * Your Tuner API key and workspace ID. See [API keys](/docs/getting-started/api-keys) and [the contract](/docs/integrations/custom-stack/overview#the-contract). *** ## Send your first call The video below walks through the full flow. [Custom Integration via the Tuner API](https://www.youtube.com/embed/Izr5JsWDEzM) 1. **Create a Tuner Agent** and select **Custom API** as the integration type. 2. In your voice system, after the call ends, capture: * the **full structured conversation timeline** (agent and user messages, tool calls, and any node or state transitions) * call start and end timestamps * a public `https://` recording URL. Tuner treats any other value, such as a placeholder or a `localhost` link, as no recording. * any relevant operational or enrichment data, such as cost, call outcome, dynamic variables, or provider-native analysis 3. Call the **Create Call** endpoint with all data, following the API reference. 4. Open **Call Logs** in Tuner to see the processed results. *** ## API reference The full **Create Call** request and response schema, with examples, is in the [Create Call API reference](/api-reference/calls/create-call). *** ## Enable simulation Required if you'll use [Call Simulation](/docs/simulation/overview). Skip it otherwise. Tuner links each simulated call to its run through a field you send in the Create Call request: `sip_call_id` or `sip_headers` for inbound agents and `recipient` for outbound agents ([how simulated calls are linked](/docs/simulation/run-statuses#how-simulated-calls-are-linked)). Do the steps for your agent's call direction. ### Inbound Tuner calls your agent over SIP. 1. Add your agent's SIP URI in **Agent Settings > Simulation Setup**. Get it from your [SIP provider](/docs/simulation/inbound/other-platforms), then see [Set up inbound simulation](/docs/simulation/inbound/setup). 2. Send the SIP `Call-ID` of the call Tuner placed as `sip_call_id`. Read it from the inbound call in your SIP stack; it may arrive [under a different name](/docs/simulation/run-statuses#the-call-id-may-arrive-under-a-different-name). ```json theme={null} { "call_id": "your-call-id", "sip_call_id": "the-inbound-sip-call-id", ... } ``` Tuner also adds an `X-Correlation-Id` header to the call. If a carrier or proxy between Tuner and your agent changes the Call-ID, send the header instead, as `sip_headers`. Tuner keeps only this header, and uses it only to link the call. ```json theme={null} { "call_id": "your-call-id", "sip_headers": { "X-Correlation-Id": "the-header-value-tuner-sent" }, ... } ``` `sip_call_id` doesn't replace `call_id`. Tuner stores the call under `call_id` and uses it to detect duplicates. ### Outbound Your agent calls a Simulated Caller at a SIP URI that Tuner sends to your trigger endpoint. 1. Configure the trigger endpoint in **Agent Settings > Simulation Setup**. See [Set up outbound simulation](/docs/simulation/outbound). 2. Send the SIP URI your agent dialed as `recipient`, exactly as Tuner sent it. ```json theme={null} { "call_id": "your-call-id", "recipient": "the-sip-uri-tuner-sent", ... } ``` ## Check simulation works Start a simulation run. See [Run a simulation](/docs/simulation/run-a-simulation). When the call ends, check its result in the run. If it shows **Unreported**, Tuner never received a matching call from your agent. See [Fix an Unreported run](/docs/simulation/run-statuses#fix-an-unreported-run). *** ## Optional fields The Create Call request accepts more optional fields, such as `agent_version`. The [API reference](/api-reference/calls/create-call) lists every field. The fields simulation needs are covered in [Enable simulation](#enable-simulation). \--- | --- | \| `sip_call_id` | The inbound call's SIP `Call-ID`. Required for inbound simulation; see [Enable simulation](#enable-simulation). | \| `recipient` | The phone number or SIP URI your agent dialed. Required for outbound simulation; see [Enable simulation](#enable-simulation). | \| `agent_version` | An integer (0 or greater) for the version of your agent that handled the call. | *** ## Best practices * **Make retries safe.** Treat `call_id` as immutable and retry the same request on failure. A duplicate `call_id` returns `409`, which counts as success. * **Send the final transcript.** If you only have partial transcripts, send only when final, or the analysis runs on incomplete data. * **Log request IDs and responses.** You'll want them when debugging ingestion. * **Back off on `429`.** Create Call is rate limited per workspace. A request over the limit returns `429`; retry it later. *** ## OpenTelemetry traces To show a span tree on the call, send spans to Tuner's OTLP endpoint alongside your Create Call request. Any OpenTelemetry SDK works if it exports OTLP over HTTP with protobuf encoding. The full requirements are in [Traces](/docs/observability/traces#ingest-requirements). **1. Point your exporter at Tuner** With environment variables, in any language: ```shell theme={null} export OTEL_EXPORTER_OTLP_TRACES_ENDPOINT="https://api.usetuner.ai/api/v1/traces" export OTEL_EXPORTER_OTLP_HEADERS="authorization=Bearer tr_api_..." ``` Use the signal-specific `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` with the full URL. The exporter appends `/v1/traces` to the generic `OTEL_EXPORTER_OTLP_ENDPOINT`, which does not resolve to Tuner's path, and that variable also applies to metrics and logs. Or in code, with the Python SDK: ```python theme={null} from opentelemetry import trace from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import BatchSpanProcessor from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter exporter = OTLPSpanExporter( endpoint="https://api.usetuner.ai/api/v1/traces", headers={"authorization": "Bearer tr_api_..."}, ) provider = TracerProvider() provider.add_span_processor(BatchSpanProcessor(exporter)) trace.set_tracer_provider(provider) tracer = trace.get_tracer("my-voice-agent") ``` Use the HTTP exporter (`opentelemetry.exporter.otlp.proto.http`). Tuner does not accept gRPC. **2. Tag a span with the call ID** ```python theme={null} with tracer.start_as_current_span("agent_session") as span: span.set_attribute("tuner.call_id", call_id) # your pipeline runs here ``` Use the same `call_id` you send to Create Call. One tagged span is enough: Tuner applies the ID to every span in the same trace. It links the spans to the call once both have arrived, in either order. **3. Check that it worked** A **Traces** tab appears on the call details page once spans have matched. Calls with no spans show no tab. ## Before you finish * A test call appears in [Call Logs](/docs/observability/call-logs). * Your API key, workspace ID and Agent Remote ID come from [API keys](/docs/getting-started/api-keys). * If you use Call Simulation: [Enable simulation](#enable-simulation) is done for your agent's call direction, and one simulated call shows a result other than **Unreported**. ## Common issues ### Calls don't appear in Tuner Usually one of: * wrong `workspace_id` * `agent_remote_identifier` doesn't match the agent mapping you intended * the call was sent but the transcript is empty or invalid ### Unauthorized (401) * Ensure you're sending `Authorization: Bearer `, not `X-API-Key`. * Confirm the key belongs to the workspace you're sending to. ### Validation errors (4xx) * Follow the API reference for required fields and types. * If you're unsure which field failed, start from the minimal example in the API reference and add fields incrementally. ## Next steps > [card] [Create Call API reference](/api-reference/calls/create-call) > > Required fields, types, and a minimal example. > [card] [Worked example](/docs/integrations/vapi-transient-assistants) > > A full single-file integration built on this API. > [card] [Webhooks](/docs/integrations/webhooks) > > Receive events when analysis finishes or an alert fires. > [card] [Review your first call](/docs/observability/call-logs) > > What Tuner does with the data once it lands. # LangChain / LangGraph Source: https://docs.usetuner.ai/docs/integrations/custom-stack/langchain Capture node transitions, timing, and tool calls from your LangGraph or LangChain layer on a custom stack, LiveKit, or Pipecat. ## What it does Every call has two layers: * **Voice layer:** STT hears the user and TTS speaks the reply (your transport). You already track this. * **Brain layer:** LangGraph decides which step runs next, and LangChain runs the LLM and tools inside each step. This is **invisible** unless you instrument it. `tuner-langchain` makes the brain layer visible. It records node transitions, timing, and tool calls automatically, with no hand-wrapping of individual nodes or tools. How you attach it depends on your stack. On **LiveKit** and **Pipecat**, the host SDK wraps your graph and flushes the events for you. On a **custom stack** with `tuner-core`, the `TunerSession` does the same. On a custom stack without `tuner-core`, you attach a callback handler and include the resulting segments in your own [Create Call](/api-reference/calls/create-call) payload. *** ## How it works Three pieces do the work. A simple way to picture them: ```text theme={null} Handler = ears (listens while the graph runs) Accumulator = notebook (stores what happened) Segment builder = formatter (turns the notebook into Tuner transcript rows) ``` 1. **Handler** (`TunerLangGraphHandler` or `TunerLangChainHandler`): a LangChain callback. It's passed to `invoke()`; you never call its methods yourself. 2. **Accumulator** (`TunerAccumulator`): one per call. It stores every event the brain layer produced. 3. **Segment builder** (`segments_from_invocation()`): converts one turn's events into Tuner transcript rows, with timestamps as **milliseconds since call start**. On LiveKit, Pipecat and `tuner-core`, `wrap_graph()` wires all three for you. > [!NOTE] > > **One handler sees both frameworks.** LangGraph is built on LangChain, so a single handler on `graph.invoke()` captures the graph's nodes *and* the LLM/tool calls nested inside them, with no extra wiring per LLM. | Framework | Role | You'll recognize | | - | - | - | | **LangGraph** | Orchestration (which step runs next) | `StateGraph`, conditional edges | | **LangChain** | Execution (LLM calls, tools, prompts) | `ChatOpenAI.invoke()`, `@tool` | *** ## Attach to your stack Pick your host. Each tab covers the install and the full wiring for that stack. > [tab] Custom stack > > See [Custom stack](/docs/integrations/custom-stack/overview) for the surrounding integration. How you attach depends on whether you use `tuner-core`. > > ### Install > > ```bash theme={null} > pip install tuner-langchain > ``` > > Requires Python ≥ 3.10 and `langchain-core` 1.x. Pin a version in production. See the package on [PyPI](https://pypi.org/project/tuner-langchain/). > > ### With tuner-core > > If you use a `TunerSession` from `tuner-core` (see the [SDK quickstart](/docs/integrations/custom-stack/sdk-quickstart)), wrap the graph and attach it to the session. The session adds the graph's segments to the call when you run `flush()`. > > ```python theme={null} > from tuner_langchain import wrap_graph > > graph = session.attach(wrap_graph(your_graph)) > > # then invoke as usual: > result = await graph.ainvoke({"messages": history}) > ``` > > Use `wrap_chain()` for a plain LangChain runnable. The wrapper adds its callback to `ainvoke()` and `astream()` calls only, so call the graph asynchronously. > > ### Without tuner-core > > You attach the handler yourself and include the segments in your own Create Call payload. You touch the library at three moments in a call: set up once, attach the handler on every turn, then format and send when the call ends. > > **1. Set up once per call** > > Create one accumulator (the notebook) and one handler (the ears). > > ```python theme={null} > from tuner_langchain import TunerAccumulator > from tuner_langchain.handlers import TunerLangGraphHandler > > accumulator = TunerAccumulator() # collects events for this call > handler = TunerLangGraphHandler(accumulator) # listens while the graph runs > ``` > > **2. Attach the handler on every turn** > > Pass the handler in `config` each time you run the graph or chain. This is the only wiring you add. > > ```python LangGraph theme={null} > result = graph.invoke(state, config={"callbacks": [handler]}) > response = result["response"] > ``` > > ```python LangChain theme={null} > from tuner_langchain.handlers import TunerLangChainHandler > > handler = TunerLangChainHandler(accumulator) > chain.invoke(inputs, config={"callbacks": [handler]}) > ``` > > **3. Format and send when the call ends** > > Turn the captured events into transcript rows, merge them with your own voice turns, and POST. > > ```python theme={null} > from tuner_langchain.segment_builder import segments_from_invocation > > # segments_from_invocation expects nanoseconds, so convert your call start > call_start_ns = call_start_ms * 1_000_000 > > graph_segments = [] > for invocation in accumulator.get_invocations(): # one entry per user turn > graph_segments.extend(segments_from_invocation(invocation, call_start_ns)) > > # merge with your STT/TTS turns and sort the timeline > transcript = sorted(voice_turns + graph_segments, key=lambda e: e.get("start_ms", 0)) > ``` > > Then include `transcript` in your [Create Call](/api-reference/calls/create-call) request. > [tab] LiveKit > > The [Tuner LiveKit plugin](/docs/integrations/livekit) handles the wiring and flushes the events automatically when the session ends. > > ### Install > > No extra install. `tuner-langchain` is installed as a dependency of `tuner-livekit-sdk`. > > ### Attach to a LangGraph graph > > Save the plugin reference, then call `wrap_graph()` and pass the result into `langchain.LLMAdapter`. It returns a drop-in replacement for the graph you pass in, with no callbacks to wire up. > > ```python theme={null} > from tuner import TunerPlugin > from livekit.plugins import langchain > > async def entrypoint(ctx: JobContext): > session = AgentSession(...) > plugin = TunerPlugin(session, ctx) # save the reference > > agent = Agent( > instructions="", > llm=langchain.LLMAdapter( > plugin.wrap_graph(my_graph), > stream_mode="custom", > config={"configurable": {"thread_id": thread_id}}, > ), > ) > await session.start(agent=agent) # plus your room/transport options > ``` > > ### Attach to a plain LangChain chain > > For a plain (non-graph) LangChain runnable, use `wrap_chain()` instead: > > ```python theme={null} > agent = Agent( > instructions="", > llm=langchain.LLMAdapter( > plugin.wrap_chain(my_chain), > stream_mode="messages", > config={"configurable": {"thread_id": thread_id}}, > ), > ) > ``` > [tab] Pipecat > > The [Tuner Pipecat observer](/docs/integrations/pipecat) merges brain-layer events into the same `transcript_with_tool_calls` timeline it builds for plain Pipecat pipelines, whichever frames the driving processor emits. > > ### Install > > ```shell theme={null} > pip install 'tuner-pipecat-sdk[langchain]' > ``` > > > [!NOTE] > > > > This extra is optional. If `tuner-langchain` isn't installed, calling `wrap_graph` / `wrap_chain` raises an `ImportError` with install instructions. The rest of the SDK works the same. > > ### Attach a graph or chain > > Wrap your compiled graph (or chain) with the observer, then pass the wrapped runnable into pipecat's `LangchainProcessor` in place of a native LLM service: > > ```python theme={null} > from pipecat.processors.frameworks.langchain import LangchainProcessor > from tuner_pipecat_sdk import Observer > > observer = Observer(api_key=..., workspace_id=..., agent_id=..., call_id=...) > > wrapped_graph = observer.wrap_graph(my_compiled_graph) # or observer.wrap_chain(my_chain) > lc = LangchainProcessor(chain=wrapped_graph) > > pipeline = Pipeline([ > transport.input(), > stt, > context_aggregator.user(), > lc, # in place of a native LLM service > tts, > transport.output(), > context_aggregator.assistant(), > ]) > ``` > > Runnable examples: [`examples/pizza_order_langchain/`](https://github.com/usetuner/tuner-pipecat-sdk-python/tree/main/examples/pizza_order_langchain) (`wrap_chain()`, a raw LangChain tool-calling chat model) and [`examples/nova_clinic_langgraph/`](https://github.com/usetuner/tuner-pipecat-sdk-python/tree/main/examples/nova_clinic_langgraph) (`wrap_graph()`, a LangGraph `create_react_agent` that shows node-transition tracking). *** ## Data privacy By default the library forwards node inputs, outputs, system prompts, and tool payloads. Pass a `CaptureConfig` to suppress what you don't need: ```python theme={null} from tuner_langchain import CaptureConfig capture = CaptureConfig( node_instructions=False, # system prompts node_inputs=False, # graph state in node_outputs=False, # graph state out tool_inputs=False, # tool parameters tool_outputs=False, # tool results ) ``` Where you pass it depends on your stack: | Stack | Pass it to | | - | - | | Custom stack with `tuner-core` | `wrap_graph(my_graph, capture=capture)` | | Custom stack without `tuner-core` | `TunerAccumulator(capture=capture)` | | LiveKit | `plugin.wrap_graph(my_graph, capture=capture)` | | Pipecat | `observer.wrap_graph(my_graph, capture=capture)` | > [!WARNING] > > **Tool error output is always captured**, regardless of `tool_outputs`. Errors aren't treated as sensitive and are needed for debugging. *** ## Public API The symbols below are what you use on a **custom stack without `tuner-core`**. With `tuner-core`, LiveKit or Pipecat, you only need `wrap_graph()` or `wrap_chain()` and `CaptureConfig`. ```python theme={null} from tuner_langchain import TunerAccumulator, CaptureConfig, wrap_graph, wrap_chain from tuner_langchain.handlers import TunerLangGraphHandler, TunerLangChainHandler from tuner_langchain.segment_builder import segments_from_invocation from tuner_langchain.models import GraphInvocation, NodeTransition, ToolCallEvent ``` | Symbol | Role | | - | - | | `TunerLangGraphHandler` | Callback for a LangGraph `StateGraph` | | `TunerLangChainHandler` | Callback for a plain LangChain chain | | `TunerAccumulator` | Per-call event storage; read with `get_invocations()` | | `segments_from_invocation()` | Turns raw events into Tuner transcript rows | | `CaptureConfig` | Privacy / redaction flags | | `wrap_graph()`, `wrap_chain()` | Drop-in wrappers that add the handler for you; used with `tuner-core` | | `GraphInvocation`, `NodeTransition`, `ToolCallEvent` | Data models, mostly for reading/debugging | *** ## Minimal starter (custom stack without tuner-core) ```python theme={null} import time from tuner_langchain import TunerAccumulator, CaptureConfig from tuner_langchain.handlers import TunerLangGraphHandler from tuner_langchain.segment_builder import segments_from_invocation # Per call call_start_ms = int(time.time() * 1000) accumulator = TunerAccumulator(capture=CaptureConfig(tool_inputs=False)) handler = TunerLangGraphHandler(accumulator) voice_turns = [] # your own STT/TTS turns # Per turn def handle_turn(user_text: str, state: dict) -> str: voice_turns.append({"role": "user", "text": user_text, "start_ms": ...}) result = compiled_graph.invoke(state, config={"callbacks": [handler]}) response = result["response"] voice_turns.append({"role": "agent", "text": response, "start_ms": ...}) return response # At hang-up def build_transcript() -> list[dict]: call_start_ns = call_start_ms * 1_000_000 segments = [] for inv in accumulator.get_invocations(): segments.extend(segments_from_invocation(inv, call_start_ns)) return sorted(voice_turns + segments, key=lambda e: e.get("start_ms", 0)) # POST build_transcript() inside your Tuner Create Call payload ``` *** ## Next steps > [card] [Custom stack](/docs/integrations/custom-stack/overview) > [card] [Connecting to LiveKit](/docs/integrations/livekit) > [card] [Connecting to Pipecat](/docs/integrations/pipecat) > [card] [Create Call API Reference](/api-reference/calls/create-call) # Overview Source: https://docs.usetuner.ai/docs/integrations/custom-stack/overview Send call data to Tuner from your own voice stack with the Python SDKs or the Create Call API. Use this guide if you run your own voice stack, or a platform Tuner doesn't ship a dedicated integration for. Otherwise see [Retell](/docs/integrations/retell), [Vapi](/docs/integrations/vapi), [LiveKit](/docs/integrations/livekit), [Pipecat](/docs/integrations/pipecat), or [Dograh](/docs/integrations/dograh). *** ## What this is Tuner needs one thing from your stack: the **completed call**, meaning a structured conversation timeline plus metadata, sent once after the call ends. Tuner then processes it and runs your configured analyses. ## Choose your path The two paths produce identical results in Tuner and follow the same contract. Use the SDKs on a Python stack and the API from any other language. > [card] [Python SDKs](/docs/integrations/custom-stack/sdk-quickstart) > > **On a Python stack, start here.** Attach observers to your STT, TTS, and LLM framework. They capture the transcript, per-turn timing, tool calls, usage, and cost for you, and send everything in one `flush()` at call end. > [card] [Direct API](/docs/integrations/custom-stack/direct-api) > > **Any other language.** Build the call timeline yourself and POST it to the Create Call API after the call ends. This is more work: you assemble the per-turn timing and interruption data the SDKs derive automatically. The SDKs are a client for the same API. Reach for the API directly when the SDKs don't fit your stack. *** ## The contract However you send calls, these identifiers decide which agent a call lands under: * `workspace_id`: the Tuner workspace receiving the call * `agent_remote_identifier`: your **Agent Remote ID**, from **Agent Settings > Agent Connection** * `call_id`: your unique identifier for the call. Use the same value on every retry so ingestion stays idempotent. *** ## Simulation To use [Call Simulation](/docs/simulation/overview), your calls also need the SIP data Tuner puts on the call (inbound) or `recipient` (outbound). Follow **Enable simulation** on your path's page: [Python SDKs](/docs/integrations/custom-stack/sdk-quickstart#enable-simulation) or [Direct API](/docs/integrations/custom-stack/direct-api#enable-simulation). *** ## Authentication All API requests use **Bearer authentication**. Send your Tuner API key in the `Authorization` header. Create the key on the **API Keys** page of your workspace; see [API keys](/docs/getting-started/api-keys). ``` Authorization: Bearer ``` `tuner-core` and the LiveKit SDK read the key from the `TUNER_API_KEY` environment variable and send it for you. The Pipecat `Observer` takes it as the `api_key` argument. *** ## Webhooks Tuner can send events about this agent's calls to a webhook. See [Webhooks](/docs/integrations/webhooks). *** ## Next steps > [card] [Python SDKs](/docs/integrations/custom-stack/sdk-quickstart) > > The session lifecycle, observers, and one flush at call end. > [card] [Direct API](/docs/integrations/custom-stack/direct-api) > > Build the payload yourself and POST it. > [card] [Create Call API reference](/api-reference/calls/create-call) > > The full request/response schema both paths feed into. > [card] [Review your first call](/docs/observability/call-logs) > > What Tuner does with the data once it lands. # SDK quickstart Source: https://docs.usetuner.ai/docs/integrations/custom-stack/sdk-quickstart Add Tuner to a custom Python voice stack with a session, one observer per pipeline role, and one flush at call end. > [!NOTE] > > Uses [`tuner-core`](https://pypi.org/project/tuner-core/) plus one observer per role in your pipeline. Not on Python? See [Direct API](/docs/integrations/custom-stack/direct-api). This guide shows the Tuner lines you add to a voice agent you already have. The examples assume Deepgram for STT, LangGraph for the LLM layer, and Cartesia for TTS. Swap or skip any role you don't use. Your audio loops, agent logic, and synthesis code stay as they are. With the observers attached, Tuner receives user and agent turns with timing, per-turn STT/LLM/TTS and end-to-end latency, tool calls and results in the same timeline, word-accurate interruption capture, and usage plus cost, without code of your own. ## Prerequisites * An active Tuner account * A Tuner agent with provider **Custom API** * A Tuner API key, your workspace ID and the agent's **Agent Remote ID**. See [API keys](/docs/getting-started/api-keys). * Python 3.10 to 3.13 and a custom voice stack you control ## The mental model **1. Create one TunerSession per call** `tuner-core` coordinates the call. The session holds your call's identity (`call_id`, workspace, and agent mapping) and coordinates the observers. **2. Attach one observer per role** STT, LLM, and TTS each have their own package. Attach only the roles your stack has; each is independent. **3. flush() at call end** The session assembles what the observers captured into a single timeline and sends it to Tuner via the [Create Call API](/api-reference/calls/create-call). One network call, at the end. ## Step 1: Install ```shell theme={null} theme={null} pip install tuner-core "tuner-stt-observer[deepgram]" "tuner-tts-observer[cartesia]" tuner-langchain ``` `tuner-core` provides `TunerSession` and `TunerConfig`. Provider SDKs sit behind extras so you only pull in what you use. Other combinations are in [Mix and match](#mix-and-match) below. ## Step 2: Set your credentials `TunerConfig.from_env()` reads these from the environment. Keyword arguments you pass to it take priority. ```shell theme={null} theme={null} export TUNER_API_KEY="tr_api_..." export TUNER_WORKSPACE_ID="123" export TUNER_AGENT_ID="fa4da74c-..." ``` | Variable | Required | Description | | - | - | - | | `TUNER_API_KEY` | ✅ | Bearer token (starts with `tr_api_`) | | `TUNER_WORKSPACE_ID` | ✅ | Your Tuner workspace ID | | `TUNER_AGENT_ID` | ✅ | **Agent Remote ID** from **Agent Settings > Agent Connection** | | `TUNER_BASE_URL` | No | API base URL (default: `https://api.usetuner.ai`) | | `TUNER_DEBUG` | No | Set to `true` to log the full payload on flush | | `AGENT_VERSION` | No | Integer agent version attached to every call. No `TUNER_` prefix. The `agent_version` argument overrides it. | ## Step 3: Create a session per call Create one `TunerSession` at the start of each call. The model names are recorded as call metadata. Keep `call_id` stable across retries so ingestion stays idempotent. ```python theme={null} theme={null} from tuner_core import TunerConfig, TunerSession session = TunerSession( config=TunerConfig.from_env( asr_model="nova-2", llm_model="gpt-4o-mini", tts_model="sonic-2", ), call_id=call_id, # your unique, retry-stable identifier for this call ) ``` ### Extra metadata Attach arbitrary key-value data to every call, such as environment, region, deployment version, or tenant: ```python theme={null} theme={null} config = TunerConfig.from_env( asr_model="nova-2", llm_model="gpt-4o-mini", tts_model="sonic-2", extra_metadata={"env": "production", "region": "us-east-1"}, ) ``` Metadata can also be used as an eval input, which is how you evaluate agents whose instructions change per call. See [Evaluate agents with per-call instructions](/docs/evaluation/dynamic-agents). The keys `ai_models` and `usage_token` are reserved and ignored in `extra_metadata`. ### Cost calculation Pass a `cost_calculator` callable. At flush, it receives a `CallUsage` and returns the call cost in USD cents. The rates below are illustrative. ```python theme={null} theme={null} from tuner_core import CallUsage, TunerConfig def calculate_cost(usage: CallUsage) -> float: usd = ( usage.llm_prompt_tokens * 0.000_003 + usage.llm_completion_tokens * 0.000_015 + usage.tts_characters * 0.000_030 + usage.stt_audio_seconds * 0.000_006 ) return usd * 100 # USD -> cents config = TunerConfig.from_env(cost_calculator=calculate_cost) ``` `CallUsage` fields: `llm_prompt_tokens`, `llm_completion_tokens`, `llm_total_tokens`, `tts_characters`, `stt_audio_seconds`. If the callable raises, the call is sent without a cost. ### Disconnection reason Set `session.disconnection_reason` before `flush()` to record why the call ended. Use a `DisconnectReason` value or your own string: ```python theme={null} theme={null} from tuner_core import DisconnectReason session.disconnection_reason = DisconnectReason.AGENT_HANGUP ``` | Constant | Value | | - | - | | `DisconnectReason.USER_HANGUP` | `"user_hangup"` | | `DisconnectReason.AGENT_HANGUP` | `"agent_hangup"` | | `DisconnectReason.ERROR` | `"error"` | | `DisconnectReason.TIMEOUT` | `"timeout"` | | `DisconnectReason.UNKNOWN` | `"unknown"` | ## Step 4: Attach observers ### STT: Deepgram ```python theme={null} theme={null} from tuner_stt_observer import DeepgramAdapter stt = DeepgramAdapter(connection=dg_connection) # your existing Deepgram connection stt.on_utterance = handle_user_utterance # your callback: complete user turn text session.attach(stt) ``` Send audio to Deepgram as you normally would. The adapter only listens on the connection's events. Your `LiveOptions` must set `utterance_end_ms` and `vad_events=True`, or you'll see calls with no user turns. Speechmatics, custom providers, and what each adapter captures: [Speech-to-Text](/docs/integrations/custom-stack/speech-to-text). ### LLM: LangGraph ```python theme={null} theme={null} from tuner_langchain import wrap_graph graph = session.attach(wrap_graph(your_graph)) # then invoke as usual: result = await graph.ainvoke({"messages": history}) ``` Node transitions, per-node LLM latency, and tool calls land in the timeline. Plain chains and privacy controls: [LangChain / LangGraph](/docs/integrations/custom-stack/langchain). ### TTS: Cartesia ```python theme={null} theme={null} from tuner_tts_observer import CartesiaAdapter tts = session.attach(CartesiaAdapter()) # around your existing Cartesia WebSocket receive loop: async with tts.track_ws(agent_text) as tracked: async for chunk in tracked(ctx.receive()): # ctx: your Cartesia context ... # your playback / send code ``` Word-accurate interruption capture, the SSE pattern for HTTP-only stacks, and what your app owns for barge-in: [Text-to-Speech](/docs/integrations/custom-stack/text-to-speech). ## Step 5: Flush at call end `flush()` is the only network call the libraries make. Put it in a `finally` block so the call reaches Tuner even when the connection drops or your loop raises: ```python theme={null} theme={null} try: ... # your call loop finally: await session.flush() ``` Open **Call Logs** in Tuner to see the processed result. ## Enable simulation Required for [Call Simulation](/docs/simulation/overview). Skip it otherwise. ### Inbound Tuner calls your agent over SIP. | SDK | Version | | - | - | | Python, `tuner-core` | 0.1.3 or later | If your calls come through a carrier, the carrier sends each call to a webhook, then opens a WebSocket for the audio. Tuner's SIP data reaches the webhook but not the WebSocket. Forward it from the webhook, then attach it to the session. **1. Add your SIP URI in Tuner** Add your agent's SIP URI in **Agent Settings > Simulation Setup**. Get it from your [SIP provider](/docs/simulation/inbound/other-platforms), then see [Set up inbound simulation](/docs/simulation/inbound/setup). **2. Forward the SIP data from your webhook** Read the SIP data from the carrier's request and put it on the WebSocket. > [tab] Twilio > > ```python theme={null} > from tuner_core.telephony import extract_sip, forward_to_websocket > > # Twilio voice webhook: the Voice URL of the SIP Domain that Tuner dials > info = extract_sip(await request.form(), provider="twilio") > fwd = forward_to_websocket(info, ws_url=WS_URL) > return Response(fwd.twiml, media_type="application/xml") > ``` > [tab] Telnyx > > ```python theme={null} > from tuner_core.telephony import extract_sip, forward_to_websocket > > # Telnyx call.initiated webhook > fwd = forward_to_websocket(extract_sip(webhook_json, provider="telnyx"), ws_url=WS_URL) > > # answer rejects custom_parameters, so answer first, then start the stream > await telnyx(f"calls/{call_control_id}/actions/answer", {}) > await telnyx(f"calls/{call_control_id}/actions/streaming_start", fwd.stream) > ``` > > Tuner dials the SIP subdomain of a Call Control application. Set the application's webhook to this handler. **3. Attach the SIP data to the session** In your WebSocket handler, read the SIP data from the first message and attach it to the session. Do this before you call `flush()`. ```python theme={null} session.attach_sip(extract_sip(start_message, provider="twilio")) # or "telnyx" ``` Twilio forwards `SipCallId` and `X-Correlation-Id`. Telnyx's `call.initiated` event has no SIP Call-ID, so `X-Correlation-Id` links a Telnyx call. Tuner links the call on either one. You can call `attach_sip` more than once. Headers merge, and the first non-empty value wins. It never changes the shared config. > [accordion] Your own SIP trunk or another carrier > > If you already have the values, pass them directly: > > ```python theme={null} > session.attach_sip( > sip_call_id=sip_call_id, # SIP Call-ID of the inbound call > sip_headers={"X-Correlation-Id": correlation_id}, # the header Tuner put on the call > ) > ``` > > To read a carrier's payload with `extract_sip`, register a class with a `name` and `extract(payload) -> SipInfo`. Add `forward_to_websocket(info, ws_url) -> Forward` to support forwarding. > > ```python theme={null} > from tuner_core.telephony import SipInfo, register_provider > > class AcmeProvider: > name = "acme" > > def extract(self, payload) -> SipInfo: > return SipInfo(sip_call_id=payload["sip_call_id"], sip_headers=payload["headers"]) > > register_provider(AcmeProvider()) > ``` > [accordion] Set the values in the config instead > > `TunerConfig` also takes `sip_call_id`, `sip_headers` and `recipient`. They are per call, so use a separate config for each call. They have no environment variables. > > ```python theme={null} > session = TunerSession( > config=TunerConfig.from_env( > sip_call_id=sip_call_id, > sip_headers={"X-Correlation-Id": correlation_id}, > ), > call_id=call_id, > ) > ``` > [accordion] Older SDK versions > > `tuner-core` 0.1.1 to 0.1.2 accepts `sip_call_id` on `TunerConfig`, which links calls on the SIP Call-ID. `sip_headers`, `recipient`, `attach_sip` and `tuner_core.telephony` need 0.1.3 or later. `sip_call_id` doesn't replace `call_id`. Tuner uses `call_id` to detect duplicates. ### Outbound Your agent calls a Simulated Caller at a SIP URI that Tuner sends to your trigger endpoint. 1. Configure the trigger endpoint in **Agent Settings > Simulation Setup**. See [Set up outbound simulation](/docs/simulation/outbound). 2. Report the SIP URI your agent dialed as `recipient`, exactly as Tuner sent it. It needs `tuner-core` 0.1.3 or later. If your bot gets audio from a Twilio or Telnyx media stream, put the SIP URI on the stream when you place the call. Then the bot reads it from the `start` message. > [tab] Twilio > > ```python theme={null} > from tuner_core.telephony import SipInfo, extract_sip, forward_to_websocket > > fwd = forward_to_websocket(SipInfo(recipient=dialed_sip_uri), ws_url=WS_URL, provider="twilio") > twilio_client.calls.create(to=dialed_sip_uri, from_=..., twiml=fwd.twiml) > > # in the bot, on the WebSocket "start" message > session.attach_sip(extract_sip(start, provider="twilio")) > ``` > [tab] Telnyx > > ```python theme={null} > from tuner_core.telephony import SipInfo, extract_sip, forward_to_websocket > > fwd = forward_to_websocket(SipInfo(recipient=dialed_sip_uri), ws_url=WS_URL, provider="telnyx") > # on call.answered for the call you placed > await telnyx_post(f"/v2/calls/{call_control_id}/actions/streaming_start", fwd.stream) > > # in the bot, on the WebSocket "start" message > session.attach_sip(extract_sip(start, provider="telnyx")) > ``` If your bot already has the SIP URI, pass it directly: ```python theme={null} session.attach_sip(recipient=dialed_sip_uri) # the SIP URI Tuner sent, unchanged ``` ## Check simulation works Start a simulation run. See [Run a simulation](/docs/simulation/run-a-simulation). When the call ends, check its result in the run. If it shows **Unreported**, Tuner never received a matching call from your agent. See [Fix an Unreported run](/docs/simulation/run-statuses#fix-an-unreported-run). ## Mix and match | Your stack | Install | | - | - | | Deepgram + LangGraph + Cartesia | `tuner-core "tuner-stt-observer[deepgram]" "tuner-tts-observer[cartesia]" tuner-langchain` | | Speechmatics + Cartesia | `tuner-core "tuner-stt-observer[speechmatics]" "tuner-tts-observer[cartesia]"` | | STT observability only | `tuner-core "tuner-stt-observer[deepgram]"` | | LLM tracing only | `tuner-core tuner-langchain` | | LiveKit or Pipecat | Use the [LiveKit](/docs/integrations/livekit) / [Pipecat](/docs/integrations/pipecat) SDKs instead | Missing an adapter for one of your providers? Extend the base adapter for that role. See *Custom providers* on the [Speech-to-Text](/docs/integrations/custom-stack/speech-to-text) and [Text-to-Speech](/docs/integrations/custom-stack/text-to-speech) pages. ## Before you finish * A test call appears in [Call Logs](/docs/observability/call-logs). * Your API key, workspace ID and Agent Remote ID come from [API keys](/docs/getting-started/api-keys). * If you use Call Simulation: [Enable simulation](#enable-simulation) is done for your agent's call direction, and one simulated call shows a result other than **Unreported**. ## Troubleshooting > [accordion] Calls don't appear in Tuner > > * Verify `TUNER_AGENT_ID` is the **Agent Remote ID** from **Agent Settings > Agent Connection**. > * Set `TUNER_DEBUG=true` to log the full payload on flush. > * Confirm `TUNER_WORKSPACE_ID` is correct. > * Confirm `session.flush()` ran. Put it in a `finally` block so exceptions don't skip it. > [accordion] Unauthorized (401) > > * Ensure `TUNER_API_KEY` starts with `tr_api_` and is valid. > * Confirm the API key belongs to the correct workspace. Role-specific problems (missing user turns, interrupted turns recording in full, latency fields absent) are on the [Speech-to-Text](/docs/integrations/custom-stack/speech-to-text) and [Text-to-Speech](/docs/integrations/custom-stack/text-to-speech) pages. ## Next steps > [card] [Speech-to-Text](/docs/integrations/custom-stack/speech-to-text) > > Deepgram and Speechmatics adapters, options, custom providers. > [card] [Text-to-Speech](/docs/integrations/custom-stack/text-to-speech) > > Cartesia over WebSocket or SSE, word-level interruption capture. > [card] [LangChain / LangGraph](/docs/integrations/custom-stack/langchain) > > Node transitions, tool calls, and LLM latency in your timeline. > [card] [Review your first call](/docs/observability/call-logs) > > What Tuner does with the data once it lands. # Speech-to-text Source: https://docs.usetuner.ai/docs/integrations/custom-stack/speech-to-text Capture user transcript, turn timing, and STT latency by attaching a Tuner adapter to your existing STT provider. > [!NOTE] > > This guide uses [`tuner-stt-observer`](https://pypi.org/project/tuner-stt-observer/). It assumes you have a `TunerSession` set up. See the [Quickstart](/docs/integrations/custom-stack/sdk-quickstart) for the session lifecycle and credentials. `tuner-stt-observer` hooks into your STT provider's **native event system** to capture the user side of the conversation. It never proxies or modifies your audio stream. It listens to the same events your application already receives. ## Supported adapters | Provider | Adapter | Status | | - | - | - | | Deepgram | `DeepgramAdapter` | ✅ Supported | | Speechmatics | `SpeechmaticsAdapter` | ✅ Supported | | AssemblyAI | — | SOON | Need a provider that isn't listed? Extend `BaseSTTAdapter`. See [Custom providers](#custom-providers) below. ## Install ```shell theme={null} theme={null} pip install tuner-core tuner-stt-observer ``` Each provider adapter lives behind an optional extra so you only pull in the SDKs you actually use: ```shell theme={null} theme={null} pip install "tuner-stt-observer[deepgram]" # DeepgramAdapter pip install "tuner-stt-observer[speechmatics]" # SpeechmaticsAdapter ``` ## Deepgram `DeepgramAdapter` registers on Deepgram's `Open`, `Transcript`, and `UtteranceEnd` events. `speech_final` transcript fragments are buffered internally and flushed as a single joined utterance when `UtteranceEnd` fires. You get **one complete user turn per utterance**. Attach it to the Deepgram connection you already have: ```python theme={null} theme={null} from tuner_stt_observer import DeepgramAdapter stt = DeepgramAdapter(connection=dg_connection) # your existing Deepgram connection stt.on_utterance = handle_user_utterance # your callback: complete user turn text session.attach(stt) ``` Send audio to Deepgram as you normally would. The adapter only listens on the connection's events and never touches audio: ```python theme={null} theme={null} await dg_connection.send(chunk) ``` > [!WARNING] > > Your `LiveOptions` **must** set `utterance_end_ms` (e.g. `"1000"`) and `vad_events=True`. Without them, `UtteranceEnd` never fires and the fragment buffer never flushes, so calls have no user turns. > [!TIP] > > Barge-in isn't handled by this adapter. Build it yourself with a local VAD or a provider event like Deepgram's `SpeechStarted`. ## Speechmatics `SpeechmaticsAdapter` registers on `ADD_TRANSCRIPT` and `END_OF_UTTERANCE`. Speechmatics-rt **stacks** event handlers rather than replacing them, so the adapter coexists safely with any handlers you register yourself. ```python theme={null} theme={null} import time from tuner_stt_observer import SpeechmaticsAdapter session_start_ns = time.time_ns() # capture right before you start the Speechmatics session stt = SpeechmaticsAdapter( client=stt_client, # your existing Speechmatics client session_start_ns=session_start_ns, # needed for STT latency ) session.attach(stt) # Your own handlers still work alongside the adapter's. # For barge-in, register your own partial-transcript handler: stt_client.on(SMEvent.ADD_PARTIAL_TRANSCRIPT)(handle_barge_in) ``` Speechmatics reports word times relative to the start of its session. `session_start_ns` anchors them to wall-clock time so the adapter can measure STT latency. Without it, the latency field is omitted. If the value is captured slightly too early, the adapter corrects it automatically. ## Custom providers For providers other than Deepgram and Speechmatics, extend `BaseSTTAdapter` from `tuner_stt_observer`. Its docstring documents the full contract (`_record_user_turn()`, `_record_stt_usage()`, timestamp conversion) with a worked example. ## What gets captured | Signal | Deepgram | Speechmatics | | - | - | - | | Complete user utterance text | ✓ (fragments joined on `UtteranceEnd`) | ✓ (fragments joined on `END_OF_UTTERANCE`) | | Turn start timestamp | ✓ | ✓ | | Turn duration | ✓ | ✓ | | STT latency | ✓ (last fragment's audio end to `Transcript` arrival) | ✓ (last fragment's audio end to `ADD_TRANSCRIPT` arrival; requires `session_start_ns`) | | STT audio usage | ✓ | ✓ | ## Troubleshooting > [accordion] Calls have no user turns (Deepgram) > > * Your `LiveOptions` must set `utterance_end_ms` (e.g. `"1000"`) and `vad_events=True`. Without them, Deepgram never emits `UtteranceEnd` and the utterance buffer never flushes. > [accordion] User turns arrive as fragments > > * Fragments are joined per utterance. If you're seeing one turn per fragment, the utterance-end event is never firing. On Deepgram, check `utterance_end_ms`; on Speechmatics, confirm your session emits `END_OF_UTTERANCE`. ## Next steps > [card] [Quickstart](/docs/integrations/custom-stack/sdk-quickstart) > > The session lifecycle, credentials, and every observer wired together. > [card] [Text-to-Speech](/docs/integrations/custom-stack/text-to-speech) > > Capture the agent side: synthesis latency and word-accurate interruption. > [card] [LangChain / LangGraph](/docs/integrations/custom-stack/langchain) > > Node transitions, tool calls, and LLM latency in your call timeline. > [card] [Create Call API](/api-reference/calls/create-call) > > The underlying API every observer feeds into at flush time. # Text-to-speech Source: https://docs.usetuner.ai/docs/integrations/custom-stack/text-to-speech Capture agent transcript, synthesis latency, and word-accurate interruptions by wrapping your TTS stream with a Tuner adapter. > [!NOTE] > > This guide uses [`tuner-tts-observer`](https://pypi.org/project/tuner-tts-observer/). It assumes you have a `TunerSession` set up. See the [Quickstart](/docs/integrations/custom-stack/sdk-quickstart) for the session lifecycle and credentials. `tuner-tts-observer` wraps your TTS provider's synthesis stream to capture the agent side of the conversation: transcript, TTS time-to-first-byte, and end-to-end latency. The adapter only observes synthesis. Removing the context managers leaves your synthesis code unaffected. ## Supported adapters | Provider | Adapter | Status | | - | - | - | | Cartesia | `CartesiaAdapter` | ✅ Supported | | ElevenLabs | — | SOON | | OpenAI TTS | — | SOON | Need a provider that isn't listed? Extend `BaseTTSAdapter`. See [Custom providers](#custom-providers) below. ## Install ```shell theme={null} theme={null} pip install tuner-core tuner-tts-observer ``` WebSocket support (recommended) requires the `cartesia` extra: ```shell theme={null} theme={null} pip install "tuner-tts-observer[cartesia]" ``` ## WebSocket (recommended) WebSocket is the pattern for real-time voice agents. It supports **word-level interruption detection**: when the user interrupts the agent, Tuner records only the words actually spoken. Attach the adapter once per call, then wrap each turn's receive loop with `track_ws()`: ```python theme={null} theme={null} from tuner_tts_observer import CartesiaAdapter tts = session.attach(CartesiaAdapter()) # around your existing Cartesia WebSocket receive loop, per turn: async with tts.track_ws(agent_text) as tracked: async for chunk in tracked(ctx.receive()): # ctx: your Cartesia context if barge_in_event.is_set(): # your barge-in signal tts.mark_interrupted() break ... # your playback / send code else: await tts.wait_for_interruption(barge_in_event) ``` Word-accurate interruption capture requires `add_timestamps=True` on your Cartesia context: ```python theme={null} theme={null} ctx = await tts_ws.context( ..., # your model, voice, and output format add_timestamps=True, # required for word-accurate interruption capture ) ``` Without it, interruptions are still recorded, but the spoken text cannot be cut at the word the user interrupted. TTS providers stream faster than real-time, so your loop can finish seconds before the audio finishes playing out loud. `mark_interrupted()` on the `break` path handles a mid-stream interruption; `wait_for_interruption()` on the `else` path keeps watching during that remaining gap and calls `mark_interrupted()` for you if one happens there. Skip the `else` branch and any interruption after the loop ends naturally is silently lost. ### What your app owns This package only records interruptions. It never detects or acts on them. You need: (1) a detection signal (VAD, provider event, client-side signal), (2) a shared flag or event, (3) the actual stop: breaking your loop, *and* telling the client to stop already-buffered audio if detection was server-side: ```python theme={null} # server, on server-side detection barge_in_event.set() await websocket.send_text(json.dumps({"type": "stop_playback"})) ``` ```js theme={null} // client if (msg.type === 'stop_playback') stopPlaybackImmediately() ``` Both `mark_interrupted()` and `wait_for_interruption()` are optional. Without them, turns record in full. ## SSE (legacy) SSE is the simpler pattern, available for HTTP-only stacks or existing integrations. Interruption detection is supported, but spoken text **cannot** be cut accurately. The full intended response is recorded. Wrap your synthesis stream with `track()`: ```python theme={null} theme={null} from tuner_tts_observer import CartesiaAdapter tts = session.attach(CartesiaAdapter()) # around your existing SSE synthesis loop, per turn: with tts.track(agent_text) as tracked: for chunk in tracked(your_sse_stream): # e.g. cartesia_client.tts.sse(...) ... # your playback / send code ``` ## Custom providers For providers other than Cartesia, extend `BaseTTSAdapter` from `tuner_tts_observer`. Its docstring documents the full contract (timestamping, `_record_agent_turn()` / `_record_tts_usage()`, `mark_interrupted()`) with a worked example. ## What gets captured | Signal | SSE | WebSocket | | - | - | - | | Agent transcript text | ✓ full text | ✓ spoken words only on interruption | | Turn start timestamp | ✓ | ✓ | | Turn duration | ✓ | ✓ | | TTS TTFB | ✓ | ✓ | | E2e latency | ✓ | ✓ | | LLM latency | ✓\* | ✓\* | | `interrupted: true` on barge-in | ✓ | ✓ | | Word-accurate spoken text cut | ✗ | ✓ | \* Populated from the session. Requires a LangChain/LangGraph handler (`tuner-langchain`) attached to the same session. With no LLM handler attached, this field is absent. ## Troubleshooting > [accordion] Interrupted turns record the full intended response > > * On WebSocket, confirm `add_timestamps=True` is set on your Cartesia context. Without word timestamps, the spoken text cannot be cut. > * Confirm your loop has the `else: await tts.wait_for_interruption(barge_in_event)` branch. Without it, interruptions that happen after the loop ends naturally are never recorded. > * On SSE this is expected behavior. Word-accurate cutting requires the WebSocket pattern. > [accordion] Agent turns are missing from the call > > * Every synthesis turn must go through `track_ws()` / `track()`. Turns synthesized outside the wrapper are invisible to Tuner. > * Confirm the adapter was attached to the session before the first turn: `tts = session.attach(CartesiaAdapter())`. > [accordion] Latency numbers look wrong or missing > > * E2e latency and LLM latency are assembled from other observers on the same session. If either is missing, confirm the relevant observer (`tuner-stt-observer` for e2e, `tuner-langchain` for LLM latency) is attached to the same session. ## Next steps > [card] [Quickstart](/docs/integrations/custom-stack/sdk-quickstart) > > The session lifecycle, credentials, and every observer wired together. > [card] [Speech-to-Text](/docs/integrations/custom-stack/speech-to-text) > > Capture the user side: transcript and turn timing. > [card] [LangChain / LangGraph](/docs/integrations/custom-stack/langchain) > > Node transitions, tool calls, and LLM latency in your call timeline. > [card] [Create Call API](/api-reference/calls/create-call) > > The underlying API every observer feeds into at flush time. # Connecting to Dograh Source: https://docs.usetuner.ai/docs/integrations/dograh Connect a Dograh voice workflow to Tuner with the Tuner node, so completed calls are sent to Tuner for analysis, and set it up for simulation. [YouTube video player](https://www.youtube.com/embed/mFfMIsK-qPM) ## Overview You connect Dograh in two halves: create a Dograh agent in Tuner, then add the Tuner node to your Dograh workflow with three values from Tuner. There's no code to write. **1. Create the agent in Tuner** Add a **Dograh** agent with the agent setup wizard. **2. Add the Tuner node in Dograh** Add the **Tuner** node to your workflow and paste your Agent Remote ID, Workspace ID and API key. **3. Publish and check** Publish the workflow, place a test call and find it in **Call Logs**. > [!NOTE] > > **You need:** a Dograh workflow and a [Tuner](https://app.usetuner.ai) account. *** ## Step 1: Create your agent in Tuner 1. In Tuner, click **Create New Agent** in the sidebar (**Set up your first agent** if you don't have one yet). 2. Under **Where does your agent run?**, choose **Dograh**. 3. Enter an **Agent name** and set **Call direction** to match production, then click **Add agent**. 4. Choose how to configure the agent, as described in the [Quickstart](/docs/getting-started/quickstart). The wizard then shows **Connect Tuner to Dograh** with **Your Tuner credentials**: the **Agent Remote ID**, **Workspace ID** and **API Key**, each with a copy button. Keep this page open for Step 2. The wizard fills in the API key only if your workspace has no key yet. Otherwise, create one on the **API Keys** page; see [API keys and IDs](/docs/getting-started/api-keys). A key is shown only once, so store it somewhere safe. *** ## Step 2: Add the Tuner node in Dograh 1. Open the voice workflow you want to observe. 2. Use **Add node** at the top of the canvas and open the node panel on the right. ![Dograh voice workflow builder, with Add node at the top of the canvas](https://mintcdn.com/tuner/E_tPYJjPApvwp6ol/images/dograh-workflow-builder.png?fit=max\&auto=format\&n=E_tPYJjPApvwp6ol\&q=85\&s=2261c681297553bcc60dc2412a151139) 3) Scroll to **Integrations** and select **Tuner**. A node appears marked **Not configured**. ![Dograh Integrations panel with QA Analysis, Tuner and Webhook](https://mintcdn.com/tuner/E_tPYJjPApvwp6ol/images/dograh-integrations-panel.png?fit=max\&auto=format\&n=E_tPYJjPApvwp6ol\&q=85\&s=b308456db6f06ab8e0b5167cf5fe5513) ![The Tuner node on the canvas, marked Not configured](https://mintcdn.com/tuner/E_tPYJjPApvwp6ol/images/dograh-tuner-node-not-configured.png?fit=max\&auto=format\&n=E_tPYJjPApvwp6ol\&q=85\&s=0853310409d7b135b69c1bae8e04ce64) 4. Select the **Tuner** node to open **Edit Tuner**, and check that **Enabled** is on. When it's off, Dograh doesn't send calls to Tuner. 5. Paste the three values from Step 1: * **Tuner Agent ID**: the **Agent Remote ID**. * **Tuner Workspace ID**: the **Workspace ID**. * **Tuner API Key**: the **API Key**. 6. Click **Save**. ![Dograh Edit Tuner panel with the credentials and the Enabled toggle](https://mintcdn.com/tuner/E_tPYJjPApvwp6ol/images/dograh-edit-tuner-modal.png?fit=max\&auto=format\&n=E_tPYJjPApvwp6ol\&q=85\&s=3c9fbd2e35fad7d421cd198018a62115) 7. To have Tuner calculate call cost, turn on **Calculate Cost**, enter your providers' rates and save. ![Dograh Tuner node cost settings with provider rates](https://mintcdn.com/tuner/EBEvVmAd9oCdmoka/images/Screenshot-2026-07-02-at-10.45.57.png?fit=max\&auto=format\&n=EBEvVmAd9oCdmoka\&q=85\&s=8bb2d8eb612544c19b9cb42051cf20e3) *** ## Step 3: Publish and check 1. In Dograh, **Save** the workflow. 2. **Publish** it. Dograh only sends calls from published workflows, so a Tuner node that exists only in a draft sends nothing. 3. Place a short test call. 4. In Tuner, open **Call Logs**. The call appears there with its transcript once it ends. *** ## Enable simulation Required if you'll use [Call Simulation](/docs/simulation/overview). Skip it otherwise. * **Inbound:** build a SIP URI from your Dograh settings and paste it into **Agent Settings > Simulation Setup**. You need Dograh **v1.48.0** or later and a published workflow with the Tuner node. There's no code to add. Follow the steps in [Set up inbound simulation: Dograh](/docs/simulation/inbound/setup#dograh). * **Outbound:** outbound simulation isn't available for Dograh agents. ## Check simulation works Run one simulated call; see [Run your first simulation](/docs/simulation/overview#run-your-first-simulation). If it shows **Unreported**, Tuner didn't receive the matching call from Dograh. Check the Dograh version and that the workflow is published, then see [Fix an Unreported run](/docs/simulation/run-statuses#fix-an-unreported-run). *** ## Webhooks Tuner can send events about your calls to your own endpoint. See [Webhooks](/docs/integrations/webhooks). ## Troubleshooting > [accordion] Calls don't appear in Call Logs > > * The Tuner node's **Enabled** toggle is on. > * The Agent Remote ID, Workspace ID and API key have no leading or trailing spaces. > * The workflow is published, not only saved as a draft. > * The agent in Tuner was created with the **Dograh** provider. ## Next steps > [card] [Set up inbound simulation](/docs/simulation/inbound/setup#dograh) > > Build the Dograh SIP URI and run your first simulation. > [card] [Call logs](/docs/observability/call-logs) > > Review your calls, transcripts and eval results. # Connecting to ElevenLabs Source: https://docs.usetuner.ai/docs/integrations/elevenlabs Connect an ElevenLabs agent to Tuner with your ElevenLabs API key, import its recent calls, and set up simulation. > [!NOTE] > > **Prerequisites:** > > * An ElevenLabs account with at least one agent > * An ElevenLabs API key > * A Tuner account > > No code is needed. Tuner works with ElevenLabs' default API host only. Accounts on the EU, India or Singapore data residency hosts can't connect yet. ## Overview You connect an ElevenLabs agent from the agent setup wizard. Tuner registers a webhook in ElevenLabs that sends each finished conversation to Tuner. 1. [Get your ElevenLabs API key](#step-1-get-your-elevenlabs-api-key) 2. [Create your agent in Tuner](#step-2-create-your-agent-in-tuner) 3. [Import recent calls](#import-recent-elevenlabs-calls) ## Step 1: Get your ElevenLabs API key Create an API key in ElevenLabs. Tuner uses it to list your agents, read their conversations and recordings, and add its webhook to the agent you connect. If you restrict the key's permissions, enable the following: | Permission | Used for | | - | - | | `convai_read` | Listing agents, reading conversations and recordings, and checking phone numbers | | `convai_write` | Optional, for [outbound simulation](/docs/simulation/outbound#elevenlabs). Lets **Create phone number** create the `Tuner Outbound` SIP trunk phone number that points at Tuner's SIP host and save it to your outbound config. Without it, create the number in ElevenLabs yourself and enter its ID | | `webhooks_write` | Creating the `Tuner` webhook | | `user_read` | Optional. Checking your ElevenLabs credits before each outbound simulated call. Without it, Tuner skips the check and places the call | If ElevenLabs reports a missing permission, Tuner shows its name. When you connect the key, Tuner checks it by listing your agents. If ElevenLabs rejects the key, Tuner shows ElevenLabs' reason. > [!NOTE] > > Treat your API key like a password. Never paste it into frontend code, public repos or source control. ## Step 2: Create your agent in Tuner **1. Open the wizard** In the sidebar, click **Create New Agent**. Before your workspace has its first agent, the button reads **Set up your first agent**. **2. Choose ElevenLabs** Under **Where does your agent run?**, select **ElevenLabs**. **3. Connect your ElevenLabs API key** Under **Connection**, paste your ElevenLabs API key and click **Connect**. Tuner validates the key and stores it in your workspace settings. **4. Pick your agent** In **Which agent?**, choose the ElevenLabs agent to connect. Tuner fills in **Agent name** and the system prompt from ElevenLabs. You can edit both. For a workflow agent, Tuner imports the agent's main prompt only. Prompts set on individual workflow nodes aren't imported. **5. Add the agent** Click **Add agent**. Tuner creates the agent and sets its post-call webhook in ElevenLabs. This replaces any post-call webhook the agent already had. See [Webhooks](#webhooks). **6. Get your first evaluated call** The last wizard step checks your ElevenLabs account for recent calls. See [Import recent ElevenLabs calls](#import-recent-elevenlabs-calls). > [accordion] Save the key in Workspace Settings instead > > You can save or replace your ElevenLabs key outside the wizard: > > 1. Open **Workspace Settings > General Settings**. > 2. Under **Third-party Integrations**, paste your key into **ElevenLabs API Key**. > 3. Click **Save Changes**. > > A saved key shows as **Saved, ending in** followed by its last characters. The wizard then uses it automatically. ## Webhooks > [!WARNING] > > **Connecting to Tuner replaces the post-call webhook on your ElevenLabs agent.** Tuner points it at itself, so any URL you had set there (n8n, Zapier, your own backend) stops receiving ElevenLabs events. Add that URL in Tuner under **Agent Settings > Webhooks** instead. It then receives: * **Tuner events:** `call.analyzed` and `alert.fired`. * **ElevenLabs' `post_call_transcription` event:** forwarded as a `call.received` event, with ElevenLabs' original body in `payload`. Tuner forwards only `post_call_transcription`. Other ElevenLabs webhook events are not forwarded, so an automation that depends on them stops receiving them. Tuner creates one webhook named `Tuner` in your ElevenLabs workspace and sets it as the post-call webhook of the agent you connected. Later ElevenLabs agents in your Tuner workspace reuse that webhook. Tuner keeps the webhook events the agent already subscribes to and adds the transcript event. It doesn't change your ElevenLabs workspace-wide webhook settings. See [Webhooks](/docs/integrations/webhooks) for the event format, headers and URL requirements. ## Import recent ElevenLabs calls On the last wizard step, **Get your first evaluated call**, Tuner checks your ElevenLabs account for finished conversations of the connected agent. Click **Import & evaluate all N** to import them and run your evals. Importing needs available credits in your workspace. Tuner imports only conversations that have ended, including ones ElevenLabs marks as failed. Conversations that are still in progress or processing are skipped. A conversation Tuner already has isn't imported again. ## Verify the first call **1. Make a test call** Call your ElevenLabs agent, or open **Call Logs** and confirm the imported calls appear. **2. Open the call** Open the call in **Call Logs**. The transcript, recording and metrics from the table below appear once ElevenLabs finishes processing the conversation. ### What Tuner reads from each call | Data | Source in ElevenLabs | | - | - | | Transcript | The conversation transcript, including tool calls, tool results and workflow node transitions | | Latency | ElevenLabs' per-turn metrics: end-to-end latency, speech-to-text, LLM and text-to-speech time to first byte | | Cost | The conversation cost in USD, with credits and speech usage in the breakdown | | Recording | The conversation audio, copied into Tuner | | Analysis | Ended reason, sentiment, ElevenLabs' own evaluation criteria results and data collection | ## Enable simulation Required if you use [Call Simulation](/docs/simulation/overview). Neither direction needs code. ### Inbound Give Tuner the SIP URI of an ElevenLabs SIP trunk phone number that's assigned to your agent. See [Simulate an ElevenLabs agent](/docs/simulation/inbound/setup#elevenlabs). ### Outbound Give Tuner an ElevenLabs SIP trunk phone number whose outbound address is Tuner's SIP host. Tuner places each simulated call through ElevenLabs from that number. Tuner can create the number for you with **Create phone number** in **Agent Settings > Simulation Setup**. See [Set up outbound simulation](/docs/simulation/outbound#elevenlabs). ## Check simulation works Start a simulation run. See [Run a simulation](/docs/simulation/run-a-simulation). When the call ends, check its result in the run. If it shows **Unreported**, Tuner never received a matching call from ElevenLabs. See [Fix an Unreported run](/docs/simulation/run-statuses#fix-an-unreported-run). ## Before you finish * [ ] The ElevenLabs API key connects and the agent appears in **Which agent?** * [ ] The agent's post-call webhook in ElevenLabs is the `Tuner` webhook * [ ] **Agent Remote ID** in **Agent Settings > Agent Setup** matches the ElevenLabs agent ID * [ ] A call appears in **Call Logs** with its transcript * [ ] For simulation: a run ends with a status other than **Unreported** ## Troubleshooting > [accordion] The key won't connect > > Tuner shows ElevenLabs' reason when it rejects the key. If the key is missing a permission, enable it in ElevenLabs or create a new key, and try again. See [Step 1](#step-1-get-your-elevenlabs-api-key). > [accordion] Adding the agent fails with a webhook error > > ElevenLabs refused to create or attach Tuner's webhook. Check that your key has the `webhooks_write` permission. > [accordion] Calls stopped arriving after I changed the API key > > Open each agent in Tuner and save it again. Tuner then creates a webhook in the new workspace and attaches it. This happens when the new key belongs to a different ElevenLabs workspace: agents connected with the old key still point at the old webhook, and Tuner rejects their deliveries. > [accordion] Calls don't appear in Tuner > > Check that the agent's **Agent Remote ID** in **Agent Settings > Agent Setup** matches the ElevenLabs agent ID, and that the agent's post-call webhook in ElevenLabs is still the `Tuner` webhook. ## Next steps > [card] [Run a simulation](/docs/simulation/run-a-simulation) > > Run Scenarios against your ElevenLabs agent once simulation is set up. > [card] [Webhooks](/docs/integrations/webhooks) > > See the events Tuner sends to your own URL. # Connecting to LiveKit Source: https://docs.usetuner.ai/docs/integrations/livekit Send LiveKit Agents sessions to Tuner with the Tuner LiveKit SDK for Python or Node.js. > [!NOTE] > > This guide covers both the **Python SDK** ([`tuner-livekit-sdk`](https://pypi.org/project/tuner-livekit-sdk/)) and the **Node.js SDK** ([`@usetuner.ai/livekit-sdk`](https://www.npmjs.com/package/@usetuner.ai/livekit-sdk)). Use the language switcher below to view the guide for your stack. ## Video tutorial [Connecting to LiveKit - Tuner Integration Tutorial](https://www.youtube.com/embed/OtnCEM_IlEY) ## Prerequisites * An active Tuner account * A Tuner agent with provider **LiveKit** * A Tuner API key, your workspace ID and the agent's **Agent Remote ID**. See [API keys](/docs/getting-started/api-keys). * A LiveKit Agents project, either: * **Python** running [LiveKit Agents](https://docs.livekit.io/agents/) v1.4 or later, or * **Node.js 18+** running [`@livekit/agents`](https://github.com/livekit/agents-js) v1.4 or later with `@livekit/rtc-node` v0.13 or later. ## Overview The Tuner LiveKit SDK captures session data from your LiveKit agent and sends it to Tuner when the call ends. You don't make any API calls yourself. It ships as a Python package and a Node.js package that share the same wire format. **1. Install the SDK** Add the package to your project. **2. Set your credentials** Configure your Tuner API key, workspace ID, and Agent Remote ID. **3. Add the plugin** Add two lines to your entrypoint. **4. Enable simulation** Required only if you use Call Simulation. See [Enable simulation](#enable-simulation). > [tab] Python > > ## Step 1: Install the SDK > > ```shell theme={null} > pip install tuner-livekit-sdk > ``` > > **Requirements:** Python ≥ 3.10, `livekit-agents >= 1.4`, `aiohttp >= 3.9`. The package also installs `tuner-langchain >= 0.1.1` as a dependency. > > To forward OpenTelemetry traces as well, install the `traces` extra instead. See [OpenTelemetry traces](#opentelemetry-traces). > > ```shell theme={null} > pip install 'tuner-livekit-sdk[traces]' > ``` > > ## Step 2: Set your credentials > > You can configure credentials via environment variables or pass them directly in code. > > > [tab] Environment variables > > > > ```shell theme={null} > > export TUNER_API_KEY="tr_api_..." > > export TUNER_WORKSPACE_ID="123" > > export TUNER_AGENT_ID="fa4da74c-..." > > ``` > > > > | Variable | Required | Description | > > | - | - | - | > > | `TUNER_API_KEY` | ✅ | Bearer token (starts with `tr_api_`) | > > | `TUNER_WORKSPACE_ID` | ✅ | Your Tuner workspace ID | > > | `TUNER_AGENT_ID` | ✅ | **Agent Remote ID** from **Agent Settings > Agent Connection**. This is a UUID, not your agent's display name. | > > | `TUNER_BASE_URL` | No | API base URL (default: `https://api.usetuner.ai`) | > > > [tab] Inline in code > > > > ```python theme={null} > > TunerPlugin( > > session, ctx, > > api_key="tr_api_...", > > workspace_id=123, > > agent_id="fa4da74c-...", > > ) > > ``` > > > [!TIP] > > > > Use the **Agent Remote ID** from **Agent Settings > Agent Connection**, not your agent's display name. It is a UUID (for example `fa4da74c-...`). Copy **your** value from the Tuner dashboard. > > ## Step 3: Add the plugin > > Import `TunerPlugin` and add it right after creating your `AgentSession`, before calling `session.start()`: > > ```python theme={null} > from tuner import TunerPlugin > > async def entrypoint(ctx: JobContext): > session = AgentSession(...) > TunerPlugin(session, ctx) # wires itself automatically > await session.start(...) > ``` > > The plugin listens to session events and submits call data to Tuner when the session ends. > [tab] Node.js > > ## Step 1: Install the SDK > > ```shell theme={null} > npm install @usetuner.ai/livekit-sdk > ``` > > **Requirements:** Node 18+, `@livekit/agents >= 1.4.0`, `@livekit/rtc-node >= 0.13.0` > > ## Step 2: Set your credentials > > You can configure credentials via environment variables or pass them directly in code. > > > [tab] Environment variables > > > > ```shell theme={null} > > export TUNER_API_KEY="tr_api_..." > > export TUNER_WORKSPACE_ID="123" > > export TUNER_AGENT_ID="fa4da74c-..." > > ``` > > > > | Variable | Required | Description | > > | - | - | - | > > | `TUNER_API_KEY` | ✅ | Bearer token (starts with `tr_api_`) | > > | `TUNER_WORKSPACE_ID` | ✅ | Your Tuner workspace ID | > > | `TUNER_AGENT_ID` | ✅ | **Agent Remote ID** from **Agent Settings > Agent Connection**. This is a UUID, not your agent's display name. | > > | `TUNER_BASE_URL` | No | API base URL (default: `https://api.usetuner.ai`) | > > > [tab] Inline in code > > > > ```ts theme={null} > > new TunerPlugin(session, ctx, { > > apiKey: 'tr_api_...', > > workspaceId: 123, > > agentId: 'fa4da74c-...', > > }); > > ``` > > > [!TIP] > > > > Use the **Agent Remote ID** from **Agent Settings > Agent Connection**, not your agent's display name. It is a UUID (for example `fa4da74c-...`). Copy **your** value from the Tuner dashboard. > > ## Step 3: Add the plugin > > Import `TunerPlugin` and add it right after creating your `AgentSession`, before calling `session.start()`: > > ```ts theme={null} > import { TunerPlugin } from '@usetuner.ai/livekit-sdk'; > import { voice, type JobContext } from '@livekit/agents'; > > export default async function entry(ctx: JobContext) { > const session = new voice.AgentSession({ /* ... */ }); > new TunerPlugin(session, ctx); // wires itself automatically > await session.start({ agent, room: ctx.room }); > } > ``` > > The plugin listens to session events and submits call data to Tuner when the session ends. ## Enable simulation Required for [Call Simulation](/docs/simulation/overview). Skip it otherwise. ### Inbound Tuner calls your agent over SIP. | SDK | Version | | - | - | | Python, `tuner-livekit-sdk` | 0.1.11 or later | | Node.js, `@usetuner.ai/livekit-sdk` | 0.5.6 or later | 1. Add your agent's SIP URI in **Agent Settings > Simulation Setup**. Get it from your [SIP provider](/docs/simulation/inbound/other-platforms), then see [Set up inbound simulation](/docs/simulation/inbound/setup). 2. Run your agent. There is nothing to add in code. If a carrier such as Twilio or Telnyx sits between Tuner and LiveKit, also follow [Carrier in front of LiveKit](#carrier-in-front-of-livekit). > [accordion] How Tuner links the call > > Tuner puts two IDs on each simulated call: the SIP Call-ID and an `X-Correlation-Id` header. The plugin reads both from the SIP participant and sends them with the call report. Tuner links the call on either one. When Tuner calls LiveKit directly, the Call-ID links it. Behind a carrier, the Call-ID changes and the header links it. > > See [How simulated calls are linked](/docs/simulation/run-statuses#how-simulated-calls-are-linked). > [accordion] Older Python SDK versions > > | `tuner-livekit-sdk` | Sends | Direct to LiveKit | Behind a carrier | > | - | - | - | - | > | 0.1.11 or later | Call-ID and header | Links | Links | > | 0.1.5 to 0.1.10 | Call-ID | Links | Doesn't link | > | Before 0.1.5 | Nothing for simulation | Doesn't link | Doesn't link | > > To upgrade, install 0.1.11 or later. No code changes are needed. ### Outbound Your agent calls a Simulated Caller at a SIP URI that Tuner sends to your trigger endpoint. 1. Configure the trigger endpoint in **Agent Settings > Simulation Setup**. See [Set up outbound simulation](/docs/simulation/outbound). 2. Pass the SIP URI your agent dialed as `recipient`, exactly as Tuner sent it. > [tab] Python > > Requires `tuner-livekit-sdk` 0.1.7 or later. > > ```python theme={null} > TunerPlugin( > session, ctx, > recipient=dialed_sip_uri, # the SIP URI Tuner sent, unchanged > ) > ``` > [tab] Node.js > > ```ts theme={null} > new TunerPlugin(session, ctx, { > recipient: dialedSipUri, // the SIP URI Tuner sent, unchanged > }); > ``` If the plugin starts before your agent knows the SIP URI, report it later with `attach_sip`. This needs `tuner-livekit-sdk` 0.1.12 or `@usetuner.ai/livekit-sdk` 0.5.6. > [tab] Python > > ```python theme={null} > plugin.attach_sip(recipient=dialed_sip_uri) > ``` > [tab] Node.js > > ```ts theme={null} > plugin.attachSip(null, { recipient: dialedSipUri }); > ``` ### Carrier in front of LiveKit Use this if a carrier such as Twilio or Telnyx sits between Tuner and LiveKit. Skip it if Tuner calls LiveKit directly. > [!NOTE] > > **Prerequisite:** your LiveKit inbound trunk must pass SIP headers to the agent. Set the trunk's `include_headers` option to `SIP_X_HEADERS` or `SIP_ALL_HEADERS`. The default, `SIP_NO_HEADERS`, drops them. As an alternative, map the header explicitly with `headers_to_attributes`, using `{"X-Correlation-Id": "sip.h.x-correlation-id"}`. > > To check, run `lk sip inbound list --json`. The setting appears only in the JSON output. Requires `tuner-livekit-sdk` 0.1.12 or later (Python) or `@usetuner.ai/livekit-sdk` 0.5.6 or later (Node.js). Set up the carrier so Tuner's call reaches your webhook: * **Twilio**: Tuner dials a Twilio **SIP Domain** with a Credential List. Set the domain's Voice URL to your webhook. Use the domain for inbound only, because a domain has one Voice URL. Twilio passes Tuner's header to the webhook as `SipHeader_X-Correlation-Id`. * **Telnyx**: Tuner dials the SIP subdomain of a Call Control application, `sip:@.sip.telnyx.com`. Set the subdomain to receive calls from anyone, and set the application's webhook to your server. Transfer the call on the incoming `call.initiated` event. Telnyx puts Tuner's header in the event's `custom_headers`. See [SIP providers](/docs/simulation/inbound/other-platforms) for the SIP URI and credentials. Add two calls where your webhook already sends the call to LiveKit: `extract_sip` reads Tuner's data from the carrier's webhook, and `forward_to_sip` builds the leg into LiveKit with Tuner's header on it. Your server keeps its routing, signature checks and call control. > [tab] Twilio > > > [tab] Python > > > > ```python theme={null} > > from tuner.telephony import extract_sip, forward_to_sip > > > > # in your existing Twilio voice webhook > > params = dict(await request.form()) > > info = extract_sip(params, provider="twilio") > > > > # sip_uri: the LiveKit SIP address you already dial > > fwd = forward_to_sip(info, sip_uri="sip:agent@xxxx.sip.livekit.cloud") > > > > # fwd.sip_uri: that address with Tuner's header attached, unchanged when there is none > > response = VoiceResponse() > > response.dial(answer_on_bridge=True).sip(fwd.sip_uri, username=..., password=...) > > ``` > > > [tab] Node.js > > > > ```ts theme={null} > > import { extractSip, forwardToSip } from '@usetuner.ai/livekit-sdk/telephony'; > > > > // in your existing Twilio voice webhook > > const info = extractSip(params, { provider: 'twilio' }); > > > > // sipUri: the LiveKit SIP address you already dial > > const fwd = forwardToSip(info, { sipUri: 'sip:agent@xxxx.sip.livekit.cloud' }); > > > > // fwd.sipUri: that address with Tuner's header attached, unchanged when there is none > > response.dial({ answerOnBridge: true }).sip({ username, password }, fwd.sipUri); > > ``` > [tab] Telnyx > > > [tab] Python > > > > ```python theme={null} > > from tuner.telephony import extract_sip, forward_to_sip > > > > # event: the webhook JSON. sip_uri: the LiveKit SIP address you already dial > > fwd = forward_to_sip( > > extract_sip(event, provider="telnyx"), > > sip_uri="sip:agent@xxxx.sip.livekit.cloud", > > ) > > > > # fwd.transfer: {"to": ..., "custom_headers": [...]}, without headers when there is none > > await telnyx_post(f"/calls/{call_control_id}/actions/transfer", { > > **fwd.transfer, > > "sip_auth_username": ..., "sip_auth_password": ..., > > }) > > ``` > > > [tab] Node.js > > > > ```ts theme={null} > > import { extractSip, forwardToSip } from '@usetuner.ai/livekit-sdk/telephony'; > > > > // event: the webhook JSON. sipUri: the LiveKit SIP address you already dial > > const fwd = forwardToSip(extractSip(event, { provider: 'telnyx' }), { > > sipUri: 'sip:agent@xxxx.sip.livekit.cloud', > > }); > > > > // fwd.transfer: { to, custom_headers }, without headers when there is none > > await telnyxPost(`/calls/${encodeURIComponent(callControlId)}/actions/transfer`, { > > ...fwd.transfer, > > sip_auth_username: '...', > > sip_auth_password: '...', > > }); > > ``` You can call `forward_to_sip` on every call. Without Tuner's header, it returns your address unchanged. A malformed header is dropped with a warning on the `tuner.telephony` logger, and the call still connects. The SDK doesn't check the carrier's webhook signature, so keep your own check. > [accordion] Why a carrier needs this > > The carrier opens a new SIP leg into LiveKit with its own Call-ID, and doesn't copy Tuner's `X-Correlation-Id` header onto that leg. `forward_to_sip` forwards the header, and the trunk setting lets it reach your agent. The plugin then sends it to Tuner, which links the call. For the general rule, see [How simulated calls are linked](/docs/simulation/run-statuses#how-simulated-calls-are-linked). > > The SDK knows where each carrier puts Tuner's data (Twilio's `SipHeader_` fields, Telnyx's `custom_headers`), so the code is the same for every carrier. Only the `provider` name changes. > [accordion] How the header travels > > ```mermaid theme={null} > sequenceDiagram > participant T as Tuner > participant C as Carrier > participant W as Your webhook > participant L as LiveKit > participant A as Your agent > T->>C: Call with Call-ID A and X-Correlation-Id > C->>W: Webhook with the call details > W->>C: forward_to_sip: dial LiveKit with the header > C->>L: New call with Call-ID B > L->>A: Participant attribute sip.h.x-correlation-id > A->>T: Call report with sip_headers > ``` > [accordion] If the call doesn't link > > The call still connects and your agent still talks. In the run it shows **Unreported**. The header can be lost in two places: > > | Your webhook | LiveKit trunk | Result | > | - | - | - | > | Uses `forward_to_sip` | `SIP_X_HEADERS` or `SIP_ALL_HEADERS` | Links | > | Uses `forward_to_sip` | `SIP_NO_HEADERS` (the default) | Doesn't link. The trunk drops the header. | > | Dials a plain SIP address | `SIP_X_HEADERS` or `SIP_ALL_HEADERS` | Doesn't link. The carrier drops the header. | > | Dials a plain SIP address | `SIP_NO_HEADERS` (the default) | Doesn't link. The carrier drops the header. | > > The header also can't link the call if another worker with the same agent name takes the job and reports to a different Tuner agent. Give each agent's worker its own name. > [accordion] Support another carrier > > Write a provider with a `name`, an `extract` method that reads the webhook payload into a `SipInfo`, and a `forward_to_sip` method that returns a `Forward`. Register it once. Then pass its name as `provider`. > > > [tab] Python > > > > ```python theme={null} > > from tuner.telephony import Forward, SipInfo, register_provider > > > > > > class AcmeProvider: > > name = "acme" > > > > def extract(self, payload) -> SipInfo: > > return SipInfo(sip_headers={"X-Correlation-Id": payload.get("x_correlation_id", "")}) > > > > def forward_to_sip(self, info: SipInfo, sip_uri: str) -> Forward: > > return Forward(sip_uri=sip_uri, correlation_id=info.correlation_id or None) > > > > > > register_provider(AcmeProvider()) > > ``` > > > [tab] Node.js > > > > ```ts theme={null} > > import { Forward, SipInfo, registerProvider } from '@usetuner.ai/livekit-sdk/telephony'; > > > > registerProvider({ > > name: 'acme', > > extract: (payload: any) => > > new SipInfo({ sipHeaders: { 'X-Correlation-Id': payload?.x_correlation_id ?? '' } }), > > forwardToSip: (info, sipUri) => new Forward(sipUri, info.correlationId || null), > > }); > > ``` ## Check simulation works Start a simulation run. See [Run a simulation](/docs/simulation/run-a-simulation). When the call ends, check its result in the run. If it shows **Unreported**, Tuner never received a matching call from your agent. 1. Open **Call Logs** and look for the call. If it's missing, check that the plugin is sending calls (see [Troubleshooting](#troubleshooting)). 2. If it's there, check your `tuner-livekit-sdk` version against the [Inbound](#inbound) table. Behind a carrier, also check the carrier webhook and the trunk's `include_headers` setting. See [Fix an Unreported run](/docs/simulation/run-statuses#fix-an-unreported-run). > [tab] Python > > ## Per-turn timing > > Each user and agent turn in the transcript carries these metadata fields. The values come from LiveKit's own per-turn metrics; the SDK converts them to milliseconds and does not recompute them. > > | Field | Description | > | - | - | > | `stt_node_ttfb` | Time to obtain the transcript after the user stopped speaking | > | `eou_delay` | Time between the end of user speech and the decision to end their turn. Requires `tuner-livekit-sdk >= 0.1.9`. | > | `llm_node_ttft` | Time for the LLM node to return its first token | > | `tts_node_ttfb` | Time for the TTS node to return its first audio chunk | > | `e2e_latency` | Time from the end of user speech to the agent beginning its response | > | `interrupted` | Whether the turn was interrupted before it completed | > | `transcript_confidence` | STT confidence score for user turns | > > ## Disconnection reasons > > Tuner captures why each call ended. User disconnects and errors are tracked automatically. To record agent-initiated hangups, pass `reason="agent_hangup"` when ending the call programmatically: > > ```python theme={null} > get_job_context().shutdown(reason="agent_hangup") > ``` > > Without this, agent hangups are indistinguishable from dropped calls in your analytics. > > > [accordion] Full tool call example > > > > ```python theme={null} > > @function_tool > > async def end_call(self, context: RunContext): > > """End the call once the user has been helped.""" > > await context.session.shutdown(drain=True) > > get_job_context().shutdown(reason="agent_hangup") > > ``` > > > > `drain=True` lets any in-flight audio finish before the session closes. Omit it for an immediate cutoff. > > ## LangChain and LangGraph observability > > If you use LangGraph or LangChain for your logic layer, the plugin can capture node transitions, tool calls, and timing alongside session data. See [LangChain / LangGraph](/docs/integrations/custom-stack/langchain#attach-to-your-stack). > > ## Configuration options > > > [accordion] Call type > > > > The plugin auto-detects the call type (`phone_call` for SIP participants, `web_call` otherwise). Override it explicitly when needed: > > > > ```python theme={null} > > TunerPlugin(session, ctx, call_type="phone_call") > > TunerPlugin(session, ctx, call_type="web_call") > > ``` > > > [accordion] Recording URL > > > > Tuner requires a `recording_url` for every call. Provide a resolver function that returns the URL. If you don't provide one, the plugin submits `"pending"` as a placeholder. > > > > The URL must be a public `https://` link. Tuner stores a placeholder or any other value as sent, but treats the call as having no recording: it has no playback in call details and can't be added to a [Dataset](/docs/datasets/add-calls). > > > > ```python theme={null} > > # Static / pre-known URL > > async def my_resolver(room_name: str, job_id: str) -> str: > > return f"https://cdn.example.com/recordings/{job_id}.ogg" > > > > TunerPlugin(session, ctx, recording_url_resolver=my_resolver) > > ``` > > > > ```python theme={null} > > # LiveKit Egress to S3 > > async def egress_resolver(room_name: str, job_id: str) -> str: > > url = await my_egress_db.get_recording_url(room_name) > > return url or "pending" > > > > TunerPlugin(session, ctx, recording_url_resolver=egress_resolver) > > ``` > > > [accordion] Cost calculation > > > > Provide a callable that receives a `UsageSummary` and returns the call cost in USD cents. Implement the method that matches your pricing plan; the snippet below is illustrative. > > > > ```python theme={null} > > def calculate_cost(usage) -> float: > > # rates below are USD per unit; convert to cents before returning > > llm_cost = usage.llm_prompt_tokens * 0.000_003 > > llm_cost += usage.llm_completion_tokens * 0.000_015 > > tts_cost = usage.tts_characters_count * 0.000_030 > > stt_cost = usage.stt_audio_duration * 0.000_006 > > return (llm_cost + tts_cost + stt_cost) * 100 # USD -> cents > > > > TunerPlugin(session, ctx, cost_calculator=calculate_cost) > > ``` > > > [accordion] Extra metadata > > > > Attach arbitrary key-value data to every call record: > > > > ```python theme={null} > > TunerPlugin( > > session, ctx, > > extra_metadata={ > > "env": "production", > > "region": "us-east-1", > > "deployment": "v2.3.1", > > }, > > ) > > ``` > > > [accordion] Retry and timeout > > > > ```python theme={null} > > TunerPlugin( > > session, ctx, > > timeout_seconds=15.0, # per-request timeout (default: 30.0) > > max_retries=5, # retries on 5xx / 429 / network errors (default: 3) > > ) > > ``` > > > [accordion] Agent version tracking > > > > Track which version of your agent handled each call, for example after you update a prompt, swap a model, or change your pipeline: > > > > ```shell theme={null} > > AGENT_VERSION=42 python agent.py start > > ``` > > > > The plugin reads `AGENT_VERSION` automatically. Bump the number on every deployment. > > > > Override in code (takes priority over the env var): > > > > ```python theme={null} > > TunerPlugin(session, ctx, agent_version=42) > > ``` > > > [accordion] Trace forwarding > > > > With the `traces` extra installed, the plugin forwards LiveKit's OpenTelemetry spans to Tuner. `forward_traces` defaults to `True`. To turn it off: > > > > ```python theme={null} > > TunerPlugin(session, ctx, forward_traces=False) > > ``` > > > > See [OpenTelemetry traces](#opentelemetry-traces). > > > [accordion] Disable the plugin > > > > Useful for local development or test environments: > > > > ```python theme={null} > > import os > > > > TunerPlugin( > > session, ctx, > > enabled=os.getenv("ENV") == "production", > > ) > > ``` > > ## Full example > > ```python theme={null} > import os > from livekit.agents import JobContext, AgentSession > from tuner import TunerPlugin > > def calculate_cost(usage) -> float: > usd = ( > usage.llm_prompt_tokens * 0.000_003 > + usage.llm_completion_tokens * 0.000_015 > + usage.tts_characters_count * 0.000_030 > ) > return usd * 100 # Tuner expects USD cents > > async def get_recording_url(room_name: str, job_id: str) -> str: > return await my_storage.get_url(job_id) or "pending" > > async def entrypoint(ctx: JobContext): > session = AgentSession(...) > > TunerPlugin( > session, > ctx, > api_key=os.environ["TUNER_API_KEY"], > workspace_id=int(os.environ["TUNER_WORKSPACE_ID"]), > agent_id=os.environ["TUNER_AGENT_ID"], > call_type="phone_call", > recording_url_resolver=get_recording_url, > cost_calculator=calculate_cost, > extra_metadata={"env": "prod", "region": "us-east-1"}, > timeout_seconds=20.0, > max_retries=3, > enabled=True, > ) > > await session.start(...) > ``` > > The SIP Call-ID is captured automatically, so the example doesn't pass `sip_call_id`. > [tab] Node.js > > ## Disconnection reasons > > Tuner captures why each call ended. User disconnects and errors are tracked automatically. > > > [!NOTE] > > > > `@livekit/agents` (Node) currently invokes shutdown callbacks with no arguments, so the JS SDK submits a hardcoded `'shutdown'` reason instead of the actual disconnect reason. Once LiveKit's Node SDK forwards the reason, the JS plugin will pass it through automatically. > > ## Configuration options > > > [accordion] Call type > > > > The plugin auto-detects the call type (`phone_call` for SIP participants, `web_call` otherwise). Override it explicitly when needed: > > > > ```ts theme={null} > > new TunerPlugin(session, ctx, { callType: 'phone_call' }); > > new TunerPlugin(session, ctx, { callType: 'web_call' }); > > ``` > > > [accordion] Recording URL > > > > Tuner requires a recording URL for every call. Provide a resolver function that returns the URL. If you don't provide one, the plugin submits `"pending"` as a placeholder. > > > > The URL must be a public `https://` link. Tuner stores a placeholder or any other value as sent, but treats the call as having no recording: it has no playback in call details and can't be added to a [Dataset](/docs/datasets/add-calls). > > > > ```ts theme={null} > > async function getRecordingUrl(roomName: string, jobId: string): Promise { > > return (await myStorage.getUrl(jobId)) ?? 'pending'; > > } > > > > new TunerPlugin(session, ctx, { recordingUrlResolver: getRecordingUrl }); > > ``` > > > [accordion] Cost calculation > > > > Provide a callable that receives a `UsageSummary` and returns the call cost in USD cents. Implement the method that matches your pricing plan; the snippet below is illustrative. > > > > ```ts theme={null} > > import type { metrics } from '@livekit/agents'; > > > > function calculateCost(usage: metrics.UsageSummary): number { > > const usd = > > usage.llmPromptTokens * 0.000_003 + > > usage.llmCompletionTokens * 0.000_015 + > > usage.ttsCharactersCount * 0.000_030; > > return usd * 100; // Tuner expects USD cents > > } > > > > new TunerPlugin(session, ctx, { costCalculator: calculateCost }); > > ``` > > > [accordion] Extra metadata > > > > Attach arbitrary key-value data to every call record: > > > > ```ts theme={null} > > new TunerPlugin(session, ctx, { > > extraMetadata: { > > env: 'production', > > region: 'us-east-1', > > deployment: 'v2.3.1', > > }, > > }); > > ``` > > > [accordion] Retry and timeout > > > > ```ts theme={null} > > new TunerPlugin(session, ctx, { > > timeoutSeconds: 15, // per-request timeout (default: 30) > > maxRetries: 5, // retries on 5xx / 429 / network errors (default: 3) > > }); > > ``` > > > [accordion] Agent version tracking > > > > Track which version of your agent handled each call, for example after you update a prompt, swap a model, or change your pipeline: > > > > ```shell theme={null} > > AGENT_VERSION=42 node agent.js start > > ``` > > > > The plugin reads `AGENT_VERSION` automatically. Bump the number on every deployment. > > > > Override in code (takes priority over the env var): > > > > ```ts theme={null} > > new TunerPlugin(session, ctx, { agentVersion: 42 }); > > ``` > > > [accordion] Disable the plugin > > > > Useful for local development or test environments: > > > > ```ts theme={null} > > new TunerPlugin(session, ctx, { > > enabled: process.env.NODE_ENV === 'production', > > }); > > ``` > > ## Full example > > ```ts theme={null} > import { TunerPlugin } from '@usetuner.ai/livekit-sdk'; > import { voice, type JobContext, type metrics } from '@livekit/agents'; > > function calculateCost(usage: metrics.UsageSummary): number { > const usd = > usage.llmPromptTokens * 0.000_003 + > usage.llmCompletionTokens * 0.000_015 + > usage.ttsCharactersCount * 0.000_030; > return usd * 100; // Tuner expects USD cents > } > > async function getRecordingUrl(roomName: string, jobId: string): Promise { > return (await myStorage.getUrl(jobId)) ?? 'pending'; > } > > export default async function entry(ctx: JobContext) { > const session = new voice.AgentSession({ /* ... */ }); > > new TunerPlugin(session, ctx, { > apiKey: process.env.TUNER_API_KEY, > workspaceId: Number.parseInt(process.env.TUNER_WORKSPACE_ID!, 10), > agentId: process.env.TUNER_AGENT_ID, > callType: 'phone_call', > recordingUrlResolver: getRecordingUrl, > costCalculator: calculateCost, > extraMetadata: { env: 'prod', region: 'us-east-1' }, > agentVersion: 42, > timeoutSeconds: 20, > maxRetries: 3, > enabled: process.env.NODE_ENV === 'production', > }); > > await session.start({ agent, room: ctx.room }); > } > ``` ## OpenTelemetry traces LiveKit Agents emits OpenTelemetry spans for every session. The Python SDK forwards them to Tuner, and they appear as a span tree on the call's **Traces** tab. See [Traces](/docs/observability/traces) for how to read one. The Node.js SDK does not forward traces. > [!NOTE] > > Requires `tuner-livekit-sdk` 0.1.10 or later. **1. Install the traces extra** ```shell theme={null} pip install 'tuner-livekit-sdk[traces]' ``` The extra adds the OpenTelemetry SDK and the OTLP HTTP exporter. Without it, trace forwarding is skipped with a debug log, and the rest of the plugin works as usual. **2. Keep forward_traces on** `forward_traces` defaults to `True`, so `TunerPlugin(session, ctx)` is enough. The plugin sends spans to Tuner with the API key and base URL you already configured, and tags every span with the call's ID. You don't need to create a `TracerProvider`, choose an exporter, or set any `OTEL_*` environment variable. If you already configured a `TracerProvider` to export traces elsewhere, the plugin adds Tuner as an extra destination on it. Your existing backend keeps receiving the same spans. To stop forwarding traces, pass `forward_traces=False`. **3. Check that it worked** Open the call in Tuner. A **Traces** tab appears on the call details page once spans have been received and matched. Matching completes when the call itself is ingested, so the tab can take a moment to appear after a session ends. ### Span reference The span names come from LiveKit Agents, so they are the same ones you would see in any other OpenTelemetry backend. | Span | What it covers | | - | - | | `agent_session` | The whole session. This is the root span. | | `start_agent_activity`, `on_enter` | Session startup and the agent's entry hook. | | `agent_turn` | One agent response. | | `llm_node` | The model stage of that turn. | | `llm_request`, `llm_request_run` | The model request itself, nested inside the node span. | | `tts_node` | The synthesis stage of that turn. | | `tts_stream_adapter`, `tts_request_run` | The streaming adapter and the synthesis request underneath it. | | `user_turn` | One customer turn. | | `user_speaking` | The window where the customer was actually speaking. | See [LiveKit's telemetry documentation](https://docs.livekit.io/agents/build/events/) for the full set, and [Traces](/docs/observability/traces) for how to read the tree in Tuner. ### Traces troubleshooting > [accordion] The Traces tab never appears > > 1. **The `traces` extra isn't installed.** The plugin skips forwarding and logs a debug message. Install `tuner-livekit-sdk[traces]`. > 2. **The SDK is older than 0.1.10.** Upgrade `tuner-livekit-sdk`. > 3. **`forward_traces=False` is set.** Remove it or set it to `True`. > 4. **The API key is wrong or revoked.** Tuner rejects the spans with `401` or `403`. ## Webhooks Tuner can notify your systems when it has something to report on a call. See [Webhooks](/docs/integrations/webhooks). ## Before you finish * A test call appears in [Call Logs](/docs/observability/call-logs). * Your API key, workspace ID and Agent Remote ID come from [API keys](/docs/getting-started/api-keys). * If you use Call Simulation: [Enable simulation](#enable-simulation) is done for your agent's call direction, and one simulated call shows a result other than **Unreported**. ## Troubleshooting > [accordion] Calls don't appear in Tuner > > * Verify that `TUNER_AGENT_ID` is the **Agent Remote ID** from **Agent Settings > Agent Connection** (not your agent's display name). > * Confirm `TUNER_WORKSPACE_ID` is correct. > * Check your application logs for any error messages from the plugin. > [accordion] Unauthorized (401) > > * Ensure `TUNER_API_KEY` starts with `tr_api_` and is valid. > * Confirm the API key belongs to the correct workspace. > [accordion] Simulated calls show as Unreported > > * Inbound: check that the caller joins the room as a SIP participant with a `sip.callIDFull` attribute, and check your `tuner-livekit-sdk` version against the [Inbound](#inbound) table. > * Inbound, with a carrier in front of LiveKit: check that your webhook calls `forward_to_sip` (see [Carrier in front of LiveKit](#carrier-in-front-of-livekit)) and that the inbound trunk's `include_headers` is `SIP_X_HEADERS` or `SIP_ALL_HEADERS`. > * Outbound: confirm you pass `recipient` with the SIP URI exactly as Tuner sent it. > * See [Fix an Unreported run](/docs/simulation/run-statuses#fix-an-unreported-run). > [accordion] A call has no recording > > * You haven't provided a recording URL resolver (`recording_url_resolver` in Python, `recordingUrlResolver` in Node.js), so the plugin sent `"pending"`. Add one that returns the actual recording URL for each call. > * The resolver returned a link that isn't a public `https://` URL, such as `http://` or `localhost`. Tuner treats those as no recording. > * If using LiveKit Egress, ensure the recording has finished processing before the resolver is called. ## Next steps > [card] [Configure your agent](/docs/getting-started/quickstart) > > Set up call outcomes, user intents, and evals. > [card] [Custom integration](/docs/integrations/custom-stack/overview) > > Learn about the underlying API if you need more control. > [card] [Classify calls](/docs/evaluation/call-classification) > > Define how Tuner categorizes your calls. > [card] [Alerts](/docs/observability/alerts) > > Get notified when issues are detected. # Connecting to Pipecat Source: https://docs.usetuner.ai/docs/integrations/pipecat Send Pipecat calls to Tuner with the tuner-pipecat-sdk Observer. > [!NOTE] > > This guide covers the **Python SDK** for [pipecat-ai](https://github.com/pipecat-ai/pipecat). The package is available on PyPI. A **Node.js SDK** is coming soon. ## Video tutorial [Connecting to Pipecat - Tuner Integration Tutorial](https://www.youtube.com/embed/kOA4iZYCd7I) ## Prerequisites * An active Tuner account * A Tuner agent with provider **Pipecat** * A Tuner API key, your workspace ID and the agent's **Agent Remote ID**. See [API keys](/docs/getting-started/api-keys). * Python 3.11 to 3.13 (3.14 is not yet supported due to Pipecat dependencies) * A Python project running [pipecat-ai](https://github.com/pipecat-ai/pipecat) v1.0.0 or later ## Overview **tuner-pipecat-sdk** is an observer that captures latency signals, transcript segments, and usage metadata from your Pipecat pipeline, then sends a structured `CallPayload` to Tuner when the call ends. You don't make any API calls yourself. If your agent's LLM step is a LangChain runnable or LangGraph graph, the same observer also captures node transitions, tool calls, and token usage from that layer. See [LangChain and LangGraph observability](#langchain-and-langgraph-observability) below. **1. Install the SDK** Add the package to your project with pip. **2. Pass your credentials** Give the observer your Tuner API key, workspace ID, and Agent Remote ID. **3. Add the observer** Create an observer instance and register it on your pipeline task. **4. Enable simulation** Required only if you use Call Simulation. See [Enable simulation](#enable-simulation). ## Step 1: Install the SDK ```shell theme={null} pip install tuner-pipecat-sdk ``` **Requirements:** Python 3.11 to 3.13, `pipecat-ai>=1.0.0`. Do not use Python 3.14: Pipecat dependencies (`onnxruntime`, `numba`) do not yet have 3.14 wheels. Optional extras: | Extra | Install | Adds | | - | - | - | | `traces` | `pip install 'tuner-pipecat-sdk[traces]'` | OpenTelemetry trace forwarding. See [OpenTelemetry traces](#opentelemetry-traces). | | `langchain` | `pip install 'tuner-pipecat-sdk[langchain]'` | `wrap_graph()` and `wrap_chain()`. See [LangChain and LangGraph observability](#langchain-and-langgraph-observability). | ## Step 2: Pass your credentials The `Observer` does not read environment variables. Pass the credentials as constructor arguments. You can load them from your own environment variables, as below. ```python theme={null} import os import uuid from tuner_pipecat_sdk import Observer observer = Observer( api_key=os.environ["TUNER_API_KEY"], workspace_id=int(os.environ["TUNER_WORKSPACE_ID"]), agent_id="fa4da74c-...", call_id=str(uuid.uuid4()), ) ``` | Parameter | Required | Description | | - | - | - | | `api_key` | ✅ | Tuner API key (starts with `tr_api_`) | | `workspace_id` | ✅ | Your Tuner workspace ID (integer) | | `agent_id` | ✅ | **Agent Remote ID** from **Agent Settings > Agent Connection**. This is a UUID, not your agent's display name. | | `call_id` | ✅ | A unique ID for this call. Use `uuid4()`. | | `base_url` | No | API base URL (default: `https://api.usetuner.ai`) | > [!TIP] > > Use the **Agent Remote ID** from **Agent Settings > Agent Connection**, not your agent's display name. It is a UUID (for example `fa4da74c-...`). Copy **your** value from the Tuner dashboard. ## Step 3: Add the observer Create an `Observer` instance and attach turn tracking: ```python theme={null} import uuid from tuner_pipecat_sdk import Observer from pipecat.observers.turn_tracking_observer import TurnTrackingObserver turn_tracker = TurnTrackingObserver() observer = Observer( api_key="tr_api_...", workspace_id=42, agent_id="fa4da74c-...", call_id=str(uuid.uuid4()), asr_model="deepgram/nova-3", llm_model="gpt-4o-mini", tts_model="cartesia/sonic", ) observer.attach_turn_tracking_observer(turn_tracker) ``` `Observer` is a pipeline-level observer. Register it, its `latency_observer` and the turn tracker in `observers=[...]` on the `PipelineTask`, not as a processor inside `Pipeline([...])`: ```python theme={null} from pipecat.pipeline.task import PipelineTask, PipelineParams task = PipelineTask( pipeline, params=PipelineParams( enable_metrics=True, enable_usage_metrics=True, ), observers=[observer, observer.latency_observer, turn_tracker], ) ``` Without `enable_metrics` and `enable_usage_metrics`, the observer logs warnings and LLM/TTS metric fields are absent from the payload. > [!NOTE] > > From pipecat-ai 1.3, `PipelineWorker` replaces `PipelineTask`. The examples on this page use `PipelineTask`. When Pipecat emits `EndFrame` or `CancelFrame`, the observer sends the call to Tuner in the background. If the request fails, the SDK logs the failure and never raises or blocks your pipeline. If a call doesn't show up in Tuner, check your logs for `[tuner] failed to deliver call`. For more examples, see the [tuner-pipecat-sdk-python examples](https://github.com/usetuner/tuner-pipecat-sdk-python/tree/main/examples). ## Enable simulation Required for [Call Simulation](/docs/simulation/overview). Skip it otherwise. ### Inbound Tuner calls your agent over SIP. | SDK | Version | | - | - | | Python, `tuner-pipecat-sdk` | 0.2.9 or later | Your carrier sends each call to a webhook, then opens a WebSocket for the audio. Tuner's SIP data reaches the webhook but not the WebSocket. Forward it from the webhook, then attach it in your bot. **1. Add your SIP URI in Tuner** Add your agent's SIP URI in **Agent Settings > Simulation Setup**. Get it from your [SIP provider](/docs/simulation/inbound/other-platforms), then see [Set up inbound simulation](/docs/simulation/inbound/setup). **2. Forward the SIP data from your webhook** Read the SIP data from the carrier's request and put it on the WebSocket. > [tab] Twilio > > ```python theme={null} > from tuner_pipecat_sdk import extract_sip, forward_to_websocket > > @app.post("/twiml") > async def twiml(request): > info = extract_sip(await request.form(), provider="twilio") > fwd = forward_to_websocket(info, ws_url="wss://your-host/ws") > return Response(content=fwd.twiml, media_type="application/xml") > ``` > > Set the Voice URL of the Twilio SIP Domain that Tuner dials to this route. Pipecat's built-in dev runner returns TwiML with no `` tags, so use your own webhook. > [tab] Telnyx > > ```python theme={null} > info = extract_sip(webhook_json, provider="telnyx") # call.initiated > fwd = forward_to_websocket(info, ws_url="wss://your-host/ws") > > # answer rejects custom_parameters, so answer first, then start the stream > await telnyx_post(f"/v2/calls/{call_control_id}/actions/answer", {}) > await telnyx_post(f"/v2/calls/{call_control_id}/actions/streaming_start", fwd.stream) > ``` > > Tuner dials the SIP subdomain of a Call Control application. Set the application's webhook to this handler. **3. Attach the SIP data in your bot** In your WebSocket handler, read the SIP data from the first message and attach it to the observer. Do this before the call ends. ```python theme={null} start = ... # the WebSocket "start" message observer.attach_sip(extract_sip(start, provider="twilio")) # or "telnyx" ``` On Twilio, the `call_data` from Pipecat's `parse_telephony_websocket` also works. On Telnyx, pass the raw `start` message, because `parse_telephony_websocket` drops its `custom_parameters`. Twilio forwards `SipCallId` and `X-Correlation-Id`. Telnyx's `call.initiated` event has no SIP Call-ID, so `X-Correlation-Id` links a Telnyx call. Tuner links the call on either one. You can call `attach_sip` more than once. Headers merge, and the first non-empty value wins. > [accordion] Plivo, Exotel, Jambonz, Daily or your own SIP trunk > > The SDK reads the SIP data for these carriers but doesn't build the forwarding. You configure the carrier yourself, then attach in your bot. > > | Carrier | Configure | Attach | > | - | - | - | > | Plivo | Add `extraHeaders="SipCallId={{sip_call_id}}"` to `` | `observer.attach_sip(extract_sip(call_data, provider="plivo"))` | > | Exotel | Add `custom_parameters: SipCallId=<%CallSid%>` in the Voicebot applet | `observer.attach_sip(extract_sip(call_data, provider="exotel"))` | > | Jambonz | SIP data arrives on the call-hook webhook, not the WebSocket. `JambonzPendingStore` holds it until the WebSocket opens. See [`jambonz_server.py`](https://github.com/usetuner/tuner-pipecat-sdk-python/tree/main/examples/nova_clinic_pipecat). | `observer.attach_sip(extract_sip(call_hook_json, provider="jambonz"))` | > | Daily dial-in | Nothing | `observer.attach_sip(extract_sip(runner_args.body["dialin_settings"], provider="daily"))` | > | Your own SIP trunk | Nothing | `observer.attach_sip(sip_call_id=..., sip_headers={"X-Correlation-Id": ...})` | > > Web calls have no SIP data. Skip this section for them. > [accordion] How the SIP data reaches your bot > > ```mermaid theme={null} > sequenceDiagram > participant T as Tuner > participant C as Carrier > participant W as Your webhook > participant B as Your bot > T->>C: Call with Call-ID and X-Correlation-Id > C->>W: Webhook request with the SIP data > W->>C: forward_to_websocket puts the SIP data on the stream > C->>B: WebSocket start message with the SIP data > B->>T: Call report with sip_call_id and sip_headers > ``` > [accordion] Support another carrier > > Register an object with a `name` and `extract(payload) -> SipInfo`. Add `forward_to_websocket(info, ws_url) -> Forward` to support forwarding. > > ```python theme={null} > from tuner_pipecat_sdk import Forward, SipInfo, register_provider > > class AcmeProvider: > name = "acme" > > def extract(self, payload) -> SipInfo: > return SipInfo(sip_call_id=payload["sip_call_id"], sip_headers=payload["headers"]) > > def forward_to_websocket(self, info: SipInfo, ws_url: str) -> Forward: ... > > register_provider(AcmeProvider()) > ``` > [accordion] Older SDK versions > > These methods still work in 0.2.9 and warn once. Use the replacement. > > | Deprecated | Use | > | - | - | > | `attach_sip_from_telephony(payload, provider=...)` | `attach_sip(extract_sip(payload, provider=...))` | > | `attach_sip_from_context(ctx)` | `attach_sip(extract_sip(payload, provider=...))` | > | `attach_sip_from_dialin(settings)` | `attach_sip(extract_sip(settings, provider="daily"))` | > | `attach_sip_info(sip_call_id=..., sip_headers=...)` | `attach_sip(sip_call_id=..., sip_headers=...)` | > | `build_sip_forwarding_twiml(form, ws_url=...)` | `forward_to_websocket(extract_sip(form, provider="twilio"), ws_url=...).twiml` | ### Outbound Your agent calls a Simulated Caller at a SIP URI that Tuner sends to your trigger endpoint. 1. Configure the trigger endpoint in **Agent Settings > Simulation Setup**. See [Set up outbound simulation](/docs/simulation/outbound). 2. Report the SIP URI your agent dialed as `recipient`, exactly as Tuner sent it. Reading it from the stream needs `tuner-pipecat-sdk` 0.2.9 or later. If your bot gets audio from a Twilio or Telnyx media stream, put the SIP URI on the stream when you place the call. Then the bot reads it from the `start` message. > [tab] Twilio > > ```python theme={null} > from tuner_pipecat_sdk import SipInfo, extract_sip, forward_to_websocket > > fwd = forward_to_websocket(SipInfo(recipient=dialed_sip_uri), ws_url="wss://your-host/ws", provider="twilio") > twilio_client.calls.create(to=dialed_sip_uri, from_=..., twiml=fwd.twiml) > > # in the bot, on the WebSocket "start" message > observer.attach_sip(extract_sip(start, provider="twilio")) > ``` > [tab] Telnyx > > ```python theme={null} > from tuner_pipecat_sdk import SipInfo, extract_sip, forward_to_websocket > > fwd = forward_to_websocket(SipInfo(recipient=dialed_sip_uri), ws_url="wss://your-host/ws", provider="telnyx") > # on call.answered for the call you placed > await telnyx_post(f"/v2/calls/{call_control_id}/actions/streaming_start", fwd.stream) > > # in the bot, on the WebSocket "start" message > observer.attach_sip(extract_sip(start, provider="telnyx")) > ``` If your bot already has the SIP URI, pass it directly: ```python theme={null} Observer( ..., recipient=dialed_sip_uri, # the SIP URI Tuner sent, unchanged ) ``` ## Check simulation works Start a simulation run. See [Run a simulation](/docs/simulation/run-a-simulation). When the call ends, check its result in the run. If it shows **Unreported**, Tuner never received a matching call from your agent. See [Fix an Unreported run](/docs/simulation/run-statuses#fix-an-unreported-run). ## End-of-utterance (EOU) delay Wire your user context aggregator to the observer to capture how long the pipeline took to decide the user was done talking: the gap between the user going silent and the turn closing. This appears on every user turn in the transcript view as `eou_delay`, `eou_confidence`, and `eou_reason`. ```python theme={null} theme={null} user_aggregator, assistant_aggregator = LLMContextAggregatorPair( context, user_params=LLMUserAggregatorParams(vad_analyzer=SileroVADAnalyzer()), ) observer.attach_user_aggregator(user_aggregator) ``` `eou_reason` tells you *which* signal closed the turn, so `eou_delay` means something different depending on the value: | `eou_reason` | What closed the turn | `eou_delay` measures | | - | - | - | | `silence_timeout` | Local VAD silence threshold | ms from the last VAD-detected speech-end to the turn closing | | `model_verdict` | A turn-completion model (e.g. Smart Turn) decided | the model's own end-to-end decision time; `eou_confidence` carries its probability | | `stt_endpoint` | Server-side STT (e.g. Deepgram Flux) decided on its own clock | not populated, because the decision happens server-side, independent of local VAD | All three fields are omitted from a turn's metadata when nothing decided that turn's end. ## LangChain and LangGraph observability If you use LangGraph or LangChain for your LLM step, the observer can capture node transitions, tool calls, and token usage from inside that runnable alongside the standard call data. Install the `langchain` extra and see [LangChain / LangGraph](/docs/integrations/custom-stack/langchain#attach-to-your-stack). ## Configuration options > [accordion] Call type > > Override the default call type label (default: `"web_call"`): > > ```python theme={null} > Observer(..., call_type="web_call") > Observer(..., call_type="phone_call") > ``` > [accordion] Recording URL > > Provide a recording URL if available. Default is `"pipecat://no-recording"`: > > ```python theme={null} > Observer(..., recording_url="https://cdn.example.com/recordings/call-123.ogg") > ``` > > The URL must be a public `https://` link. Tuner stores the default or any other value as sent, but treats the call as having no recording: it has no playback in call details and can't be added to a [Dataset](/docs/datasets/add-calls). > [accordion] Disconnection reason > > Record why a call ended by passing a `disconnection_reason_resolver` callable. The resolver is called at flush time and should return a string or `None`. > > Use the built-in constants from `DisconnectReason` or pass a custom string: > > | Constant | Value | > | - | - | > | `DisconnectReason.USER_HANGUP` | `"user_hangup"` | > | `DisconnectReason.AGENT_HANGUP` | `"agent_hangup"` | > | `DisconnectReason.ERROR` | `"error"` | > | `DisconnectReason.TIMEOUT` | `"timeout"` | > | `DisconnectReason.UNKNOWN` | `"unknown"` | > > ```python theme={null} > from tuner_pipecat_sdk.models import DisconnectReason > > _reason = None > > def resolve_reason() -> str | None: > return _reason > > observer = Observer(..., disconnection_reason_resolver=resolve_reason) > > # Set the reason when your app knows it > _reason = DisconnectReason.USER_HANGUP > ``` > [accordion] Model names > > Specify your ASR, LLM, and TTS models. They are recorded as call metadata: > > ```python theme={null} > Observer( > ..., > asr_model="deepgram/nova-3", > llm_model="gpt-4o-mini", > tts_model="cartesia/sonic", > ) > ``` > [accordion] Extra metadata > > Attach arbitrary key-value data to every call record, such as environment, region, deployment version, or tenant: > > ```python theme={null} > Observer( > ..., > extra_metadata={ > "env": "production", > "region": "us-east-1", > "deployment": "v2.3.1", > }, > ) > ``` > > Metadata can also be used as an eval input. See [Evaluate agents with per-call instructions](/docs/evaluation/dynamic-agents). > [accordion] Agent version > > Track which version of your agent handled each call. Set `APP_VERSION` in your environment: > > ```shell theme={null} > APP_VERSION=42 python agent.py start > ``` > > If `APP_VERSION` is not set, the observer reads `GITHUB_RUN_NUMBER`, `CIRCLE_BUILD_NUM` or `BUILD_NUMBER`. The value must be an integer. The constructor argument takes priority over all of them: > > ```python theme={null} > Observer(..., agent_version=42) > ``` > [accordion] Trace forwarding > > With the `traces` extra installed, the observer forwards Pipecat's OpenTelemetry spans to Tuner. `forward_traces` defaults to `True`. To turn it off: > > ```python theme={null} > Observer(..., forward_traces=False) > ``` > > See [OpenTelemetry traces](#opentelemetry-traces). > [accordion] Debug mode > > Log the full transcript when flushing: > > ```python theme={null} > Observer(..., debug=True) > ``` > [accordion] Cost calculation > > Provide a callable that receives the call's usage summary (`CallUsage`) and returns the call cost in USD cents. Implement the method that matches your pricing plan; the snippet below is illustrative. > > ```python theme={null} > def calculate_cost(usage) -> float: > # OpenAI gpt-4o-mini pricing (per token / per character / per second) > llm_cost = (usage.llm_prompt_tokens or 0) * 0.000_000_150 > llm_cost += (usage.llm_completion_tokens or 0) * 0.000_000_600 > # OpenAI TTS-1: $15 per 1M characters > tts_cost = (usage.tts_characters or 0) * 0.000_015 > # OpenAI gpt-4o-transcribe: $6 per 1M audio seconds > stt_cost = usage.stt_audio_seconds * 0.000_006 > return (llm_cost + tts_cost + stt_cost) * 100 # USD -> cents > > Observer(..., cost_calculator=calculate_cost) > ``` > > `stt_audio_seconds` is the call's wall-clock duration in seconds, used as a proxy for STT duration. ## Full example ```python theme={null} import os import uuid from tuner_pipecat_sdk import Observer, extract_sip from tuner_pipecat_sdk.models import DisconnectReason from pipecat.observers.turn_tracking_observer import TurnTrackingObserver from pipecat.pipeline.pipeline import Pipeline from pipecat.pipeline.task import PipelineTask, PipelineParams async def run_bot(call_data, context, transport, stt, llm, tts, context_aggregator): # call_data is the payload from your telephony WebSocket handler # e.g. _, call_data = await parse_telephony_websocket(websocket) turn_tracker = TurnTrackingObserver() _reason = None # update the rates to match your models def calculate_cost(usage) -> float: # OpenAI gpt-4o-mini pricing (per token / per character / per second) llm_cost = (usage.llm_prompt_tokens or 0) * 0.000_000_150 llm_cost += (usage.llm_completion_tokens or 0) * 0.000_000_600 # OpenAI TTS-1: $15 per 1M characters tts_cost = (usage.tts_characters or 0) * 0.000_015 # OpenAI gpt-4o-transcribe: $6 per 1M audio seconds stt_cost = usage.stt_audio_seconds * 0.000_006 return (llm_cost + tts_cost + stt_cost) * 100 observer = Observer( api_key=os.environ["TUNER_API_KEY"], workspace_id=int(os.environ["TUNER_WORKSPACE_ID"]), agent_id="fa4da74c-...", call_id=str(uuid.uuid4()), call_type="phone_call", asr_model="deepgram/nova-3", llm_model="gpt-4o-mini", tts_model="cartesia/sonic", disconnection_reason_resolver=lambda: _reason, cost_calculator=calculate_cost, extra_metadata={"env": "prod", "region": "us-east-1"}, ) # Inbound simulation: attach the SIP data (see Enable simulation) observer.attach_sip(extract_sip(call_data, provider="twilio")) observer.attach_turn_tracking_observer(turn_tracker) pipeline = Pipeline([ transport.input(), stt, context_aggregator.user(), llm, tts, transport.output(), context_aggregator.assistant(), ]) task = PipelineTask( pipeline, params=PipelineParams( enable_metrics=True, enable_usage_metrics=True, ), observers=[observer, observer.latency_observer, turn_tracker], ) _reason = DisconnectReason.USER_HANGUP ``` > [!TIP] > > Using LangChain or LangGraph for your LLM step instead of a native Pipecat LLM service? Swap `llm` for a `LangchainProcessor` wrapping `observer.wrap_graph(...)` or `observer.wrap_chain(...)`. See [LangChain / LangGraph](/docs/integrations/custom-stack/langchain#attach-to-your-stack). ## OpenTelemetry traces Pipecat emits OpenTelemetry spans for every conversation when tracing is on. The SDK forwards them to Tuner, and they appear as a span tree on the call's **Traces** tab. See [Traces](/docs/observability/traces) for how to read one. > [!NOTE] > > Requires `tuner-pipecat-sdk` 0.2.8 or later. **1. Install the tracing extras** ```shell theme={null} pip install 'pipecat-ai[tracing]' # lets Pipecat emit spans pip install 'tuner-pipecat-sdk[traces]' # lets the SDK forward them to Tuner ``` Without the `traces` extra, trace forwarding is skipped with a debug log, and the rest of the observer works as usual. **2. Turn on tracing in Pipecat** Set `enable_tracing=True` on your `PipelineTask`. This is Pipecat's own switch for emitting spans. The SDK can't set it for you, because you create the task after the observer. ```python theme={null} task = PipelineTask( pipeline, params=PipelineParams(enable_metrics=True, enable_usage_metrics=True), observers=[observer, observer.latency_observer, turn_tracker], enable_tracing=True, # required enable_turn_tracking=True, # recommended: gives the trace its turn structure ) ``` **3. Keep forward_traces on** `forward_traces` defaults to `True` on the `Observer`. The SDK sends spans to Tuner with the API key and base URL you passed to the `Observer`, and tags every span with your `call_id`. You don't need `setup_tracing(...)`, a `TracerProvider`, an exporter, or any `OTEL_*` environment variable. If you already call Pipecat's `setup_tracing(...)` to export traces elsewhere, the SDK adds Tuner as an extra destination. If you configure an exporter yourself, use the OTLP HTTP exporter: Tuner does not accept gRPC. To stop forwarding traces, pass `forward_traces=False`. Pipecat's `enable_tracing` is a separate switch that controls whether Pipecat produces spans at all. **4. Check that it worked** Open the call in Tuner. A **Traces** tab appears on the call details page once spans have been received and matched. Matching completes when the call itself is ingested, so the tab can take a moment to appear after a call ends. ### Span reference The span names come from Pipecat, so they are the same ones you would see in any other OpenTelemetry backend. Service spans nest under turns, under one conversation span: ``` conversation └── turn ├── stt ├── llm └── tts ``` Realtime models such as Gemini Live and OpenAI Realtime replace the `llm` span with `llm_setup`, `llm_response`, and `llm_tool_call` or `llm_tool_result`. See [Pipecat's OpenTelemetry documentation](https://docs.pipecat.ai/server/utilities/opentelemetry) for the full set, and [Traces](/docs/observability/traces) for how to read the tree in Tuner. ## Webhooks Tuner can notify your systems when it has something to report on a call. See [Webhooks](/docs/integrations/webhooks). ## Before you finish * A test call appears in [Call Logs](/docs/observability/call-logs). * Your API key, workspace ID and Agent Remote ID come from [API keys](/docs/getting-started/api-keys). * If you use Call Simulation: [Enable simulation](#enable-simulation) is done for your agent's call direction, and one simulated call shows a result other than **Unreported**. ## Troubleshooting > [accordion] No matching distribution found for onnxruntime > > **Python 3.14**: Pipecat pins `onnxruntime` versions that have no 3.14 wheels. Switch to **Python 3.12 or 3.13** and create a new venv. > [accordion] Failed to build numba / Cannot install on Python 3.14 > > Same as above: use **Python 3.12 or 3.13**. > [accordion] Calls don't appear in Tuner > > * Verify that `agent_id` is the **Agent Remote ID** from **Agent Settings > Agent Connection** (not your agent's display name). > * Confirm `workspace_id` is correct. > * Ensure `enable_metrics=True` and `enable_usage_metrics=True` are set on `PipelineParams`. > * Check your application logs for `[tuner] failed to deliver call`. > [accordion] Unauthorized (401) > > * Ensure `api_key` starts with `tr_api_` and is valid. > * Confirm the API key belongs to the correct workspace. > [accordion] Simulated calls show as Unreported > > * `sip_call_id` is the Twilio `CA…` CallSid: your TwiML had no `SipCallId` parameter. Return `forward_to_websocket(...).twiml` from your webhook. > * No `X-Correlation-Id` on a Telnyx call: the stream started without `custom_parameters`. Send `fwd.stream` as the `streaming_start` body. > * `sip_call_id` is `null`: `attach_sip` never ran. Call it with the WebSocket `start` message. > * `ValueError: Unknown provider`: the name is misspelled. Use a built-in name or `register_provider`. > * See [Fix an Unreported run](/docs/simulation/run-statuses#fix-an-unreported-run). > [accordion] wrap_graph / wrap_chain raises ImportError > > The `langchain` extra isn't installed. Run `pip install 'tuner-pipecat-sdk[langchain]'`. > [accordion] The Traces tab never appears > > 1. **`enable_tracing=True` is missing on the `PipelineTask`.** Pipecat emits no spans without it. > 2. **The `traces` extra isn't installed.** Install `tuner-pipecat-sdk[traces]` and `pipecat-ai[tracing]`. > 3. **`forward_traces=False` is set on the `Observer`.** > 4. **The API key is wrong or revoked.** Tuner rejects the spans with `401` or `403`. ## Next steps > [card] [Configure your agent](/docs/getting-started/quickstart) > > Set up call outcomes, user intents, and evals. > [card] [Custom integration](/docs/integrations/custom-stack/overview) > > Learn about the underlying API if you need more control. > [card] [Classify calls](/docs/evaluation/call-classification) > > Define how Tuner categorizes your calls. > [card] [Alerts](/docs/observability/alerts) > > Get notified when issues are detected. # Connecting to Retell Source: https://docs.usetuner.ai/docs/integrations/retell Connect a Retell voice agent to Tuner with your Retell API key, import its recent calls, and keep your existing webhook automations. > [!NOTE] > > **Prerequisites:** an active Retell account with at least one agent, and a Tuner account. No code is needed. ## Overview You connect a Retell agent from the agent setup wizard in Tuner. You paste your Retell API key, pick the Retell agent, and Tuner configures the Retell webhook for you. **1. Get your Retell API key** Copy an API key from the Retell dashboard. **2. Create the agent in Tuner** Click **Create New Agent**, choose **Retell**, connect your key and pick your Retell agent. **3. Import recent calls** On the last wizard step, import your most recent Retell calls so they're evaluated right away. > [!NOTE] > > **No webhook configuration needed.** When you create the agent, Tuner sets the webhook URL on your Retell agent. This replaces any webhook URL already set there. See [Webhooks](#webhooks) for how to keep your existing automations running. *** ## Step 1: Get your Retell API key Your Retell **API Key** lets Tuner authenticate with Retell, list your agents and ingest call data. 1. Log in to your [Retell dashboard](https://dashboard.retellai.com/). 2. Open **Settings** and go to **API Keys** (or your workspace's API key section, depending on your Retell UI). 3. **Create** a new key or copy an existing one. > [!TIP] > > Treat your Retell API Key like a password. Do not commit it to source control or expose it in client-side code. ### Find your Retell Agent ID (only if needed) The wizard lists your Retell agents, so you usually don't need the Agent ID. You only type it in if the list can't load or is empty. 1. Open the [Retell dashboard](https://dashboard.retellai.com/agents) and click the agent you want to connect. 2. Copy the **Agent ID** shown at the top of the page. It starts with `agent_`. > [!TIP] > > The Agent ID is also in the URL when you view an agent, for example `https://dashboard.retellai.com/agents/agent_bcf7565e36612c8b9929857f4b`. *** ## Step 2: Create your agent in Tuner **1. Open the wizard** In the sidebar, click **Create New Agent**. Before your workspace has its first agent, the button reads **Set up your first agent**. The full-screen setup wizard opens. **2. Choose Retell** Under **Where does your agent run?**, select **Retell**. **3. Connect your Retell API key** Under **Connection**, paste your key into **Retell API key** and click **Connect**. Tuner validates the key and stores it in your workspace settings. If your workspace already has a Retell key, the wizard shows **Using your workspace's Retell key** instead. Click **Change** to use a different key. **4. Pick your Retell agent** In **Which agent?**, choose the Retell agent to connect. Tuner selects the first agent in the list and fills in **Agent name** and the system prompt from Retell. You can edit both. If the list can't load or your account has no agents, the wizard shows an **Agent ID** field instead. Paste the Agent ID from Retell. **5. Fill in the details** Under **Details**, check **Agent name** and set **Call direction** to **Inbound** or **Outbound**, matching how the agent is used. The system prompt is optional; click **Add system prompt (optional)** to add one if it wasn't imported. **6. Add the agent** Click **Add agent**. Tuner creates the agent and sets its webhook URL on your Retell agent. **7. Choose how to configure it** Under **How do you want to configure it?**, choose **Start from a template**, **Configure via MCP** or **Set up manually**, then click **Continue**. **8. Get your first evaluated call** The last step checks your Retell account for recent calls. See [Import recent Retell calls](#import-recent-retell-calls). ![The Add an agent wizard with Retell selected: the Connection section shows "Using your workspace's Retell key" and the Which agent? picker](https://mintcdn.com/tuner/6TrbntNcJS8frrHh/images/wizard-retell.png?fit=max\&auto=format\&n=6TrbntNcJS8frrHh\&q=85\&s=8ad4c15b9924e81dcf8681f12ff2b7a7) ### Save the key in Workspace Settings instead You can also save or replace your Retell key outside the wizard: 1. Open **Workspace Settings > General Settings**. 2. Under **Third-party Integrations**, paste your key into **Retell API Key**. 3. Click **Save Changes**. A saved key shows as **Saved, ending in** followed by its last characters. The wizard then uses it automatically. ![The Third-party Integrations card in Workspace Settings, with saved Retell and Vapi keys shown as "Saved, ending in" and the Save Changes button](https://mintcdn.com/tuner/6TrbntNcJS8frrHh/images/third-party-integrations.png?fit=max\&auto=format\&n=6TrbntNcJS8frrHh\&q=85\&s=b95430779318dc59bec25e39fe4d3841) *** ## Import recent Retell calls On the last wizard step, **Get your first evaluated call**, Tuner checks your Retell account for calls from the connected agent. **1. Review the calls found** If Tuner finds recent calls, it shows a **Found N recent calls** card. **2. Import and evaluate them** Click **Import & evaluate all N**. Tuner imports your most recent calls and runs your evals on them. A progress bar shows how many are done. Importing needs available credits in your workspace. **3. View the results** When the import finishes, click **View your calls** to finish setup and open [Call Logs](/docs/observability/call-logs). If no recent calls are found, the step shows a **Real call** card and a **Simulated call** card instead. Make a call to your Retell agent or run a [simulation](/docs/simulation/inbound/setup#retell), then click **Finish**. To bring in older calls after setup, use **Import older calls** on the [Call Logs](/docs/observability/call-logs) page. | Limit | Value | | - | - | | Calls imported during setup | Up to 25, most recent first | | Lookback window for the setup import | Last 30 days | *** ## Enable simulation Required if you'll use [Call Simulation](/docs/simulation/overview). Skip it otherwise. ### Inbound There is nothing to set up. Tuner starts each simulated call through Retell, using your agent's Agent Remote ID and the Retell API key saved in your workspace. See [Simulate a Retell agent](/docs/simulation/inbound/setup#retell). ### Outbound Outbound simulation isn't available for Retell agents. ## Check simulation works Start a simulation run. See [Run a simulation](/docs/simulation/run-a-simulation). When the call ends, check its result in the run. If it shows **Unreported**, Tuner never received a matching call from Retell. See [Fix an Unreported run](/docs/simulation/run-statuses#fix-an-unreported-run). *** ## Webhooks > [!WARNING] > > **Connecting to Tuner replaces the webhook URL on your Retell agent.** Tuner points that webhook at itself, so any URL you had set there (n8n, Zapier, your own backend) stops receiving Retell events. Add that URL in Tuner under **Agent Settings > Webhooks** instead. It then receives: * **Tuner events:** `call.analyzed` and `alert.fired`. * **Retell's `call_analyzed` event:** forwarded as a `call.received` event, with Retell's original body in `payload`. Tuner forwards only Retell's `call_analyzed` event. Other Retell events are not forwarded, so an automation that depends on them stops receiving them. See [Webhooks](/docs/integrations/webhooks) for the event format, headers and URL requirements. ## Troubleshooting > [accordion] The key won't connect > > The wizard shows an error under **Retell API key** when Retell rejects the key. Check that you copied the whole key with no extra spaces, or create a new key in Retell and try again. > [accordion] My agent isn't in the list > > If you have many Retell agents, the list shows the most recent ones. If your agent is missing, or the wizard shows the **Agent ID** field, paste the Agent ID from Retell. It starts with `agent_`. > [accordion] Calls don't appear in Tuner > > Check that the agent's **Agent Remote ID** in **Agent Settings > Agent Setup** matches the Retell Agent ID, and that a Retell key is saved under **Workspace Settings > General Settings > Third-party Integrations**. ## Next steps > [card] [Run a simulation](/docs/simulation/run-a-simulation) > > Test your Retell agent against generated Scenarios. > [card] [Configure via MCP](/docs/mcp/setup) > > Use your IDE or chat app to generate outcomes, intents, evals and alerts. # Connecting to Vapi Source: https://docs.usetuner.ai/docs/integrations/vapi Connect a Vapi assistant to Tuner with your Vapi Private API key, import its recent calls, and keep your existing webhook automations. > [!NOTE] > > **Prerequisites:** an active Vapi account with at least one assistant, and a Tuner account. No code is needed. If you create Vapi assistants at call time, see [Vapi transient assistants](/docs/integrations/vapi-transient-assistants) instead. ## Overview You connect a Vapi assistant from the agent setup wizard in Tuner. You paste your Vapi Private API key, pick the assistant, and Tuner configures the Vapi server URL for you. **1. Get your Vapi Private API key** Copy a Private API key from the Vapi dashboard. **2. Create the agent in Tuner** Click **Create New Agent**, choose **Vapi**, connect your key and pick your assistant. **3. Import recent calls** On the last wizard step, import your most recent Vapi calls so they're evaluated right away. > [!NOTE] > > **No webhook configuration needed.** When you create the agent, Tuner sets the server URL on your Vapi assistant. This replaces any server URL already set there. See [Webhooks](#webhooks) for how to keep your existing automations running. *** ## Step 1: Get your Vapi API key Use a **Private API Key** from Vapi. The **Public** key is meant for client-side use; Tuner needs a Private key for server-side access. 1. Log in to the [Vapi dashboard](https://dashboard.vapi.ai/). 2. Open **API Keys** using either path: * Click your **profile menu** (top right) and choose **Vapi API Keys**, or * Go directly to [dashboard.vapi.ai/org/api-keys](https://dashboard.vapi.ai/org/api-keys). 3. Under **Private API Keys**, copy an existing key or create a new one. > [!TIP] > > Treat your Private API Key like a password. Never paste it into frontend code, public repos or source control. ### Find your Vapi Assistant ID (only if needed) The wizard lists your Vapi assistants, so you usually don't need the Assistant ID. You only type it in if the list can't load or is empty. 1. In the [Vapi dashboard](https://dashboard.vapi.ai/), open **Assistants** and click the assistant you want to connect. 2. Copy the **Assistant ID** from the assistant detail page. It may also appear in the page URL. *** ## Step 2: Create your agent in Tuner **1. Open the wizard** In the sidebar, click **Create New Agent**. Before your workspace has its first agent, the button reads **Set up your first agent**. The full-screen setup wizard opens. **2. Choose Vapi** Under **Where does your agent run?**, select **Vapi**. **3. Connect your Vapi API key** Under **Connection**, paste your Private key into **Vapi API key** and click **Connect**. Tuner validates the key and stores it in your workspace settings. If your workspace already has a Vapi key, the wizard shows **Using your workspace's Vapi key** instead. Click **Change** to use a different key. **4. Pick your assistant** In **Which agent?**, choose the Vapi assistant to connect. Tuner selects the first assistant in the list and fills in **Agent name** and the system prompt from Vapi. You can edit both. If the list can't load or your account has no assistants, the wizard shows an **Agent ID** field instead. Paste the Assistant ID from Vapi. **5. Fill in the details** Under **Details**, check **Agent name** and set **Call direction** to **Inbound** or **Outbound**, matching how the assistant is used. The system prompt is optional; click **Add system prompt (optional)** to add one if it wasn't imported. **6. Add the agent** Click **Add agent**. Tuner creates the agent and sets its server URL on your Vapi assistant. **7. Choose how to configure it** Under **How do you want to configure it?**, choose **Start from a template**, **Configure via MCP** or **Set up manually**, then click **Continue**. **8. Get your first evaluated call** The last step checks your Vapi account for recent calls. See [Import recent Vapi calls](#import-recent-vapi-calls). ![The Add an agent wizard with Vapi selected: the Connection section shows "Using your workspace's Vapi key" and the Which agent? picker](https://mintcdn.com/tuner/6TrbntNcJS8frrHh/images/wizard-vapi.png?fit=max\&auto=format\&n=6TrbntNcJS8frrHh\&q=85\&s=9354da672c1b722c8c477f8aeae6bbe2) ### Save the key in Workspace Settings instead You can also save or replace your Vapi key outside the wizard: 1. Open **Workspace Settings > General Settings**. 2. Under **Third-party Integrations**, paste your Private key into **Vapi API Key**. 3. Click **Save Changes**. A saved key shows as **Saved, ending in** followed by its last characters. The wizard then uses it automatically. ![The Third-party Integrations card in Workspace Settings, with saved Retell and Vapi keys shown as "Saved, ending in" and the Save Changes button](https://mintcdn.com/tuner/6TrbntNcJS8frrHh/images/third-party-integrations.png?fit=max\&auto=format\&n=6TrbntNcJS8frrHh\&q=85\&s=b95430779318dc59bec25e39fe4d3841) *** ## Import recent Vapi calls On the last wizard step, **Get your first evaluated call**, Tuner checks your Vapi account for calls from the connected assistant. **1. Review the calls found** If Tuner finds recent calls, it shows a **Found N recent calls** card. **2. Import and evaluate them** Click **Import & evaluate all N**. Tuner imports your most recent calls and runs your evals on them. A progress bar shows how many are done. Importing needs available credits in your workspace. **3. View the results** When the import finishes, click **View your calls** to finish setup and open [Call Logs](/docs/observability/call-logs). If no recent calls are found, the step shows a **Real call** card and a **Simulated call** card instead. Make a call to your assistant or run a [simulation](/docs/simulation/inbound/setup#vapi), then click **Finish**. Vapi only returns calls inside your Vapi plan's call history retention, so the check can cover fewer days than the limit below. To bring in older calls after setup, use **Import older calls** on the [Call Logs](/docs/observability/call-logs) page. | Limit | Value | | - | - | | Calls imported during setup | Up to 25, most recent first | | Lookback window for the setup import | Last 30 days | *** ## Enable simulation Required if you'll use [Call Simulation](/docs/simulation/overview). Skip it otherwise. Neither direction needs code. ### Inbound Create a Free Vapi SIP trunk linked to your assistant, then add its SIP URI in **Agent Settings > Simulation Setup**. See [Simulate a Vapi agent](/docs/simulation/inbound/setup#vapi). ### Outbound Open **Agent Settings > Simulation Setup**. Enter your Vapi number's **VAPI Phone Number ID**, or choose **No, I don't have one** to run the in-app setup that creates one. See [Set up outbound simulation](/docs/simulation/outbound#vapi). ## Check simulation works Start a simulation run. See [Run a simulation](/docs/simulation/run-a-simulation). When the call ends, check its result in the run. If it shows **Unreported**, Tuner never received a matching call from Vapi. See [Fix an Unreported run](/docs/simulation/run-statuses#fix-an-unreported-run). *** ## Webhooks > [!WARNING] > > **Connecting to Tuner replaces the server URL on your Vapi assistant.** Tuner points it at itself, so any URL you had set there (n8n, Zapier, your own backend) stops receiving Vapi events. Add that URL in Tuner under **Agent Settings > Webhooks** instead. It then receives: * **Tuner events:** `call.analyzed` and `alert.fired`. * **Vapi's `end-of-call-report` message:** forwarded as a `call.received` event, with Vapi's original body in `payload`. Tuner forwards only Vapi's `end-of-call-report` message. Other Vapi server messages are not forwarded, so an automation that depends on them stops receiving them. See [Webhooks](/docs/integrations/webhooks) for the event format, headers and URL requirements. ## Troubleshooting > [accordion] The key won't connect > > The wizard shows an error under **Vapi API key** when Vapi rejects the key. Check that you used a **Private** key, not the **Public** key, and that you copied it with no extra spaces. If it still fails, create a new Private key in Vapi and try again. > [accordion] My assistant isn't in the list > > If you have many Vapi assistants, the list shows the most recent ones. If your assistant is missing, or the wizard shows the **Agent ID** field, paste the Assistant ID from Vapi. > [accordion] Calls don't appear in Tuner > > Check that the agent's **Agent Remote ID** in **Agent Settings > Agent Setup** matches the Vapi Assistant ID, and that a Vapi Private key is saved under **Workspace Settings > General Settings > Third-party Integrations**. ## Next steps > [card] [Set up simulation for Vapi](/docs/simulation/inbound/setup#vapi) > > Create a SIP trunk in Vapi, connect it to Tuner, and run your first simulation batch. > [card] [Configure via MCP](/docs/mcp/setup) > > Use your IDE or chat app to generate outcomes, intents, evals and alerts. # Connect Vapi transient assistants Source: https://docs.usetuner.ai/docs/integrations/vapi-transient-assistants Creating your Vapi assistants at call time? Forward every finished call to one Tuner agent, with each agent's customization attached as metadata for Tuner's evals. > [!NOTE] > > This integration will later be available as a Tuner library (or built into > Tuner directly). For now, it's a single drop-in file. ## How it works Building your VAPI assistants **per call** (the inline `assistant` parameter, customized per customer, campaign, or experiment)? Those transient assistants have no `assistantId` for Tuner's [native VAPI integration](/docs/integrations/vapi) to import, so instead one function call in your **`end-of-call-report`** webhook pushes each finished call to Tuner. All of them report to **one Custom API agent in Tuner**: transcript, tool calls, per-turn voice metrics, recording, and cost. Attach each agent's customization (system prompt, variant, use case) as **metadata**, and Tuner runs your evals based on it. The integration ships in **two flavors, pick the one that matches your stack:** > [card] Node / TypeScript > > `send_to_tuner.ts`, Node 18+ (uses the built-in `fetch`). No npm > dependencies. > [card] Python > > `send_to_tuner.py`, Python 3.10+. One dependency: `requests`. > [!NOTE] > > Both behave identically: the integration never throws (any failure is logged > and your webhook handler is unaffected) and it's idempotent, so re-sending the > same call is harmless. ## Setup **1. Create a Tuner account** Sign up at [Tuner](https://usetuner.ai). **2. Create a Custom API agent** In Tuner, click **Create New Agent** in the sidebar (**Set up your first agent** if the workspace has no agent yet). Under **Where does your agent run?**, select **My own stack**, fill in **Agent name** and **Call direction**, and click **Add agent**. Tuner creates a Custom API agent and generates its **Agent Remote ID**. This is the agent your VAPI calls will show up under. **3. Add the file to your server** The whole integration is a single self-contained file with no dependencies beyond your language's basics. Create `send_to_tuner.ts` (Node) or `send_to_tuner.py` (Python) next to your VAPI server and paste in the full source below, switch tabs for Node or Python and use the copy button in the code block's top-right corner. ```ts Node [expandable] theme={null} /** * Send your VAPI calls to Tuner * ============================== * Drop this file next to your VAPI server and call `sendCallToTuner(message)` * from inside your `end-of-call-report` handler, that's the whole integration: * * sendCallToTuner(message); // fire-and-forget; never throws * * // optional: attach your own metadata object to the call in Tuner * sendCallToTuner(message, { customer_id: "cus_123", campaign: "june-promo" }); * * Every finished call, including its tool calls and tool results, will show * up under your Tuner agent. * * The function automatically downloads VAPI's call log (`artifact.logUrl`, * one extra GET, no API key needed) to enrich the call with exact per-turn * latencies and interruptions. If the log is missing or unreadable, it falls * back to payload-only enrichment by itself, the transcript never depends on * the log, and a call is never lost because of it. * * Setup (4 values, all from the Tuner dashboard): * 1. TUNER_BASE_URL -> your Tuner API base URL * 2. TUNER_API_KEY -> API Keys page (starts with "tr_api_") * 3. TUNER_WORKSPACE -> Workspace Settings > General Settings > Workspace ID * 4. TUNER_AGENT_ID -> create a "My own stack" agent in Tuner, then * Agent Settings > Agent Setup > Agent Remote ID * * Requirements: Node 18+ (uses the built-in fetch). No npm dependencies. */ // ============================================================================= // CONFIG, fill these in // ============================================================================= const TUNER_BASE_URL = "https://api.usetuner.ai"; // your Tuner API base URL const TUNER_API_KEY = "tr_api_xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"; const TUNER_WORKSPACE = 0; // your workspace id (number) const TUNER_AGENT_ID = "your-custom-api-agent-id"; // Network timeout & retry behavior for the POST to Tuner. const REQUEST_TIMEOUT_MS = 15_000; // per-attempt timeout for the POST to Tuner const MAX_ATTEMPTS = 3; // retry attempts on transient failures (network, 408, 429, 5xx) type Json = Record; /** VAPI call log: raw JSONL text, or an array of parsed log-line objects. */ type VapiLog = string | Json[]; // ============================================================================= // THE FUNCTION, call this from your end-of-call handler // ============================================================================= /** * Forward one VAPI `end-of-call-report` message to Tuner. * * `message` is the `body.message` object VAPI posts to your webhook. * `metadata` (optional) is a free-form object stored with the call in Tuner * (e.g. your own customer id, campaign, A/B variant). Sent only when you * provide it; nothing is sent by default. * * The VAPI call log is fetched internally from `artifact.logUrl`; when that * fails, the payload-only enrichment runs instead, fully automatic. * Pass `prefetchedLog` when you already downloaded the log (e.g. to save it * locally) so it isn't fetched twice. * Safe to call inline, it never throws; failures are logged, not thrown. */ export async function sendCallToTuner( message: Json, metadata?: Json | null, prefetchedLog?: Json[] | null, ): Promise { try { const call: Json = message.call ?? {}; const artifact: Json = message.artifact ?? {}; const callId = call.id; if (!callId) { console.warn("Tuner: end-of-call-report has no call id, call will not be sent"); return; } // VAPI keeps the timed, structured transcript under artifact.messages. const rawMessages: Json[] = artifact.messages ?? message.messages ?? []; const callStartMs = toEpochMs(message.startedAt); let segments = buildSegments(rawMessages, callStartMs); if (segments.length === 0) { console.warn(`Tuner: no transcript segments found, call ${callId} will not be sent`); return; } // Fetch VAPI's call log (one GET, no auth). null on any failure -> fallback. const log = prefetchedLog !== undefined ? prefetchedLog : await fetchVapiLog(artifact.logUrl ?? message.logUrl); // Attach per-turn latency: STT to the customer turn, LLM/TTS/e2e to the agent reply. // With a call log: exact interruptions + real metrics on post-tool replies. // Without (or if the log doesn't line up): the verified payload-only logic. const turnLatencies: Json[] = artifact.performanceMetrics?.turnLatencies ?? []; let logEnriched = false; if (log) { try { logEnriched = enrichFromLog(segments, log, turnLatencies); } catch (err) { logEnriched = false; console.warn( `Tuner: log enrichment failed for call ${callId} (${String(err)}), using payload-only metrics`, ); } } if (!logEnriched) { if (turnLatencies.length) { enrichWithTurnLatencies(segments, turnLatencies); } // Without log ground truth, deduce barge-ins from timing overlap. markInterruptions(segments); } // Re-join customer utterances that VAPI's stitcher sliced into two rows. mergeUserSlices(segments); segments = segments.map(stripNull); const stereoUrl = message.stereoRecordingUrl ?? artifact.stereoRecordingUrl ?? null; const recordingUrl = message.recordingUrl ?? artifact.recordingUrl ?? stereoUrl; if (!recordingUrl) { console.warn(`Tuner: no recording URL, call ${callId} will not be sent to Tuner`); return; } // Metadata is sent only when the caller provides it; Tuner accepts // free-form keys here and stores them with the call. It must be JSON- // serializable, anything else is dropped so the call itself still sends. let meta: Json | null = metadata && typeof metadata === "object" && !Array.isArray(metadata) && Object.keys(metadata).length ? metadata : null; if (meta) { try { JSON.stringify(meta); } catch { console.warn(`Tuner: metadata for call ${callId} is not JSON-serializable, sending without it`); meta = null; } } const { callAnalysis, callSuccessful } = mapAnalysis(message); // sip_call_id: the SIP Call-ID of the leg that reached VAPI, exposed by // VAPI as the "cid" variable (and as sbcCallSid). Tuner stores this same // id for its simulation calls, so it links the call back to a simulation // run. The correlation-id override variable is a last resort; nulls are // dropped below, so regular calls are unaffected. const correlationId = call.assistantOverrides?.variableValues?.["cid"] ?? call.transport?.sbcCallSid ?? call.phoneCallProviderDetails?.sbcCallId ?? call.assistantOverrides?.variableValues?.["correlation-id"] ?? null; // recipient: the call's destination address. const recipient = call.customer?.sipUri ?? call.customer?.number ?? null; const payload: Json = { call_id: callId, sip_call_id: correlationId, recipient, call_type: mapCallType(call.type), start_timestamp: callStartMs, end_timestamp: toEpochMs(message.endedAt), recording_url: recordingUrl, recording_multi_channel_url: stereoUrl, transcript: message.transcript ?? artifact.transcript ?? null, transcript_with_tool_calls: segments, call_status: "call_ended", disconnection_reason: typeof message.endedReason === "string" ? message.endedReason.slice(0, 100) || null : null, caller_phone_number: call.customer?.number ?? null, call_successful: callSuccessful, call_analysis: callAnalysis, call_cost: costInCents(message.cost), metadata: meta, }; // Drop empty optional fields so we only send what we actually have. for (const key of Object.keys(payload)) { if (payload[key] === null || payload[key] === undefined) delete payload[key]; } const params = new URLSearchParams({ workspace_id: String(TUNER_WORKSPACE), agent_remote_identifier: TUNER_AGENT_ID, }); const url = `${TUNER_BASE_URL}/api/v1/public/call?${params}`; const body = JSON.stringify(payload); // POST with retries. Transient failures (network errors, timeouts, 429, // 5xx) get up to 3 attempts with exponential backoff + jitter; other 4xx // are real errors that retrying can't fix, so they fail fast. Retrying is // safe because ingestion is idempotent: a duplicate call_id returns 409, // which counts as success. for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) { let status = 0; let detail = ""; let retryAfterMs = 0; try { const response = await fetch(url, { method: "POST", headers: { Authorization: `Bearer ${TUNER_API_KEY}`, "Content-Type": "application/json", }, body, signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), }); status = response.status; if (status === 200 || status === 201) { console.info(`Tuner: sent call ${callId}${logEnriched ? " (log-enriched)" : ""}`); return; } if (status === 409) { console.info(`Tuner: call ${callId} already sent`); // idempotent, fine return; } detail = await response.text().catch(() => ""); const retryable = status === 408 || status === 429 || status >= 500; if (!retryable) { console.warn(`Tuner: call ${callId} failed (${status}), not retryable: ${detail}`); return; } const ra = Number(response.headers?.get?.("retry-after")); if (Number.isFinite(ra) && ra > 0) retryAfterMs = Math.min(ra * 1000, 30_000); } catch (err) { detail = String(err); // network error / timeout -> retryable } if (attempt < MAX_ATTEMPTS) { const backoffMs = Math.pow(2, attempt) * 1000 + Math.random() * 1000; // ~2-3s, ~4-5s const waitMs = Math.max(backoffMs, retryAfterMs); console.warn( `Tuner: attempt ${attempt}/${MAX_ATTEMPTS} for call ${callId} failed (${status || "network"}), retrying in ${Math.round(waitMs / 1000)}s`, ); await new Promise((resolve) => setTimeout(resolve, waitMs)); } else { console.warn( `Tuner: call ${callId} failed after ${MAX_ATTEMPTS} attempts (${status || "network"}) ${detail}`, ); } } } catch (err) { // never let Tuner break your call handling console.warn("Tuner: error sending call:", err); } } // ============================================================================= // VAPI CALL LOG, internal fetch + log-based enrichment // ============================================================================= /** * Download and parse a VAPI call log (`message.artifact.logUrl`). * * The log is a gzipped JSONL file on VAPI's storage; no API key is needed. * Returns the parsed log lines, or null on any failure (missing URL, timeout, * bad response), the caller then falls back to payload-only enrichment. */ export async function fetchVapiLog(logUrl: unknown): Promise { if (typeof logUrl !== "string" || !logUrl) return null; try { const res = await fetch(logUrl, { signal: AbortSignal.timeout(10_000) }); if (!res.ok) { console.warn( `Tuner: could not fetch VAPI call log (HTTP ${res.status}), continuing without log enrichment`, ); return null; } const buf = new Uint8Array(await res.arrayBuffer()); let text: string; if (buf[0] === 0x1f && buf[1] === 0x8b) { // The log is gzipped, decompress with Node's built-in zlib. const zlib = (await import("node:" + "zlib")) as any; text = zlib.gunzipSync(buf).toString("utf8"); } else { text = new TextDecoder().decode(buf); } const out: Json[] = []; for (const line of text.split("\n")) { const trimmed = line.trim(); if (!trimmed) continue; try { out.push(JSON.parse(trimmed)); } catch { // skip malformed lines } } return out.length ? out : null; } catch (err) { console.warn( `Tuner: could not read VAPI call log (${String(err)}), continuing without log enrichment`, ); return null; } } type LogEvent = { turnId: number; time: number; event: string; latency: number | null; wasInterruption: boolean; }; /** Pull the per-turn events we use out of the raw log lines. */ function normalizeLogEvents(log: VapiLog): LogEvent[] { const lines: Json[] = typeof log === "string" ? log .split("\n") .map((l) => { try { return JSON.parse(l); } catch { return null; } }) .filter((l): l is Json => l !== null) : log; const events: LogEvent[] = []; for (const line of lines) { const a = line?.attributes; if (!a || typeof a !== "object") continue; const rawTurn = a.turnId; // numeric turnIds only; "CLEAN_UP" etc. are not conversation turns if (rawTurn === undefined || rawTurn === null || !/^\d+$/.test(String(rawTurn))) continue; if (typeof line.time !== "number" || typeof a.event !== "string") continue; events.push({ turnId: Number(rawTurn), time: line.time, event: a.event, latency: typeof a.latency === "number" ? a.latency : null, wasInterruption: a.wasInterruption === true, }); } events.sort((x, y) => x.time - y.time); return events; } type LogFragment = { channel: string; turnId: number | null; text: string; time: number; // when the final transcript ARRIVED (ordering) spokenTime: number; // when the speech was HEARD (first partial of the chain) }; /** * Pull the speech snippets out of the log: who said it, which turn, and when * it was actually spoken (taken from the live partial transcripts, which are * more reliable than the final transcript's arrival time). */ function extractFragments(log: VapiLog): LogFragment[] { const lines: Json[] = typeof log === "string" ? log .split("\n") .map((l) => { try { return JSON.parse(l); } catch { return null; } }) .filter((l): l is Json => l !== null) : log; const frags: LogFragment[] = []; const partialStart: Record = { user: null, assistant: null }; for (const line of lines) { const a = line?.attributes; if (!a || typeof a !== "object") continue; const time = typeof line.time === "number" ? line.time : 0; const channel = a.channel === "user" ? "user" : "assistant"; if (a.event === "assistant.transcriber.partialTranscript") { if (partialStart[channel] === null) partialStart[channel] = time; continue; } if (a.event !== "assistant.transcriber.finalTranscript") continue; if (typeof a.transcript !== "string" || !a.transcript) continue; const rawTurn = a.turnId; const turnId = rawTurn != null && /^\d+$/.test(String(rawTurn)) ? Number(rawTurn) : null; frags.push({ channel, turnId, text: a.transcript, time, spokenTime: partialStart[channel] ?? time, }); partialStart[channel] = null; // next partial starts a new chain } frags.sort((x, y) => x.time - y.time); return frags; } /** Lowercase letters and digits only, cosmetic differences can never break matching. */ function normText(s: string): string { return (s ?? "").toLowerCase().replace(/[^a-z0-9]/g, ""); } /** * Match every transcript row to the log snippets that make up its text. * Each VAPI transcript row is the log's speech snippets glued together, so we * re-spell the rows from the snippets, each row then knows exactly which * snippets (and turns/timings) it is made of. If the texts don't line up, * returns null and the simpler enrichment is used instead. */ function alignRowsToFragments( segments: Json[], frags: LogFragment[], ): { fragsOf: Map; covered: Map } | null { const fragsOf = new Map(); const covered = new Map(); for (const [channel, role] of [ ["user", "user"], ["assistant", "agent"], ] as const) { const rows = segments.filter((s) => s.role === role && typeof s.text === "string"); const fItems = frags .filter((f) => f.channel === channel) .map((f) => ({ frag: f, text: normText(f.text) })) .filter((f) => f.text); const rItems = rows.map((r) => ({ row: r, text: normText(r.text) })); const bigR = rItems.map((r) => r.text).join(""); const bigF = fItems.map((f) => f.text).join(""); if (!bigR.startsWith(bigF)) return null; // real divergence -> don't trust the log // Walk both lists; each row consumes fragment characters and collects fragments. let fi = 0; let fOff = 0; for (const { row, text } of rItems) { const own: LogFragment[] = []; let need = text.length; let got = 0; while (need > 0 && fi < fItems.length) { const f = fItems[fi]; const take = Math.min(f.text.length - fOff, need); own.push(f.frag); need -= take; got += take; fOff += take; if (fOff === f.text.length) { fi += 1; fOff = 0; } } fragsOf.set(row, own); covered.set(row, text.length > 0 && got === text.length); } } return { fragsOf, covered }; } /** * Enrich the transcript using VAPI's call log, the most accurate source. * The log tells us exactly which latency numbers belong to which rows, the * true metrics for replies that follow a tool call, and exactly which agent * sentences the customer interrupted. * * Returns true when applied; false means the log couldn't be used and the * simpler payload-based enrichment runs instead. */ function enrichFromLog(segments: Json[], log: VapiLog, turnLatencies: Json[]): boolean { const events = normalizeLogEvents(log); const frags = extractFragments(log); if (!events.length || !frags.length) return false; // Group events by turn; "completed" turns produced agent output (speech or // a tool invocation), these are the turns turnLatencies entries describe. const byTurn = new Map(); for (const e of events) { const list = byTurn.get(e.turnId) ?? []; list.push(e); byTurn.set(e.turnId, list); } const completedTurnIds = [...byTurn.entries()] .sort((a, b) => a[0] - b[0]) .filter(([, evs]) => evs.some((e) => e.event === "pipeline.botSpeechStarted" || e.event === "assistant.tool.started"), ) .map(([tid]) => tid); if (!completedTurnIds.length) return false; // Bind rows to their fragments by text. const aligned = alignRowsToFragments(segments, frags); if (!aligned) return false; const { fragsOf, covered } = aligned; // Figure out which turn produced each piece of agent speech, using WHEN it // was spoken vs when each turn started speaking (the log's own turn labels // can lag behind for interrupted speech, so timing is the reliable signal). const botStarts: { tid: number; time: number }[] = []; for (const tid of completedTurnIds) { for (const e of byTurn.get(tid)!) { if (e.event === "pipeline.botSpeechStarted") botStarts.push({ tid, time: e.time }); } } botStarts.sort((a, b) => a.time - b.time); const producingTurn = (t: number): number | null => { let res: number | null = null; for (const b of botStarts) { if (b.time <= t) res = b.tid; else break; } return res; }; const turnsOf = new Map>(); for (const s of segments) { const own = fragsOf.get(s); if (!own) continue; const turns = new Set(); if (s.role === "agent") { for (const f of own) { const t = producingTurn(f.spokenTime); if (t !== null) turns.add(t); } } else { // User tags are timely: the tag is the turn that started when they spoke. for (const f of own) if (f.turnId !== null) turns.add(f.turnId); } turnsOf.set(s, turns); } // The final goodbye is often cut off before its transcript finalizes, // pair any leftover turns with the remaining unmatched agent rows. const assigned = new Set(); for (const s of segments) { if (s.role !== "agent") continue; for (const t of turnsOf.get(s) ?? []) assigned.add(t); } const leftoverTurns = completedTurnIds.filter((t) => !assigned.has(t)); const uncoveredAgents = segments.filter( (s) => s.role === "agent" && covered.get(s) === false && (turnsOf.get(s)?.size ?? 0) === 0 && normText(s.text).length > 0, // a row with no real words can't claim a turn ); for (let i = 0; i < Math.min(leftoverTurns.length, uncoveredAgents.length); i++) { turnsOf.get(uncoveredAgents[i])?.add(leftoverTurns[i]); } // Build lookups: which agent rows belong to each turn, and when each // customer row started speaking. const rowsOfTurn = new Map(); const userRows: { row: Json; minTurn: number; spoken: number }[] = []; const rowSpoken = new Map(); for (const s of segments) { const own = fragsOf.get(s); if (own?.length) rowSpoken.set(s, own[0].spokenTime); const turns = turnsOf.get(s); if (!turns || !turns.size) continue; if (s.role === "agent") { for (const t of turns) { const list = rowsOfTurn.get(t) ?? []; list.push(s); rowsOfTurn.set(t, list); } } else if (s.role === "user") { userRows.push({ row: s, minTurn: Math.min(...turns), spoken: rowSpoken.get(s) ?? 0 }); } } // When each turn first produced output, the customer speech that triggered // a turn must have started before this moment. const turnFirstOut = new Map(); for (const tid of completedTurnIds) { for (const e of byTurn.get(tid)!) { if (e.event === "pipeline.botSpeechStarted" || e.event === "assistant.tool.started") { turnFirstOut.set(tid, Math.min(turnFirstOut.get(tid) ?? Infinity, e.time)); } } } // Attach VAPI's latency numbers: entry #i describes completed turn #i. for (let i = 0; i < completedTurnIds.length; i++) { const T = completedTurnIds[i]; const tl: Json | undefined = turnLatencies[i]; const evs = byTurn.get(T)!; const speechRows = rowsOfTurn.get(T) ?? []; // STT goes to the customer row that triggered this turn. If one customer // row triggered several measured exchanges, keep the largest value, the // worst transcription delay that speech experienced. if (tl?.transcriberLatency != null) { const firstOut = turnFirstOut.get(T) ?? Infinity; const trigger = [...userRows] .reverse() .find((u) => u.minTurn <= T && u.spoken < firstOut)?.row; if (trigger) { const prev = trigger.metadata?.stt_node_ttfb; if (prev === undefined || tl.transcriberLatency > prev) { trigger.metadata = { ...(trigger.metadata ?? {}), stt_node_ttfb: tl.transcriberLatency }; } } } // Latency/LLM/TTS go to the turn's first spoken reply. if (speechRows[0] && tl && speechRows[0].metadata?.e2e_latency === undefined) { const md: Json = {}; if (tl.turnLatency != null) md.e2e_latency = tl.turnLatency; if (tl.modelLatency != null) md.llm_node_ttft = tl.modelLatency; if (tl.voiceLatency != null) md.tts_node_ttfb = tl.voiceLatency; if (Object.keys(md).length) speechRows[0].metadata = { ...(speechRows[0].metadata ?? {}), ...md }; } // Replies spoken after a tool finished get their own metrics from the log. const runs = evs.filter((e) => e.event === "pipeline.botSpeechStarted"); for (let k = 1; k < Math.min(speechRows.length, runs.length); k++) { if (speechRows[k].metadata?.e2e_latency !== undefined) continue; const runStart = runs[k].time; const lastBefore = (name: string) => [...evs].reverse().find((e) => e.event === name && e.time < runStart); const llm = lastBefore("assistant.model.firstTokenReceived"); const tts = lastBefore("assistant.voice.firstAudioReceived"); const tool = lastBefore("assistant.tool.completed"); const md: Json = {}; if (tool) md.e2e_latency = runStart - tool.time; // wait after the tool returned if (llm?.latency != null) md.llm_node_ttft = llm.latency; if (tts?.latency != null) md.tts_node_ttfb = tts.latency; if (Object.keys(md).length) speechRows[k].metadata = { ...(speechRows[k].metadata ?? {}), ...md }; } } // Interruptions: the log marks every barge-in the assistant reacted to. // We find which stretch of agent speech the cut landed inside and flag that // row. Barge-ins that happened before the agent even spoke have no row to // flag, so they are skipped. // Time spans when the agent was actually speaking, and which turn each span belongs to. const intervals: { tid: number; start: number; end: number }[] = []; let open: { tid: number; start: number } | null = null; for (const e of events) { if (e.event === "pipeline.botSpeechStarted") { if (open) intervals.push({ ...open, end: e.time }); open = { tid: e.turnId, start: e.time }; } else if (e.event === "pipeline.botSpeechStopped" && open) { intervals.push({ ...open, end: e.time }); open = null; } } if (open) intervals.push({ ...open, end: Infinity }); for (const e of events) { if (e.event !== "pipeline.cleared" || !e.wasInterruption) continue; // Match the LATEST interval containing the cut (with a little slack for // event-ordering jitter), when two speech runs are back to back, the cut // belongs to the one that was actually playing. let hit: { tid: number; start: number; end: number } | null = null; for (const iv of intervals) { if (iv.start <= e.time && e.time <= iv.end + 100) hit = iv; } if (!hit) continue; // pre-speech cancellation: nothing was said, nothing to flag const rows = rowsOfTurn.get(hit.tid) ?? []; if (!rows.length) continue; // The cut row: among the turn's rows belonging to this speech run (spoken // after the run started, with slack for transcriber lag), the last one // already being spoken at the cut. const inRun = rows.filter((r) => (rowSpoken.get(r) ?? 0) >= hit.start - 1000); const pool = inRun.length ? inRun : rows; const spoken = pool.filter((r) => (rowSpoken.get(r) ?? 0) <= e.time + 100); const row = spoken[spoken.length - 1] ?? pool[0]; row.metadata = { ...(row.metadata ?? {}), interrupted: true }; } // VAPI sometimes splits one continuous agent sentence into two rows (when // the customer says something brief mid-sentence). The second piece has no // measurements of its own, so it would look like an empty row, re-join it // with its first half. Only provable same-turn pieces with no metrics of // their own are merged; everything else is left untouched. for (let i = segments.length - 1; i > 0; i--) { const r = segments[i]; if (r.role !== "agent") continue; const md = r.metadata ?? {}; if (md.e2e_latency !== undefined || md.llm_node_ttft !== undefined || md.tts_node_ttfb !== undefined) { continue; // has its own measurement -> a real, separate utterance } const rTurns = turnsOf.get(r); if (!rTurns || !rTurns.size) continue; // unbound -> not provably a slice let pi = i - 1; while (pi >= 0 && segments[pi].role !== "agent") pi--; if (pi < 0) continue; const p = segments[pi]; const pTurns = turnsOf.get(p); if (!pTurns || ![...rTurns].every((t) => pTurns.has(t))) continue; // different turn if (md.interrupted && p.metadata?.interrupted) continue; // two distinct cuts -> keep both visible p.text = `${p.text ?? ""} ${r.text ?? ""}`.trim(); const rEnd = typeof r.end_ms === "number" ? r.end_ms : typeof r.start_ms === "number" && typeof r.duration_ms === "number" ? r.start_ms + r.duration_ms : null; if (rEnd !== null) { p.end_ms = typeof p.end_ms === "number" ? Math.max(p.end_ms, rEnd) : rEnd; } if (typeof p.start_ms === "number" && typeof p.end_ms === "number") { p.duration_ms = p.end_ms - p.start_ms; } if (Array.isArray(r.words) && r.words.length) p.words = [...(p.words ?? []), ...r.words]; if (md.interrupted) p.metadata = { ...(p.metadata ?? {}), interrupted: true }; segments.splice(i, 1); } return true; } /** * Re-join customer sentences that VAPI split into two rows mid-sentence. * Merged only when clearly one utterance: the rows are back to back with * essentially no pause, and at most one of them carries an STT value * (two measured rows are two real utterances and stay separate). */ function mergeUserSlices(segments: Json[]): void { for (let i = segments.length - 1; i > 0; i--) { const r = segments[i]; const p = segments[i - 1]; if (r.role !== "user" || p.role !== "user") continue; const gap = typeof r.start_ms === "number" && typeof p.end_ms === "number" ? r.start_ms - p.end_ms : Infinity; if (Math.abs(gap) > 1000) continue; // not a slice boundary const rStt = r.metadata?.stt_node_ttfb; const pStt = p.metadata?.stt_node_ttfb; if (rStt !== undefined && pStt !== undefined) continue; // two measured utterances p.text = `${p.text ?? ""} ${r.text ?? ""}`.trim(); const rEnd = typeof r.end_ms === "number" ? r.end_ms : typeof r.start_ms === "number" && typeof r.duration_ms === "number" ? r.start_ms + r.duration_ms : null; if (rEnd !== null) { p.end_ms = typeof p.end_ms === "number" ? Math.max(p.end_ms, rEnd) : rEnd; } if (typeof p.start_ms === "number" && typeof p.end_ms === "number") { p.duration_ms = p.end_ms - p.start_ms; } if (Array.isArray(r.words) && r.words.length) p.words = [...(p.words ?? []), ...r.words]; if (rStt !== undefined && pStt === undefined) { p.metadata = { ...(p.metadata ?? {}), stt_node_ttfb: rStt }; } if (r.metadata?.interrupted) p.metadata = { ...(p.metadata ?? {}), interrupted: true }; segments.splice(i, 1); } } // ============================================================================= // CALL-LEVEL MAPPING, mirrors how Tuner maps VAPI calls natively. // ============================================================================= // VAPI call types -> Tuner's canonical snake_case values; unknown types pass through. const VAPI_CALL_TYPE_MAP: Record = { webCall: "web_call", phoneCall: "phone_call", sipCall: "sip_call", }; /** Normalize VAPI's camelCase call type to Tuner's snake_case. */ function mapCallType(vapiType: string | undefined | null): string { if (!vapiType) return "phone_call"; return VAPI_CALL_TYPE_MAP[vapiType] ?? vapiType; } /** Build Tuner's call_analysis ({summary, success_evaluation}) and call_successful. */ function mapAnalysis(message: Json): { callAnalysis: Json | null; callSuccessful: boolean | null } { const callAnalysis: Json = {}; let callSuccessful: boolean | null = null; const analysis: Json = message.analysis ?? {}; if (analysis.summary) { callAnalysis.summary = analysis.summary; } const successEval = analysis.successEvaluation; if (successEval !== undefined && successEval !== null) { callAnalysis.success_evaluation = successEval; callSuccessful = String(successEval).toLowerCase() === "true"; } // Fall back to the top-level summary if analysis didn't carry one. if (message.summary && !("summary" in callAnalysis)) { callAnalysis.summary = message.summary; } return { callAnalysis: Object.keys(callAnalysis).length ? callAnalysis : null, callSuccessful, }; } /** VAPI reports cost in dollars; Tuner expects cents. */ function costInCents(cost: unknown): number | null { if (typeof cost !== "number" || Number.isNaN(cost)) return null; return Math.round(cost * 100 * 100) / 100; // round to 2 decimals } /** Drop null/undefined values recursively so segments only carry fields that exist. */ function stripNull(obj: T): T { if (Array.isArray(obj)) { return obj.map(stripNull) as T; } if (obj !== null && typeof obj === "object") { const out: Json = {}; for (const [k, v] of Object.entries(obj)) { if (v !== null && v !== undefined) out[k] = stripNull(v); } return out as T; } return obj; } // ============================================================================= // MAPPING, VAPI messages -> Tuner's transcript timeline. // Mirrors Tuner's internal VAPI mapper so user/agent speech, tool calls, and // tool results are all captured. VAPI roles map to Tuner roles like so: // user -> user bot -> agent // tool_calls -> agent_function tool_call_result -> agent_result // system -> dropped // ============================================================================= function buildSegments(rawMessages: Json[], callStartMs: number | null): Json[] { const segments: Json[] = []; for (const m of rawMessages) { if (typeof m !== "object" || m === null) continue; const role = m.role; if (role === "user") { const seg = speechSegment(m, "user", callStartMs); if (seg) segments.push(seg); } else if (role === "bot" || role === "assistant") { const seg = speechSegment(m, "agent", callStartMs); if (seg) segments.push(seg); } else if (role === "tool_calls") { segments.push(...toolCallSegments(m)); } else if (role === "tool_call_result") { segments.push(toolResultSegment(m)); } // "system" and anything else is intentionally skipped. } return segments; } /** * A spoken row (customer or agent) with its timing. Tuner requires timing on * every spoken row, so a rare row with no usable timing is skipped rather * than rejecting the whole call. */ function speechSegment(m: Json, role: string, callStartMs: number | null): Json | null { const { startMs, endMs, durationMs } = segmentTiming(m, callStartMs); const segWords = words(m.metadata, callStartMs); const hasTiming = startMs !== null && (endMs !== null || durationMs !== null); if (!hasTiming && !segWords) { console.warn(`Tuner: skipping untimed ${role} segment: ${String(m.message ?? "").slice(0, 50)}`); return null; } const seg: Json = { role, text: m.message }; if (startMs !== null) seg.start_ms = startMs; if (endMs !== null) seg.end_ms = endMs; if (durationMs !== null) seg.duration_ms = durationMs; if (segWords) seg.words = segWords; return seg; } /** One agent_function segment per tool the agent invoked. */ function toolCallSegments(m: Json): Json[] { const seconds = m.secondsFromStart; const startMs = seconds !== undefined && seconds !== null ? Math.ceil(seconds * 1000) : null; const out: Json[] = []; for (const tc of m.toolCalls ?? []) { if (tc == null || typeof tc !== "object") continue; const fn: Json = tc.function ?? {}; const params = maybeJson(fn.arguments); out.push({ role: "agent_function", start_ms: startMs, end_ms: startMs, tool: { name: fn.name, request_id: tc.id, params: typeof params === "object" && params !== null && !Array.isArray(params) ? params : null, start_ms: startMs, end_ms: startMs, }, }); } return out; } /** The result returned by a tool. Non-object results are wrapped so nothing is lost. */ function toolResultSegment(m: Json): Json { const seconds = m.secondsFromStart; const startMs = seconds !== undefined && seconds !== null ? Math.ceil(seconds * 1000) : null; const parsed = maybeJson(m.result); let result: Json | null; if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) { result = parsed; } else if ((Array.isArray(parsed) && parsed.length) || (typeof parsed === "string" && parsed)) { result = { value: parsed }; } else { result = null; } const { isError, errorMsg } = detectToolError(m, parsed); const tool: Json = { name: m.name, request_id: m.toolCallId, result, is_error: isError, start_ms: startMs, end_ms: startMs, }; if (errorMsg) tool.error = errorMsg; return { role: "agent_result", start_ms: startMs, end_ms: startMs, tool }; } /** * Detect whether a tool result was an error and extract its message. VAPI has * no single standard error flag, so the common explicit signals are checked. */ function detectToolError(m: Json, parsed: unknown): { isError: boolean; errorMsg: string | null } { // 1. Explicit flags on the VAPI message (extra fields are allowed by VAPI). const msgError = m.error; if (typeof msgError === "string" && msgError) { return { isError: true, errorMsg: msgError }; } if (m.error === true || m.isError === true || m.is_error === true) { return { isError: true, errorMsg: typeof msgError === "string" ? msgError : null }; } if (m.success === false) { return { isError: true, errorMsg: null }; } // 2. Error-shaped result payload, e.g. {"error": "..."} or {"status": "failed"}. if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) { const p = parsed as Json; if (p.error) { return { isError: true, errorMsg: typeof p.error === "string" ? p.error : null }; } if (p.success === false) { return { isError: true, errorMsg: null }; } const status = p.status; if (typeof status === "string" && ["error", "failed", "failure"].includes(status.toLowerCase())) { return { isError: true, errorMsg: typeof p.message === "string" ? p.message : null }; } } return { isError: false, errorMsg: null }; } // ============================================================================= // TURN GROUPING + LATENCY ATTACHMENT (payload-only path) // ============================================================================= type Turn = { trigger: Json | null; rows: Json[]; hasSpeech: boolean }; /** * Group transcript rows into conversation turns: each customer message starts * a new turn, and everything the agent does until the next customer message * (speech, tool calls, tool results) belongs to that turn. The opening * greeting, spoken before any customer speech, has no trigger. */ function groupIntoTurns(segments: Json[]): Turn[] { const turns: Turn[] = []; let cur: Turn = { trigger: null, rows: [], hasSpeech: false }; const flush = () => { if (cur.rows.length) turns.push(cur); }; for (const seg of segments) { if (seg.role === "user") { flush(); cur = { trigger: seg, rows: [], hasSpeech: false }; } else if (seg.role === "agent") { cur.rows.push(seg); cur.hasSpeech = true; } else if (seg.role === "agent_function" && cur.hasSpeech) { flush(); cur = { trigger: cur.trigger, rows: [seg], hasSpeech: false }; } else { cur.rows.push(seg); // agent_result, or a tool call opening the turn } } flush(); return turns; } /** * Attach VAPI's latency numbers without the call log (fallback path). * VAPI reports one latency entry per agent response: STT goes to the customer * row that triggered it, and latency/LLM/TTS go to the agent's reply. The * opening greeting has no entry. Zeros are real values and are kept. */ function enrichWithTurnLatencies(segments: Json[], turnLatencies: Json[]): void { // Agent speech before any customer speech (the greeting) never gets an entry. const eligible = groupIntoTurns(segments).filter((t) => t.trigger !== null); const count = Math.min(eligible.length, turnLatencies.length); for (let i = 0; i < count; i++) { const turn = eligible[i]; const tl = turnLatencies[i]; const trigger = turn.trigger!; if (tl.transcriberLatency != null) { const prev = trigger.metadata?.stt_node_ttfb; if (prev === undefined || tl.transcriberLatency > prev) { trigger.metadata = { ...(trigger.metadata ?? {}), stt_node_ttfb: tl.transcriberLatency }; } } const speech = turn.rows.find((r) => r.role === "agent"); if (!speech) continue; // e.g. an endCall turn with no spoken reply const metadata: Json = {}; if (tl.turnLatency != null) metadata.e2e_latency = tl.turnLatency; if (tl.modelLatency != null) metadata.llm_node_ttft = tl.modelLatency; if (tl.voiceLatency != null) metadata.tts_node_ttfb = tl.voiceLatency; if (Object.keys(metadata).length) speech.metadata = { ...(speech.metadata ?? {}), ...metadata }; } } // A customer turn must start at least this many ms before the agent's turn ends // to count as a barge-in (filters out word-boundary noise and short backchannels). const INTERRUPTION_THRESHOLD_MS = 200; /** * Flag agent rows the customer talked over (fallback path, no call log). * If a customer message starts clearly before the previous agent message * ended, that agent message was interrupted. The log-based path detects * interruptions more completely; this is the best the payload alone allows. */ function markInterruptions(segments: Json[]): void { let lastAgentSeg: Json | null = null; for (const seg of segments) { if (seg.role === "agent") { lastAgentSeg = seg; } else if (seg.role === "user") { if ( lastAgentSeg && lastAgentSeg.end_ms != null && seg.start_ms != null && seg.start_ms < lastAgentSeg.end_ms - INTERRUPTION_THRESHOLD_MS ) { lastAgentSeg.metadata = { ...(lastAgentSeg.metadata ?? {}), interrupted: true }; } lastAgentSeg = null; // each customer turn compares against a fresh agent turn } // tool segments: ignore, keep the current agent turn as the candidate } } // ============================================================================= // TIMING HELPERS // ============================================================================= /** Work out a row's start/end/duration relative to the start of the call. */ function segmentTiming( m: Json, callStartMs: number | null, ): { startMs: number | null; endMs: number | null; durationMs: number | null } { let startMs: number | null = null; let endMs: number | null = null; let durationMs: number | null = null; const seconds = m.secondsFromStart; if (seconds !== undefined && seconds !== null) { startMs = Math.ceil(seconds * 1000); } if (m.duration !== undefined && m.duration !== null) { durationMs = Math.ceil(m.duration); } if (startMs !== null && durationMs !== null) { endMs = startMs + durationMs; } else if (callStartMs !== null) { if (m.time !== undefined && m.time !== null && startMs === null) { startMs = Math.ceil(m.time - callStartMs); } if (m.endTime !== undefined && m.endTime !== null) { endMs = Math.ceil(m.endTime - callStartMs); } if (startMs !== null && endMs !== null) { durationMs = endMs - startMs; } } return { startMs, endMs, durationMs }; } /** * Word-level timing from VAPI. VAPI has used different time units for word * timestamps over time, so the unit is detected from the value itself. */ function words(metadata: unknown, callStartMs: number | null): Json[] | null { if (typeof metadata !== "object" || metadata === null) return null; const raw = (metadata as Json).wordLevelConfidence; if (!Array.isArray(raw) || raw.length === 0) return null; const toRelMs = (v: number): number => { if (v > 1e11) return Math.ceil(v - (callStartMs ?? 0)); // epoch ms if (v < 1e5) return Math.ceil(v * 1000); // seconds from call start return Math.ceil(v); // already ms from call start }; const out: Json[] = []; for (const w of raw) { if (typeof w !== "object" || w === null || !w.word || typeof w.start !== "number" || typeof w.end !== "number") { continue; } out.push({ word: w.word, start_ms: toRelMs(w.start), end_ms: toRelMs(w.end), confidence: w.confidence ?? null, }); } return out.length ? out : null; } /** VAPI sends tool arguments/results as JSON strings; parse them, else pass through. */ function maybeJson(value: unknown): unknown { if (typeof value !== "string") return value; try { return JSON.parse(value); } catch { return value; } } /** Accept VAPI's ISO string ('2026-06-10T...Z') or a number; return epoch ms. */ function toEpochMs(value: unknown): number | null { if (value === undefined || value === null) return null; if (typeof value === "number") return Math.trunc(value); const ms = Date.parse(String(value)); return Number.isNaN(ms) ? null : ms; } ``` ```python Python [expandable] theme={null} """ Send your VAPI calls to Tuner ============================== Drop this file next to your VAPI server and call ``send_call_to_tuner(message)`` from inside your ``end-of-call-report`` handler, that's the whole integration:: send_call_to_tuner(message) # fire-and-forget; never raises # optional: attach your own metadata object to the call in Tuner send_call_to_tuner(message, {"customer_id": "cus_123", "campaign": "june-promo"}) Every finished call, including its tool calls and tool results, will show up under your Tuner agent. The function automatically downloads VAPI's call log (``artifact.logUrl``, one extra GET, no API key needed) to enrich the call with exact per-turn latencies and interruptions. If the log is missing or unreadable, it falls back to payload-only enrichment by itself, the transcript never depends on the log, and a call is never lost because of it. Because this is synchronous and may sleep between retries, call it from a background thread/task in latency-sensitive handlers, e.g.:: import threading threading.Thread(target=send_call_to_tuner, args=(message,), daemon=True).start() Setup (4 values, all from the Tuner dashboard): 1. TUNER_BASE_URL -> your Tuner API base URL 2. TUNER_API_KEY -> API Keys page (starts with "tr_api_") 3. TUNER_WORKSPACE -> Workspace Settings > General Settings > Workspace ID 4. TUNER_AGENT_ID -> create a "My own stack" agent in Tuner, then Agent Settings > Agent Setup > Agent Remote ID Install: pip install requests """ from __future__ import annotations import gzip import logging import math import random import re import time from datetime import datetime, timezone from typing import Any, Optional, Union from urllib.parse import urlencode import requests logger = logging.getLogger("tuner") # ============================================================================= # CONFIG, fill these in # ============================================================================= TUNER_BASE_URL = "https://api.usetuner.ai" # your Tuner API base URL TUNER_API_KEY = "tr_api_xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" TUNER_WORKSPACE = 0 # your workspace id (number) TUNER_AGENT_ID = "your-custom-api-agent-id" # Network timeout & retry behavior for the POST to Tuner. REQUEST_TIMEOUT_S = 15 # per-attempt timeout for the POST to Tuner MAX_ATTEMPTS = 3 # retry attempts on transient failures (network, 408, 429, 5xx) Json = dict[str, Any] # VapiLog: raw JSONL text, or a list of parsed log-line objects. VapiLog = Union[str, list[Json]] # Sentinel meaning "prefetched_log was not passed" (None means "no log, skip fetch"). _MISSING = object() # ============================================================================= # THE FUNCTION, call this from your end-of-call handler # ============================================================================= def send_call_to_tuner( message: Json, metadata: Optional[Json] = None, prefetched_log: Any = _MISSING, # sentinel "not provided"; None == "no log" ) -> None: """ Forward one VAPI ``end-of-call-report`` message to Tuner. ``message`` is the ``body.message`` object VAPI posts to your webhook. ``metadata`` (optional) is a free-form object stored with the call in Tuner (e.g. your own customer id, campaign, A/B variant). Sent only when you provide it; nothing is sent by default. The VAPI call log is fetched internally from ``artifact.logUrl``; when that fails, the payload-only enrichment runs instead, fully automatic. Pass ``prefetched_log`` when you already downloaded the log (e.g. to save it locally) so it isn't fetched twice. Safe to call inline, it never raises; failures are logged, not raised. """ try: call: Json = message.get("call") or {} artifact: Json = message.get("artifact") or {} call_id = call.get("id") if not call_id: logger.warning("Tuner: end-of-call-report has no call id, call will not be sent") return # VAPI keeps the timed, structured transcript under artifact.messages. raw_messages: list = artifact.get("messages") or message.get("messages") or [] call_start_ms = _to_epoch_ms(message.get("startedAt")) segments = _build_segments(raw_messages, call_start_ms) if not segments: logger.warning(f"Tuner: no transcript segments found, call {call_id} will not be sent") return # Fetch VAPI's call log (one GET, no auth). None on any failure -> fallback. if prefetched_log is not _MISSING: log = prefetched_log else: log = fetch_vapi_log(artifact.get("logUrl") or message.get("logUrl")) # Attach per-turn latency: STT to the customer turn, LLM/TTS/e2e to the agent reply. # With a call log: exact interruptions + real metrics on post-tool replies. # Without (or if the log doesn't line up): the verified payload-only logic. turn_latencies: list = ((artifact.get("performanceMetrics") or {}).get("turnLatencies")) or [] log_enriched = False if log: try: log_enriched = _enrich_from_log(segments, log, turn_latencies) except Exception as err: # noqa: BLE001 log_enriched = False logger.warning( f"Tuner: log enrichment failed for call {call_id} ({err!r}), " "using payload-only metrics" ) if not log_enriched: if turn_latencies: _enrich_with_turn_latencies(segments, turn_latencies) # Without log ground truth, deduce barge-ins from timing overlap. _mark_interruptions(segments) # Re-join customer utterances that VAPI's stitcher sliced into two rows. _merge_user_slices(segments) segments = [_strip_none(s) for s in segments] stereo_url = message.get("stereoRecordingUrl") or artifact.get("stereoRecordingUrl") recording_url = message.get("recordingUrl") or artifact.get("recordingUrl") or stereo_url if not recording_url: logger.warning(f"Tuner: no recording URL, call {call_id} will not be sent to Tuner") return # Metadata is sent only when the caller provides it; Tuner accepts # free-form keys here and stores them with the call. It must be JSON- # serializable, anything else is dropped so the call itself still sends. meta: Optional[Json] = ( metadata if isinstance(metadata, dict) and len(metadata) else None ) if meta is not None: try: import json json.dumps(meta) except (TypeError, ValueError): logger.warning( f"Tuner: metadata for call {call_id} is not JSON-serializable, sending without it" ) meta = None call_analysis, call_successful = _map_analysis(message) # sip_call_id: the SIP Call-ID of the leg that reached VAPI, exposed by # VAPI as the "cid" variable (and as sbcCallSid). Tuner stores this same # id for its simulation calls, so it links the call back to a simulation # run. The correlation-id override variable is a last resort; nulls are # dropped below, so regular calls are unaffected. overrides_vars = (call.get("assistantOverrides") or {}).get("variableValues") or {} correlation_id = ( overrides_vars.get("cid") or (call.get("transport") or {}).get("sbcCallSid") or (call.get("phoneCallProviderDetails") or {}).get("sbcCallId") or overrides_vars.get("correlation-id") or None ) # recipient: the call's destination address. customer = call.get("customer") or {} recipient = customer.get("sipUri") or customer.get("number") or None payload: Json = { "call_id": call_id, "sip_call_id": correlation_id, "recipient": recipient, "call_type": _map_call_type(call.get("type")), "start_timestamp": call_start_ms, "end_timestamp": _to_epoch_ms(message.get("endedAt")), "recording_url": recording_url, "recording_multi_channel_url": stereo_url, "transcript": message.get("transcript") or artifact.get("transcript") or None, "transcript_with_tool_calls": segments, "call_status": "call_ended", "disconnection_reason": ( (message["endedReason"][:100] or None) if isinstance(message.get("endedReason"), str) else None ), "caller_phone_number": customer.get("number") or None, "call_successful": call_successful, "call_analysis": call_analysis, "call_cost": _cost_in_cents(message.get("cost")), "metadata": meta, } # Drop empty optional fields so we only send what we actually have. payload = {k: v for k, v in payload.items() if v is not None} params = urlencode( { "workspace_id": str(TUNER_WORKSPACE), "agent_remote_identifier": TUNER_AGENT_ID, } ) url = f"{TUNER_BASE_URL}/api/v1/public/call?{params}" headers = { "Authorization": f"Bearer {TUNER_API_KEY}", "Content-Type": "application/json", } # POST with retries. Transient failures (network errors, timeouts, 429, # 5xx) get up to 3 attempts with exponential backoff + jitter; other 4xx # are real errors that retrying can't fix, so they fail fast. Retrying is # safe because ingestion is idempotent: a duplicate call_id returns 409, # which counts as success. for attempt in range(1, MAX_ATTEMPTS + 1): status = 0 detail = "" retry_after_ms = 0 try: response = requests.post( url, headers=headers, json=payload, timeout=REQUEST_TIMEOUT_S ) status = response.status_code if status in (200, 201): logger.info( f"Tuner: sent call {call_id}" + (" (log-enriched)" if log_enriched else "") ) return if status == 409: logger.info(f"Tuner: call {call_id} already sent") # idempotent, fine return detail = response.text or "" retryable = status == 408 or status == 429 or status >= 500 if not retryable: logger.warning( f"Tuner: call {call_id} failed ({status}), not retryable: {detail}" ) return try: ra = float(response.headers.get("retry-after", "")) if math.isfinite(ra) and ra > 0: retry_after_ms = min(ra * 1000, 30_000) except (TypeError, ValueError): pass except requests.RequestException as err: detail = str(err) # network error / timeout -> retryable if attempt < MAX_ATTEMPTS: backoff_ms = (2 ** attempt) * 1000 + random.random() * 1000 # ~2-3s, ~4-5s wait_ms = max(backoff_ms, retry_after_ms) logger.warning( f"Tuner: attempt {attempt}/{MAX_ATTEMPTS} for call {call_id} failed " f"({status or 'network'}), retrying in {round(wait_ms / 1000)}s" ) time.sleep(wait_ms / 1000) else: logger.warning( f"Tuner: call {call_id} failed after {MAX_ATTEMPTS} attempts " f"({status or 'network'}) {detail}" ) except Exception as err: # noqa: BLE001 # never let Tuner break your call handling logger.warning(f"Tuner: error sending call: {err!r}") # ============================================================================= # VAPI CALL LOG, internal fetch + log-based enrichment # ============================================================================= def fetch_vapi_log(log_url: Any) -> Optional[list[Json]]: """ Download and parse a VAPI call log (``message.artifact.logUrl``). The log is a gzipped JSONL file on VAPI's storage; no API key is needed. Returns the parsed log lines, or None on any failure (missing URL, timeout, bad response), the caller then falls back to payload-only enrichment. """ if not isinstance(log_url, str) or not log_url: return None try: res = requests.get(log_url, timeout=10) if not res.ok: logger.warning( f"Tuner: could not fetch VAPI call log (HTTP {res.status_code}), " "continuing without log enrichment" ) return None buf = res.content if len(buf) >= 2 and buf[0] == 0x1F and buf[1] == 0x8B: # The log is gzipped, decompress with the stdlib. text = gzip.decompress(buf).decode("utf-8") else: text = buf.decode("utf-8", errors="replace") import json out: list[Json] = [] for line in text.split("\n"): trimmed = line.strip() if not trimmed: continue try: out.append(json.loads(trimmed)) except ValueError: # skip malformed lines pass return out or None except Exception as err: # noqa: BLE001 logger.warning( f"Tuner: could not read VAPI call log ({err!r}), continuing without log enrichment" ) return None def _parse_log_lines(log: VapiLog) -> list[Json]: """Accept raw JSONL text or an already-parsed list; return parsed log lines.""" if not isinstance(log, str): return log import json lines: list[Json] = [] for line in log.split("\n"): try: lines.append(json.loads(line)) except ValueError: continue return [line for line in lines if line is not None] def _normalize_log_events(log: VapiLog) -> list[dict]: """Pull the per-turn events we use out of the raw log lines.""" lines = _parse_log_lines(log) events: list[dict] = [] for line in lines: a = (line or {}).get("attributes") if not isinstance(a, dict): continue raw_turn = a.get("turnId") # numeric turnIds only; "CLEAN_UP" etc. are not conversation turns if raw_turn is None or not re.fullmatch(r"\d+", str(raw_turn)): continue if not isinstance(line.get("time"), (int, float)) or not isinstance(a.get("event"), str): continue events.append( { "turnId": int(raw_turn), "time": line["time"], "event": a["event"], "latency": a["latency"] if isinstance(a.get("latency"), (int, float)) else None, "wasInterruption": a.get("wasInterruption") is True, } ) events.sort(key=lambda x: x["time"]) return events def _extract_fragments(log: VapiLog) -> list[dict]: """ Pull the speech snippets out of the log: who said it, which turn, and when it was actually spoken (taken from the live partial transcripts, which are more reliable than the final transcript's arrival time). """ lines = _parse_log_lines(log) frags: list[dict] = [] partial_start: dict[str, Optional[float]] = {"user": None, "assistant": None} for line in lines: a = (line or {}).get("attributes") if not isinstance(a, dict): continue time_val = line["time"] if isinstance(line.get("time"), (int, float)) else 0 channel = "user" if a.get("channel") == "user" else "assistant" if a.get("event") == "assistant.transcriber.partialTranscript": if partial_start[channel] is None: partial_start[channel] = time_val continue if a.get("event") != "assistant.transcriber.finalTranscript": continue if not isinstance(a.get("transcript"), str) or not a["transcript"]: continue raw_turn = a.get("turnId") turn_id = int(raw_turn) if raw_turn is not None and re.fullmatch(r"\d+", str(raw_turn)) else None frags.append( { "channel": channel, "turnId": turn_id, "text": a["transcript"], "time": time_val, "spokenTime": partial_start[channel] if partial_start[channel] is not None else time_val, } ) partial_start[channel] = None # next partial starts a new chain frags.sort(key=lambda x: x["time"]) return frags def _norm_text(s: Optional[str]) -> str: """Lowercase letters and digits only, cosmetic differences can never break matching.""" return re.sub(r"[^a-z0-9]", "", (s or "").lower()) def _align_rows_to_fragments(segments: list[Json], frags: list[dict]): """ Match every transcript row to the log snippets that make up its text. Each VAPI transcript row is the log's speech snippets glued together, so we re-spell the rows from the snippets, each row then knows exactly which snippets (and turns/timings) it is made of. If the texts don't line up, returns None and the simpler enrichment is used instead. Returns ``(frags_of, covered)`` where both are keyed by ``id(row)``. """ frags_of: dict[int, list[dict]] = {} covered: dict[int, bool] = {} for channel, role in (("user", "user"), ("assistant", "agent")): rows = [s for s in segments if s.get("role") == role and isinstance(s.get("text"), str)] f_items = [ {"frag": f, "text": _norm_text(f["text"])} for f in frags if f["channel"] == channel ] f_items = [f for f in f_items if f["text"]] r_items = [{"row": r, "text": _norm_text(r["text"])} for r in rows] big_r = "".join(r["text"] for r in r_items) big_f = "".join(f["text"] for f in f_items) if not big_r.startswith(big_f): return None # real divergence -> don't trust the log # Walk both lists; each row consumes fragment characters and collects fragments. fi = 0 f_off = 0 for item in r_items: row = item["row"] text = item["text"] own: list[dict] = [] need = len(text) got = 0 while need > 0 and fi < len(f_items): f = f_items[fi] take = min(len(f["text"]) - f_off, need) own.append(f["frag"]) need -= take got += take f_off += take if f_off == len(f["text"]): fi += 1 f_off = 0 frags_of[id(row)] = own covered[id(row)] = len(text) > 0 and got == len(text) return frags_of, covered def _enrich_from_log(segments: list[Json], log: VapiLog, turn_latencies: list) -> bool: """ Enrich the transcript using VAPI's call log, the most accurate source. The log tells us exactly which latency numbers belong to which rows, the true metrics for replies that follow a tool call, and exactly which agent sentences the customer interrupted. Returns True when applied; False means the log couldn't be used and the simpler payload-based enrichment runs instead. """ events = _normalize_log_events(log) frags = _extract_fragments(log) if not events or not frags: return False # Group events by turn; "completed" turns produced agent output (speech or # a tool invocation), these are the turns turnLatencies entries describe. by_turn: dict[int, list[dict]] = {} for e in events: by_turn.setdefault(e["turnId"], []).append(e) completed_turn_ids = [ tid for tid, evs in sorted(by_turn.items(), key=lambda kv: kv[0]) if any( e["event"] in ("pipeline.botSpeechStarted", "assistant.tool.started") for e in evs ) ] if not completed_turn_ids: return False # Bind rows to their fragments by text. aligned = _align_rows_to_fragments(segments, frags) if aligned is None: return False frags_of, covered = aligned # Figure out which turn produced each piece of agent speech, using WHEN it # was spoken vs when each turn started speaking (the log's own turn labels # can lag behind for interrupted speech, so timing is the reliable signal). bot_starts: list[dict] = [] for tid in completed_turn_ids: for e in by_turn[tid]: if e["event"] == "pipeline.botSpeechStarted": bot_starts.append({"tid": tid, "time": e["time"]}) bot_starts.sort(key=lambda b: b["time"]) def producing_turn(t: float) -> Optional[int]: res: Optional[int] = None for b in bot_starts: if b["time"] <= t: res = b["tid"] else: break return res turns_of: dict[int, set] = {} for s in segments: own = frags_of.get(id(s)) if not own: continue turns: set = set() if s.get("role") == "agent": for f in own: t = producing_turn(f["spokenTime"]) if t is not None: turns.add(t) else: # User tags are timely: the tag is the turn that started when they spoke. for f in own: if f["turnId"] is not None: turns.add(f["turnId"]) turns_of[id(s)] = turns # The final goodbye is often cut off before its transcript finalizes, # pair any leftover turns with the remaining unmatched agent rows. assigned: set = set() for s in segments: if s.get("role") != "agent": continue for t in turns_of.get(id(s), set()): assigned.add(t) leftover_turns = [t for t in completed_turn_ids if t not in assigned] uncovered_agents = [ s for s in segments if s.get("role") == "agent" and covered.get(id(s)) is False and len(turns_of.get(id(s), set())) == 0 and len(_norm_text(s.get("text"))) > 0 # a row with no real words can't claim a turn ] for i in range(min(len(leftover_turns), len(uncovered_agents))): turns_of.setdefault(id(uncovered_agents[i]), set()).add(leftover_turns[i]) # Build lookups: which agent rows belong to each turn, and when each # customer row started speaking. rows_of_turn: dict[int, list[Json]] = {} user_rows: list[dict] = [] row_spoken: dict[int, float] = {} for s in segments: own = frags_of.get(id(s)) if own: row_spoken[id(s)] = own[0]["spokenTime"] turns = turns_of.get(id(s)) if not turns: continue if s.get("role") == "agent": for t in turns: rows_of_turn.setdefault(t, []).append(s) elif s.get("role") == "user": user_rows.append( {"row": s, "minTurn": min(turns), "spoken": row_spoken.get(id(s), 0)} ) # When each turn first produced output, the customer speech that triggered # a turn must have started before this moment. turn_first_out: dict[int, float] = {} for tid in completed_turn_ids: for e in by_turn[tid]: if e["event"] in ("pipeline.botSpeechStarted", "assistant.tool.started"): turn_first_out[tid] = min(turn_first_out.get(tid, math.inf), e["time"]) # Attach VAPI's latency numbers: entry #i describes completed turn #i. for i in range(len(completed_turn_ids)): T = completed_turn_ids[i] tl: Optional[Json] = turn_latencies[i] if i < len(turn_latencies) else None evs = by_turn[T] speech_rows = rows_of_turn.get(T, []) # STT goes to the customer row that triggered this turn. If one customer # row triggered several measured exchanges, keep the largest value, the # worst transcription delay that speech experienced. if tl is not None and tl.get("transcriberLatency") is not None: first_out = turn_first_out.get(T, math.inf) trigger = None for u in reversed(user_rows): if u["minTurn"] <= T and u["spoken"] < first_out: trigger = u["row"] break if trigger is not None: prev = (trigger.get("metadata") or {}).get("stt_node_ttfb") if prev is None or tl["transcriberLatency"] > prev: trigger["metadata"] = { **(trigger.get("metadata") or {}), "stt_node_ttfb": tl["transcriberLatency"], } # Latency/LLM/TTS go to the turn's first spoken reply. if ( speech_rows and tl is not None and "e2e_latency" not in (speech_rows[0].get("metadata") or {}) ): md: Json = {} if tl.get("turnLatency") is not None: md["e2e_latency"] = tl["turnLatency"] if tl.get("modelLatency") is not None: md["llm_node_ttft"] = tl["modelLatency"] if tl.get("voiceLatency") is not None: md["tts_node_ttfb"] = tl["voiceLatency"] if md: speech_rows[0]["metadata"] = {**(speech_rows[0].get("metadata") or {}), **md} # Replies spoken after a tool finished get their own metrics from the log. runs = [e for e in evs if e["event"] == "pipeline.botSpeechStarted"] for k in range(1, min(len(speech_rows), len(runs))): if "e2e_latency" in (speech_rows[k].get("metadata") or {}): continue run_start = runs[k]["time"] def last_before(name: str): for e in reversed(evs): if e["event"] == name and e["time"] < run_start: return e return None llm = last_before("assistant.model.firstTokenReceived") tts = last_before("assistant.voice.firstAudioReceived") tool = last_before("assistant.tool.completed") md = {} if tool: md["e2e_latency"] = run_start - tool["time"] # wait after the tool returned if llm and llm.get("latency") is not None: md["llm_node_ttft"] = llm["latency"] if tts and tts.get("latency") is not None: md["tts_node_ttfb"] = tts["latency"] if md: speech_rows[k]["metadata"] = {**(speech_rows[k].get("metadata") or {}), **md} # Interruptions: the log marks every barge-in the assistant reacted to. # We find which stretch of agent speech the cut landed inside and flag that # row. Barge-ins that happened before the agent even spoke have no row to # flag, so they are skipped. # Time spans when the agent was actually speaking, and which turn each span belongs to. intervals: list[dict] = [] open_iv: Optional[dict] = None for e in events: if e["event"] == "pipeline.botSpeechStarted": if open_iv: intervals.append({**open_iv, "end": e["time"]}) open_iv = {"tid": e["turnId"], "start": e["time"]} elif e["event"] == "pipeline.botSpeechStopped" and open_iv: intervals.append({**open_iv, "end": e["time"]}) open_iv = None if open_iv: intervals.append({**open_iv, "end": math.inf}) for e in events: if e["event"] != "pipeline.cleared" or not e["wasInterruption"]: continue # Match the LATEST interval containing the cut (with a little slack for # event-ordering jitter), when two speech runs are back to back, the cut # belongs to the one that was actually playing. hit: Optional[dict] = None for iv in intervals: if iv["start"] <= e["time"] <= iv["end"] + 100: hit = iv if not hit: continue # pre-speech cancellation: nothing was said, nothing to flag rows = rows_of_turn.get(hit["tid"], []) if not rows: continue # The cut row: among the turn's rows belonging to this speech run (spoken # after the run started, with slack for transcriber lag), the last one # already being spoken at the cut. in_run = [r for r in rows if row_spoken.get(id(r), 0) >= hit["start"] - 1000] pool = in_run if in_run else rows spoken = [r for r in pool if row_spoken.get(id(r), 0) <= e["time"] + 100] row = spoken[-1] if spoken else pool[0] row["metadata"] = {**(row.get("metadata") or {}), "interrupted": True} # VAPI sometimes splits one continuous agent sentence into two rows (when # the customer says something brief mid-sentence). The second piece has no # measurements of its own, so it would look like an empty row, re-join it # with its first half. Only provable same-turn pieces with no metrics of # their own are merged; everything else is left untouched. for i in range(len(segments) - 1, 0, -1): r = segments[i] if r.get("role") != "agent": continue md = r.get("metadata") or {} if ( md.get("e2e_latency") is not None or md.get("llm_node_ttft") is not None or md.get("tts_node_ttfb") is not None ): continue # has its own measurement -> a real, separate utterance r_turns = turns_of.get(id(r)) if not r_turns: continue # unbound -> not provably a slice pi = i - 1 while pi >= 0 and segments[pi].get("role") != "agent": pi -= 1 if pi < 0: continue p = segments[pi] p_turns = turns_of.get(id(p)) if not p_turns or not all(t in p_turns for t in r_turns): continue # different turn if md.get("interrupted") and (p.get("metadata") or {}).get("interrupted"): continue # two distinct cuts -> keep both visible p["text"] = f"{p.get('text') or ''} {r.get('text') or ''}".strip() r_end = ( r["end_ms"] if isinstance(r.get("end_ms"), (int, float)) else ( r["start_ms"] + r["duration_ms"] if isinstance(r.get("start_ms"), (int, float)) and isinstance(r.get("duration_ms"), (int, float)) else None ) ) if r_end is not None: p["end_ms"] = max(p["end_ms"], r_end) if isinstance(p.get("end_ms"), (int, float)) else r_end if isinstance(p.get("start_ms"), (int, float)) and isinstance(p.get("end_ms"), (int, float)): p["duration_ms"] = p["end_ms"] - p["start_ms"] if isinstance(r.get("words"), list) and r["words"]: p["words"] = [*(p.get("words") or []), *r["words"]] if md.get("interrupted"): p["metadata"] = {**(p.get("metadata") or {}), "interrupted": True} del segments[i] return True def _merge_user_slices(segments: list[Json]) -> None: """ Re-join customer sentences that VAPI split into two rows mid-sentence. Merged only when clearly one utterance: the rows are back to back with essentially no pause, and at most one of them carries an STT value (two measured rows are two real utterances and stay separate). """ for i in range(len(segments) - 1, 0, -1): r = segments[i] p = segments[i - 1] if r.get("role") != "user" or p.get("role") != "user": continue gap = ( r["start_ms"] - p["end_ms"] if isinstance(r.get("start_ms"), (int, float)) and isinstance(p.get("end_ms"), (int, float)) else math.inf ) if abs(gap) > 1000: continue # not a slice boundary r_stt = (r.get("metadata") or {}).get("stt_node_ttfb") p_stt = (p.get("metadata") or {}).get("stt_node_ttfb") if r_stt is not None and p_stt is not None: continue # two measured utterances p["text"] = f"{p.get('text') or ''} {r.get('text') or ''}".strip() r_end = ( r["end_ms"] if isinstance(r.get("end_ms"), (int, float)) else ( r["start_ms"] + r["duration_ms"] if isinstance(r.get("start_ms"), (int, float)) and isinstance(r.get("duration_ms"), (int, float)) else None ) ) if r_end is not None: p["end_ms"] = max(p["end_ms"], r_end) if isinstance(p.get("end_ms"), (int, float)) else r_end if isinstance(p.get("start_ms"), (int, float)) and isinstance(p.get("end_ms"), (int, float)): p["duration_ms"] = p["end_ms"] - p["start_ms"] if isinstance(r.get("words"), list) and r["words"]: p["words"] = [*(p.get("words") or []), *r["words"]] if r_stt is not None and p_stt is None: p["metadata"] = {**(p.get("metadata") or {}), "stt_node_ttfb": r_stt} if (r.get("metadata") or {}).get("interrupted"): p["metadata"] = {**(p.get("metadata") or {}), "interrupted": True} del segments[i] # ============================================================================= # CALL-LEVEL MAPPING, mirrors how Tuner maps VAPI calls natively. # ============================================================================= # VAPI call types -> Tuner's canonical snake_case values; unknown types pass through. _VAPI_CALL_TYPE_MAP = { "webCall": "web_call", "phoneCall": "phone_call", "sipCall": "sip_call", } def _map_call_type(vapi_type: Any) -> str: """Normalize VAPI's camelCase call type to Tuner's snake_case.""" if not vapi_type: return "phone_call" return _VAPI_CALL_TYPE_MAP.get(vapi_type, vapi_type) def _map_analysis(message: Json) -> tuple[Optional[Json], Optional[bool]]: """Build Tuner's call_analysis ({summary, success_evaluation}) and call_successful.""" call_analysis: Json = {} call_successful: Optional[bool] = None analysis: Json = message.get("analysis") or {} if analysis.get("summary"): call_analysis["summary"] = analysis["summary"] success_eval = analysis.get("successEvaluation") if success_eval is not None: call_analysis["success_evaluation"] = success_eval call_successful = str(success_eval).lower() == "true" # Fall back to the top-level summary if analysis didn't carry one. if message.get("summary") and "summary" not in call_analysis: call_analysis["summary"] = message["summary"] return (call_analysis if call_analysis else None), call_successful def _cost_in_cents(cost: Any) -> Optional[float]: """VAPI reports cost in dollars; Tuner expects cents.""" if not isinstance(cost, (int, float)) or isinstance(cost, bool) or math.isnan(cost): return None # round half up to 2 decimals, matching JS Math.round semantics return math.floor(cost * 100 * 100 + 0.5) / 100 def _strip_none(obj: Any) -> Any: """Drop None values recursively so segments only carry fields that exist.""" if isinstance(obj, list): return [_strip_none(v) for v in obj] if isinstance(obj, dict): return {k: _strip_none(v) for k, v in obj.items() if v is not None} return obj # ============================================================================= # MAPPING, VAPI messages -> Tuner's transcript timeline. # Mirrors Tuner's internal VAPI mapper so user/agent speech, tool calls, and # tool results are all captured. VAPI roles map to Tuner roles like so: # user -> user bot -> agent # tool_calls -> agent_function tool_call_result -> agent_result # system -> dropped # ============================================================================= def _build_segments(raw_messages: list, call_start_ms: Optional[int]) -> list[Json]: segments: list[Json] = [] for m in raw_messages: if not isinstance(m, dict): continue role = m.get("role") if role == "user": seg = _speech_segment(m, "user", call_start_ms) if seg: segments.append(seg) elif role in ("bot", "assistant"): seg = _speech_segment(m, "agent", call_start_ms) if seg: segments.append(seg) elif role == "tool_calls": segments.extend(_tool_call_segments(m)) elif role == "tool_call_result": segments.append(_tool_result_segment(m)) # "system" and anything else is intentionally skipped. return segments def _speech_segment(m: Json, role: str, call_start_ms: Optional[int]) -> Optional[Json]: """ A spoken row (customer or agent) with its timing. Tuner requires timing on every spoken row, so a rare row with no usable timing is skipped rather than rejecting the whole call. """ start_ms, end_ms, duration_ms = _segment_timing(m, call_start_ms) seg_words = _words(m.get("metadata"), call_start_ms) has_timing = start_ms is not None and (end_ms is not None or duration_ms is not None) if not has_timing and not seg_words: logger.warning( f"Tuner: skipping untimed {role} segment: {str(m.get('message') or '')[:50]}" ) return None seg: Json = {"role": role, "text": m.get("message")} if start_ms is not None: seg["start_ms"] = start_ms if end_ms is not None: seg["end_ms"] = end_ms if duration_ms is not None: seg["duration_ms"] = duration_ms if seg_words: seg["words"] = seg_words return seg def _tool_call_segments(m: Json) -> list[Json]: """One agent_function segment per tool the agent invoked.""" seconds = m.get("secondsFromStart") start_ms = math.ceil(seconds * 1000) if seconds is not None else None out: list[Json] = [] for tc in m.get("toolCalls") or []: if not isinstance(tc, dict): continue fn: Json = tc.get("function") or {} params = _maybe_json(fn.get("arguments")) out.append( { "role": "agent_function", "start_ms": start_ms, "end_ms": start_ms, "tool": { "name": fn.get("name"), "request_id": tc.get("id"), "params": params if isinstance(params, dict) else None, "start_ms": start_ms, "end_ms": start_ms, }, } ) return out def _tool_result_segment(m: Json) -> Json: """The result returned by a tool. Non-object results are wrapped so nothing is lost.""" seconds = m.get("secondsFromStart") start_ms = math.ceil(seconds * 1000) if seconds is not None else None parsed = _maybe_json(m.get("result")) if isinstance(parsed, dict): result: Optional[Json] = parsed elif (isinstance(parsed, list) and parsed) or (isinstance(parsed, str) and parsed): result = {"value": parsed} else: result = None is_error, error_msg = _detect_tool_error(m, parsed) tool: Json = { "name": m.get("name"), "request_id": m.get("toolCallId"), "result": result, "is_error": is_error, "start_ms": start_ms, "end_ms": start_ms, } if error_msg: tool["error"] = error_msg return {"role": "agent_result", "start_ms": start_ms, "end_ms": start_ms, "tool": tool} def _detect_tool_error(m: Json, parsed: Any) -> tuple[bool, Optional[str]]: """ Detect whether a tool result was an error and extract its message. VAPI has no single standard error flag, so the common explicit signals are checked. """ # 1. Explicit flags on the VAPI message (extra fields are allowed by VAPI). msg_error = m.get("error") if isinstance(msg_error, str) and msg_error: return True, msg_error if m.get("error") is True or m.get("isError") is True or m.get("is_error") is True: return True, (msg_error if isinstance(msg_error, str) else None) if m.get("success") is False: return True, None # 2. Error-shaped result payload, e.g. {"error": "..."} or {"status": "failed"}. if isinstance(parsed, dict): p = parsed if p.get("error"): return True, (p["error"] if isinstance(p["error"], str) else None) if p.get("success") is False: return True, None status = p.get("status") if isinstance(status, str) and status.lower() in ("error", "failed", "failure"): return True, (p["message"] if isinstance(p.get("message"), str) else None) return False, None # ============================================================================= # TURN GROUPING + LATENCY ATTACHMENT (payload-only path) # ============================================================================= def _group_into_turns(segments: list[Json]) -> list[dict]: """ Group transcript rows into conversation turns: each customer message starts a new turn, and everything the agent does until the next customer message (speech, tool calls, tool results) belongs to that turn. The opening greeting, spoken before any customer speech, has no trigger. """ turns: list[dict] = [] cur: dict = {"trigger": None, "rows": [], "hasSpeech": False} def flush(): if cur["rows"]: turns.append(cur) for seg in segments: role = seg.get("role") if role == "user": flush() cur = {"trigger": seg, "rows": [], "hasSpeech": False} elif role == "agent": cur["rows"].append(seg) cur["hasSpeech"] = True elif role == "agent_function" and cur["hasSpeech"]: flush() cur = {"trigger": cur["trigger"], "rows": [seg], "hasSpeech": False} else: cur["rows"].append(seg) # agent_result, or a tool call opening the turn flush() return turns def _enrich_with_turn_latencies(segments: list[Json], turn_latencies: list) -> None: """ Attach VAPI's latency numbers without the call log (fallback path). VAPI reports one latency entry per agent response: STT goes to the customer row that triggered it, and latency/LLM/TTS go to the agent's reply. The opening greeting has no entry. Zeros are real values and are kept. """ # Agent speech before any customer speech (the greeting) never gets an entry. eligible = [t for t in _group_into_turns(segments) if t["trigger"] is not None] count = min(len(eligible), len(turn_latencies)) for i in range(count): turn = eligible[i] tl = turn_latencies[i] trigger = turn["trigger"] if tl.get("transcriberLatency") is not None: prev = (trigger.get("metadata") or {}).get("stt_node_ttfb") if prev is None or tl["transcriberLatency"] > prev: trigger["metadata"] = { **(trigger.get("metadata") or {}), "stt_node_ttfb": tl["transcriberLatency"], } speech = next((r for r in turn["rows"] if r.get("role") == "agent"), None) if not speech: continue # e.g. an endCall turn with no spoken reply metadata: Json = {} if tl.get("turnLatency") is not None: metadata["e2e_latency"] = tl["turnLatency"] if tl.get("modelLatency") is not None: metadata["llm_node_ttft"] = tl["modelLatency"] if tl.get("voiceLatency") is not None: metadata["tts_node_ttfb"] = tl["voiceLatency"] if metadata: speech["metadata"] = {**(speech.get("metadata") or {}), **metadata} # A customer turn must start at least this many ms before the agent's turn ends # to count as a barge-in (filters out word-boundary noise and short backchannels). _INTERRUPTION_THRESHOLD_MS = 200 def _mark_interruptions(segments: list[Json]) -> None: """ Flag agent rows the customer talked over (fallback path, no call log). If a customer message starts clearly before the previous agent message ended, that agent message was interrupted. The log-based path detects interruptions more completely; this is the best the payload alone allows. """ last_agent_seg: Optional[Json] = None for seg in segments: role = seg.get("role") if role == "agent": last_agent_seg = seg elif role == "user": if ( last_agent_seg and last_agent_seg.get("end_ms") is not None and seg.get("start_ms") is not None and seg["start_ms"] < last_agent_seg["end_ms"] - _INTERRUPTION_THRESHOLD_MS ): last_agent_seg["metadata"] = { **(last_agent_seg.get("metadata") or {}), "interrupted": True, } last_agent_seg = None # each customer turn compares against a fresh agent turn # tool segments: ignore, keep the current agent turn as the candidate # ============================================================================= # TIMING HELPERS # ============================================================================= def _segment_timing(m: Json, call_start_ms: Optional[int]): """Work out a row's start/end/duration relative to the start of the call.""" start_ms: Optional[int] = None end_ms: Optional[int] = None duration_ms: Optional[int] = None seconds = m.get("secondsFromStart") if seconds is not None: start_ms = math.ceil(seconds * 1000) if m.get("duration") is not None: duration_ms = math.ceil(m["duration"]) if start_ms is not None and duration_ms is not None: end_ms = start_ms + duration_ms elif call_start_ms is not None: if m.get("time") is not None and start_ms is None: start_ms = math.ceil(m["time"] - call_start_ms) if m.get("endTime") is not None: end_ms = math.ceil(m["endTime"] - call_start_ms) if start_ms is not None and end_ms is not None: duration_ms = end_ms - start_ms return start_ms, end_ms, duration_ms def _words(metadata: Any, call_start_ms: Optional[int]) -> Optional[list[Json]]: """ Word-level timing from VAPI. VAPI has used different time units for word timestamps over time, so the unit is detected from the value itself. """ if not isinstance(metadata, dict): return None raw = metadata.get("wordLevelConfidence") if not isinstance(raw, list) or len(raw) == 0: return None def to_rel_ms(v: float) -> int: if v > 1e11: return math.ceil(v - (call_start_ms or 0)) # epoch ms if v < 1e5: return math.ceil(v * 1000) # seconds from call start return math.ceil(v) # already ms from call start out: list[Json] = [] for w in raw: if ( not isinstance(w, dict) or not w.get("word") or not isinstance(w.get("start"), (int, float)) or not isinstance(w.get("end"), (int, float)) ): continue out.append( { "word": w["word"], "start_ms": to_rel_ms(w["start"]), "end_ms": to_rel_ms(w["end"]), "confidence": w.get("confidence"), } ) return out or None def _maybe_json(value: Any) -> Any: """VAPI sends tool arguments/results as JSON strings; parse them, else pass through.""" if not isinstance(value, str): return value import json try: return json.loads(value) except ValueError: return value def _to_epoch_ms(value: Any) -> Optional[int]: """Accept VAPI's ISO string ('2026-06-10T...Z') or a number; return epoch ms.""" if value is None: return None if isinstance(value, (int, float)) and not isinstance(value, bool): return math.trunc(value) try: s = str(value).replace("Z", "+00:00") dt = datetime.fromisoformat(s) if dt.tzinfo is None: dt = dt.replace(tzinfo=timezone.utc) return int(dt.timestamp() * 1000) except (ValueError, TypeError): return None ``` **4. Get your keys and configure the file** Open the file and fill in the four config values at the top, all from the Tuner dashboard: ```ts Node theme={null} // ============================================================================= // CONFIG, fill these in // ============================================================================= const TUNER_BASE_URL = "https://api.usetuner.ai"; // your Tuner API base URL const TUNER_API_KEY = "tr_api_xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"; const TUNER_WORKSPACE = 0; // your workspace id (number) const TUNER_AGENT_ID = "your-custom-api-agent-id"; ``` ```python Python theme={null} # ============================================================================= # CONFIG, fill these in # ============================================================================= TUNER_BASE_URL = "https://api.usetuner.ai" # your Tuner API base URL TUNER_API_KEY = "tr_api_xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" TUNER_WORKSPACE = 0 # your workspace id (number) TUNER_AGENT_ID = "your-custom-api-agent-id" ``` **TUNER_BASE_URL** `string` (default: [https://api.usetuner.ai](https://api.usetuner.ai)) Your Tuner API base URL. **TUNER_API_KEY** `string` *required* Create one on the **API Keys** page (starts with `tr_api_`). See [API keys](/docs/getting-started/api-keys). **TUNER_WORKSPACE** `number` *required* Found in **Workspace Settings > General Settings > Workspace ID** (a number). **TUNER_AGENT_ID** `string` *required* On the Custom API agent: **Agent Settings > Agent Setup > Agent Connection > Agent Remote ID**. **Set the retry logic** (just below the config) to taste, these control how the POST to Tuner behaves on transient failures: ```ts Node theme={null} // Network timeout & retry behavior for the POST to Tuner. const REQUEST_TIMEOUT_MS = 15_000; // per-attempt timeout for the POST to Tuner const MAX_ATTEMPTS = 3; // retry attempts on transient failures (network, 408, 429, 5xx) ``` ```python Python theme={null} # Network timeout & retry behavior for the POST to Tuner. REQUEST_TIMEOUT_S = 15 # per-attempt timeout for the POST to Tuner MAX_ATTEMPTS = 3 # retry attempts on transient failures (network, 408, 429, 5xx) ``` > [!NOTE] > > Retries use exponential backoff with jitter and respect `Retry-After`; > only transient failures are retried (other `4xx` fail fast). The defaults > are safe, raise `MAX_ATTEMPTS` if Tuner ingestion is occasionally slow > on your network. **5. Call the function where your call ends** Call the forward function (`sendCallToTuner` in Node, `send_call_to_tuner` in Python) from inside your VAPI **`end-of-call-report`** webhook handler. The single required argument is the **`message` object VAPI posts to your webhook** (`body.message`). ```ts Node theme={null} import { sendCallToTuner } from "./send_to_tuner"; // your existing VAPI webhook endpoint app.post("/vapi/webhook", (req, res) => { const message = req.body?.message; if (message?.type === "end-of-call-report") { // fire-and-forget, never blocks, never throws sendCallToTuner(message); } res.sendStatus(200); }); ``` ```python Python theme={null} from send_to_tuner import send_call_to_tuner # your existing VAPI webhook endpoint (FastAPI shown) @app.post("/vapi/webhook") async def vapi_webhook(request: Request): message = (await request.json()).get("message") or {} if message.get("type") == "end-of-call-report": # never blocks your handler, never raises send_call_to_tuner(message) return {} ``` > [!TIP] > > **Optional: attach your own metadata.** Pass a second free-form object > for anything that changes per call or per use case: customer names, the > use case, A/B variant, prompt version, even your whole custom system > prompt. It's stored with the call in Tuner, and you can evaluate calls > based on it. > > ```ts Node theme={null} > sendCallToTuner(message, { > customer_name: "Yuki Tanaka", > use_case: "balance_inquiry", > prompt_version: "v3", > system_prompt: "You are a helpful assistant for Acme Corp...", > }); > ``` > > ```python Python theme={null} > send_call_to_tuner(message, { > "customer_name": "Yuki Tanaka", > "use_case": "balance_inquiry", > "prompt_version": "v3", > "system_prompt": "You are a helpful assistant for Acme Corp...", > }) > ``` > > Metadata must be JSON-serializable; if it isn't, the call is still sent > without it. Nothing is sent by default, omit the argument to send no > metadata. > > To see how Tuner uses this metadata to evaluate each agent against its > own instructions, read > [Evaluating Agents with Dynamic Instructions](/docs/evaluation/dynamic-agents). **6. That's it** Make a call. When it ends, it appears under your Custom API agent in Tuner with the full transcript, tool calls/results, per-turn latency and interruption metrics, the recording, and cost, plus any metadata you attached. ## Setting up simulation Ingestion gets your real calls into Tuner, simulation lets Tuner **place test calls to your VAPI agent** and evaluate how it behaves. The integration already sends the `sip_call_id` Tuner needs to link a simulated call back to its simulation run, so once ingestion is working, simulation only needs a SIP trunk on the VAPI side. > [card] [Set up simulation for your VAPI agent](/docs/simulation/inbound/setup#vapi) > > Create a free VAPI SIP trunk, link your assistant, and paste the SIP URI and > credentials into Tuner, full walkthrough in the simulation setup guide. ## Troubleshooting Everything is logged with a `Tuner:` prefix, via `console.warn` / `console.info` in Node and the `tuner` logger (`logging`) in Python: > [accordion] Tuner: sent call \ > > Success. `(log-enriched)` means precise per-turn metrics were attached. > [accordion] Tuner: call \ already sent > > This call was already ingested, safe to ignore. > [accordion] Tuner: could not fetch/read VAPI call log … > > The call log wasn't usable; the call is still sent with payload-only > metrics. > [accordion] Tuner: … not retryable: \ > > Tuner rejected the request with an error that retrying can't fix (any > `4xx` except `408`/`429`, e.g. a bad API key or wrong agent id), so it > fails immediately without using any retry attempts. Check your config > values. > [accordion] Tuner: call \ failed after N attempts > > A transient failure (network error, timeout, `408`, `429`, or `5xx`) kept > happening until all `MAX_ATTEMPTS` retries were used up. The call was not > ingested. > [!WARNING] > > If calls never arrive: double-check `TUNER_API_KEY`, `TUNER_WORKSPACE`, and > `TUNER_AGENT_ID`, and confirm your handler only forwards > `end-of-call-report` events. # Webhooks Source: https://docs.usetuner.ai/docs/integrations/webhooks The events Tuner sends to an agent's webhook URL, their format and headers, and the URL requirements. ## Overview Every agent in Tuner can have one webhook URL, whatever its provider. Set it in **Agent Settings > Webhooks**, and Tuner sends events to it as they happen. | Event | When it's sent | Available for | | - | - | - | | `call.analyzed` | Tuner finishes analyzing a call for the first time | All providers | | `alert.fired` | A [real-time alert](/docs/observability/alerts) triggers (with the Webhook channel enabled) | All providers | | `call.received` | Tuner receives Retell's `call_analyzed` event, Vapi's `end-of-call-report` message or ElevenLabs' `post_call_transcription` event, and forwards it | Vapi, Retell and ElevenLabs only | ## Setup **1. Open your agent's webhook settings** Select the agent in the sidebar, open **Agent Settings** and go to the **Webhooks** tab. **2. Enter your webhook URL** In **URL**, enter the endpoint that should receive events, for example your n8n, Zapier or custom server endpoint. See [URL requirements](#url-requirements). **3. Save** Click **Save**. Tuner starts sending events to your URL. ![Agent Settings, Webhooks tab](https://mintcdn.com/tuner/kwIC18oY4A8eHfb1/images/webhook.png?fit=max\&auto=format\&n=kwIC18oY4A8eHfb1\&q=85\&s=b2db9a0b327a0d2ab1ccc1da13ef279d) ## URL requirements Tuner only delivers to URLs that meet all of these rules. If the URL breaks one, Tuner rejects it when you save, or skips delivery. | Rule | Detail | | - | - | | HTTPS only | The URL must start with `https://`. | | Publicly reachable | The hostname must resolve to public IP addresses. Hosts that resolve to private, loopback, link-local, multicast or reserved addresses (for example `localhost` or `10.x.x.x`) are rejected. | | Not a Tuner API host | The URL can't point to the Tuner API, such as `api.usetuner.ai`. | | No redirects | Tuner doesn't follow redirects. A `3xx` response counts as a failed delivery. | ## Delivery Tuner sends each event as an HTTP `POST` with a JSON body. Your endpoint should return a `2xx` status. * A `2xx` response marks the delivery as done. * A `404` response is treated as done and is not retried. * Any other response, a timeout or a connection error counts as a failure, and the delivery is retried. | Setting | Value | | - | - | | Method | `POST` | | Request timeout | 15 seconds | ## Headers Every delivery includes these headers, so you can route an event before you parse the body: | Header | Value | | - | - | | `X-Tuner-Event` | The event type: `call.analyzed`, `alert.fired` or `call.received`. | | `X-Tuner-Event-Id` | The event's `event_id`, same as in the body. | | `X-Tuner-Webhook-Version` | The version of the envelope format: `2026-07-02`. | ## Event envelope All events share the same envelope, so a single handler can process everything: * **`event`**: the event type (`call.analyzed`, `alert.fired` or `call.received`). * **`event_id`**: the event type and the subject it's about, joined by `:`. See the table below. * **`created_at`**: ISO 8601 timestamp of when the event was created. * **`payload`**: the event-specific data. * **`call_id`**: the provider's call ID. Only on `call.analyzed`. The `event_id` is built from the event and its subject, so a retried delivery carries the same `event_id`. Store the IDs you've processed and skip repeats. | Event | `event_id` format | | - | - | | `call.analyzed` | `call.analyzed:` | | `alert.fired` | `alert.fired::` | | `call.received` | `call.received:` | ## Event types ### `call.analyzed`: call analysis complete Sent for all providers once Tuner finishes analyzing a call. It's sent once per call; re-running the analysis doesn't send it again. The payload links to the call in Tuner, so you can route it into ticketing systems, QA queues or internal dashboards. If the call's outcome has [**Stop Analysis**](/docs/evaluation/call-classification#set-up-call-classification) turned on, Tuner sends `call.analyzed` as soon as the outcome is saved. | Field | Description | | - | - | | `payload.tuner_call_url` | Link to the call in Tuner [Call Logs](/docs/observability/call-logs). | | `payload.provider_agent_id` | The agent's **Agent Remote ID**. | | `payload.is_simulated` | `true` if the call came from a [simulation](/docs/simulation/overview) or a [Replay](/docs/simulation/replays), `false` for every other call. | Simulated calls also send `call.analyzed`. Check `payload.is_simulated` before you act on the event, so test calls don't create records or notifications in your own systems. Use `call.analyzed` for this: `call.received` doesn't carry the field, and simulated calls don't trigger alerts, so they never send `alert.fired`. A simulated call that Tuner can't [link to its run](/docs/simulation/run-statuses#how-simulated-calls-are-linked) counts as a regular call, so it has `is_simulated: false`. ```json theme={null} { "event": "call.analyzed", "event_id": "call.analyzed:call_d6e56839d80a34474f2f57f06a7", "created_at": "2026-07-03T14:39:33.677818+00:00", "payload": { "tuner_call_url": "https://app.usetuner.ai/call-logs/8379", "provider_agent_id": "agent_5410a3ec3f429c24c36e79e356", "is_simulated": false }, "call_id": "call_d6e56839d80a34474f2f57f06a7" } ``` ### `alert.fired`: a real-time alert triggered Sent for all providers when a [real-time alert](/docs/observability/alerts) with the **Webhook** notification channel enabled fires. The payload includes the alert definition, the threshold and time window that were breached, the call that triggered it and a link to the calls behind this alert firing. | Field | Description | | - | - | | `payload.alert_id` | The alert's ID. | | `payload.alert_name` | The alert's **Alert name**. | | `payload.severity` | `info`, `warning` or `critical`. | | `payload.alert_trigger_id` | The ID of this alert firing. Each time the alert fires, it gets a new ID. Pass it to [List calls](/api-reference/calls/list-calls) to list the calls behind this alert firing. | | `payload.call_id` | The Tuner ID of the call that made the alert fire. | | `payload.agent_id` | The Tuner ID of the alert's agent. | | `payload.qualifying_count` | The number of calls that matched the conditions in the window. | | `payload.threshold_n`, `payload.threshold_percentage`, `payload.threshold_minimum` | The alert's threshold settings when it fired: the call count, the **Percentage (%)** and the **Minimum calls**. | | `payload.window_ms` | The alert's time window in milliseconds. | | `payload.window_start`, `payload.window_end` | The window checked: from `window_ms` before the call ended to when the call ended. | | `payload.triggered_at` | When the alert fired. | | `payload.total_count` | For a **Percentage** alert, the calls in the window that Tuner could check for the condition's field. `null` for a **Count** alert. | | `payload.threshold_type` | `count` or `percentage`. | | `payload.call_logs_url` | A link to [Call Logs](/docs/observability/call-logs), filtered to the calls behind this alert firing. See [See the calls behind an alert](/docs/observability/alerts#see-the-calls-behind-an-alert). | ```json theme={null} { "event": "alert.fired", "event_id": "alert.fired:155:66", "created_at": "2026-07-06T03:10:35.868197+00:00", "payload": { "alert_id": 155, "alert_name": "hallucination-happened", "severity": "critical", "alert_trigger_id": 66, "call_id": 8383, "agent_id": 466, "qualifying_count": 1, "threshold_n": 1, "window_ms": 3600000, "window_start": "2026-06-25T09:18:22+00:00", "window_end": "2026-06-25T10:18:22+00:00", "triggered_at": "2026-07-06T03:10:35.513644+00:00", "total_count": null, "threshold_type": "count", "threshold_percentage": null, "threshold_minimum": null, "call_logs_url": "https://app.usetuner.ai/call-logs?workspace=12&agent=466&alerts=155&trigger=66" } } ``` ### `call.received`: provider event forwarding (Vapi, Retell and ElevenLabs only) Vapi, Retell and ElevenLabs support a single webhook URL per agent. When you connect one of these agents to Tuner, Tuner takes that webhook slot, so an automation wired to it (an n8n workflow, a Zapier trigger, a custom server) stops receiving events from the provider. To keep those automations running, Tuner forwards one provider event per call to your webhook URL as a `call.received` event: | Provider | Forwarded event | Not forwarded | | - | - | - | | Retell | `call_analyzed` | All other Retell webhook events | | Vapi | `end-of-call-report` | All other Vapi server messages | | ElevenLabs | `post_call_transcription` | All other ElevenLabs webhook events | The `payload` field holds the provider's original request body, unchanged. Update your handler to read `payload` instead of the request body root. If an automation relies on an event that isn't forwarded, it won't receive it through Tuner. ```json theme={null} { "event": "call.received", "event_id": "call.received:call_d6e56839d80a34474f2f57f06a7", "created_at": "2026-07-03T14:37:57.231241+00:00", "payload": { // The body Retell, Vapi or ElevenLabs sent, unchanged } } ``` For other providers (LiveKit, Pipecat, Dograh, custom integrations), calls reach Tuner through the SDK or API, so there is no provider event to forward. Those agents receive `call.analyzed` and `alert.fired` only. ## Next steps > [card] [Configure real-time alerts](/docs/observability/alerts) > > Create alerts and route them to email and your webhook. > [card] [Connecting to Retell](/docs/integrations/retell) > > Connect your Retell agent and keep your existing webhook automations. # Diagnose your agent Source: https://docs.usetuner.ai/docs/mcp/diagnose Use the Tuner MCP to find what's broken in your agent, understand why, and fix it, including adding the evals and data capture that keep it fixed. The dashboard shows which calls are failing. A diagnosis explains why. The Tuner MCP server reads your workspace and can write back to it, so the same assistant that finds the root cause can add the evals, intents and data fields that measure it, and suggest the prompt change. > [!NOTE] > > Diagnosis needs the [Tuner MCP server connected](/docs/mcp/setup) to your AI client, and calls from the last 30 days on the agent. *** ## Run a diagnosis Paste this into your chat to run a full diagnosis: ```text theme={null} Diagnose my agent and tell me what is broken and how to fix it. Fetch and follow the 'tuner_analyze_agent' prompt from the Tuner MCP server. agent_id: 485 workspace_id: 1420 agent_name: agent007 ``` > [!TIP] > > Replace `agent_id`, `workspace_id`, and `agent_name` with your own values. To skip typing them, click **Diagnose Agent** on the **Overview** page to copy the prompt with your values filled in. You can also ask first: *"List the agents in workspace 1420"*. See [API keys and IDs](/docs/getting-started/api-keys) for where the workspace ID is. ![Diagnose Agent button in the Tuner dashboard, prefilled with a prompt to run a full diagnosis](https://mintcdn.com/tuner/kFyLT0qVX-rDk43X/images/diagnose.png?fit=max\&auto=format\&n=kFyLT0qVX-rDk43X\&q=85\&s=c0c1f079336e32dd25dc517ae4be0ce5) *** ## What the diagnosis looks at Following the `tuner_analyze_agent` prompt, the assistant works through your data in this order: **1. Reads your agent's configuration** Pulls the system prompt, workflow, and description, plus everything you've defined: outcomes, intents, data-extraction fields, evals, and red flags. Everything else is measured against this. **2. Builds the health picture** Reviews success rate, red-flag rate, call volume, and trends over the last 30 days, then breaks calls down across your outcome labels and intent categories, to tell whether the agent is broadly healthy with isolated issues or degraded across the board. **3. Finds the priority signals** Looks at recently red-flagged calls and which intents and outcomes they cluster on. A red flag concentrated on one intent with bad outcomes becomes the lead to chase. **4. Isolates the problem segments** Filters the call logs down to the underperforming intent + outcome combinations and checks whether the problem is chronic or started at a specific agent version. A change that lines up with a version points to a regression. **5. Digs into individual calls** Opens the worst calls in detail: which evals are failing, whether STT, LLM, TTS, or end-to-end latency is elevated, and whether the same red flags fire consistently. **6. Cross-references against your prompt** Compares what the failing calls show against what your prompt and workflow are actually designed to do. The gap between the two is the root cause. *** ## What you get back The assistant returns a structured diagnosis: * **Agent health**: a one-line summary with the headline number that supports it. * **Issues found**: each with the **Signal** (the data, with numbers), the **Pattern** across failing calls, the **Root cause** hypothesis and confidence, a specific **Fix** (what to change and where), and how to **Verify** it worked. * **What's working**: so you know what *not* to touch. * **Data gaps**: configuration that, if added, would sharpen future diagnoses. > [accordion] Example diagnosis output > > ```md theme={null} > ## Agent health > Broadly healthy: 82% success across 1,240 calls in the last 30 days, but one intent is dragging the average down. > > ## Issues found > > ### Booking fails when the requested time is unavailable > **Signal:** The "Offer alternative times" eval fails on 71% of *Make a Reservation* calls that end in the *No Availability* outcome, a red-flag rate ~3x the agent average. > **Pattern:** When the first-choice slot is taken, the agent apologizes and ends the call instead of proposing nearby times. > **Root cause:** The system prompt describes booking a requested slot but has no branch for the unavailable case. (High confidence.) > **Fix:** Add an explicit step to the booking workflow: when a slot is unavailable, offer the two closest available times before closing. > **Verify:** Watch the "Offer alternative times" eval pass-rate and the share of *No Availability* outcomes over the next week. > > ## What's working > Reservation confirmations and party-size capture pass on 96%+ of calls. Leave them as-is. > > ## Data gaps > No data-extraction field for the requested time, so how far off the alternatives are can't be measured. Adding it would sharpen this analysis. > ``` *** ## From diagnosis to fix The same assistant can apply the fix in the same conversation. The MCP server's write tools create, update and delete call outcomes, intents, data-extraction fields, evals, capabilities, tools, red-flag and label rules, and alerts, and can update the agent's name, description, language and call direction. See [What the MCP server can do](/docs/mcp/setup#what-the-mcp-server-can-do). After it explains the root cause, tell it to act. It can: * **Draft the prompt and workflow change** for you to make in your agent. * **Create or refine evals** so the behavior is scored on every future call. * **Add call outcomes and intents** so the right calls get categorized. * **Add data-extraction fields** to capture the values you need to measure the problem. * **Add red flags and alerts** so you're warned when it happens again. Then diagnose again to confirm the fix. Each pass adds the measurement the next diagnosis needs. *** ## Examples ### A spike in unresolved calls on one intent Suppose your **Billing Dispute** intent is ending **Unresolved** far more often than the rest of your calls. Ask: > *"Diagnose my agent: why are so many Billing Dispute calls ending unresolved, and how do I fix it?"* The assistant pulls the outcome breakdown and sees Billing Dispute sitting at a **48% Unresolved rate vs. 12% agent-wide**. It opens the worst calls and finds the same pattern: the agent can't move forward because it never collects the account number before trying to act on the dispute. It reports the signal, the pattern, the root cause, and a concrete fix. Then you close the loop in the same chat: > *"Draft the account-verification step for my prompt, create an eval that checks the agent collected and verified the account number, and add a data field to capture it."* The assistant drafts the prompt change for you to apply, and through the MCP server's write tools creates the eval (*"Did the agent verify the account number before discussing the dispute?"*) and the data-extraction field. Every future Billing Dispute call is now measured on that behavior, so your next diagnosis can confirm whether the Unresolved rate is dropping. ### Finding problems you didn't know to look for You can only write evals for problems you already know about. Diagnosis can surface the others. Ask: > *"Are there calls that don't match any of my configured intents? Cluster them and tell me what they're about."* The assistant scans your call logs for calls that landed with **no matching intent**, reads the transcripts, and groups them into themes. For example, **62 calls in the last 30 days asking about international shipping**, an intent you never defined. Because there's no flow for it, those calls fall through to a generic response and abandon at a high rate. The assistant explains the theme, shows you example transcripts, and recommends: * Add an **International Shipping** intent so these calls are tracked. * Add a prompt or workflow branch that handles the request. * Add an **eval** to check the agent gives accurate shipping information. You can have it create the intent and eval in the same conversation. *** ## Keep asking After the diagnosis, you can keep asking about your calls in plain language: > *"Show me the transcripts of the 3 worst calls behind that issue."* > *"What's different about the calls that fail versus the ones that succeed on this intent?"* > *"Break down latency for those calls. Which component is slow: STT, the LLM, or TTS?"* > *"Did this start at a specific agent version, or has it always been like this?"* > *"Draft the exact prompt change you're recommending, then create the eval to track it."* > *"Which eval is failing the most this week, and on what kind of calls?"* > [!NOTE] > > Diagnosis needs real calls to analyze. If your agent hasn't received any calls in the last 30 days, the assistant will ask you to send calls through it first. With fewer than 10 calls it will still run, but it flags that the findings may not yet be statistically reliable. *** ## Next steps > [card] [Set up the MCP server](/docs/mcp/setup) > > Connect the Tuner MCP server to your AI client and configure your agent. > [card] [Red flags and labels](/docs/evaluation/red-flags) > > The red flags the diagnosis prioritizes when triaging issues. # Set up the MCP server Source: https://docs.usetuner.ai/docs/mcp/setup Connect the Tuner MCP server to your IDE or chatbot and configure your agent in natural language. The Tuner MCP server lets your AI assistant read and change your Tuner workspace. You can configure an agent's outcomes, intents, evals, red flags and alerts by describing what you want, and ask questions about your calls. > [!NOTE] > > The Tuner MCP server is in **Beta**. Available actions and supported clients may change. ## Why use it Describe several outcomes, evals and intents in one message, and the assistant creates them together. Your assistant can also see your codebase, your agent's system prompt and your call flows. Ask *"based on my agent's system prompt, suggest the right call outcomes and evals"* to get a configuration that matches how your agent works. ## Supported clients | Client | Auth | | - | - | | **Claude** ([claude.ai](https://claude.ai)) | OAuth | | **Claude Code** | Tuner API key | | **Cursor** | Tuner API key | | **Antigravity** | Tuner API key | > [!NOTE] > > Tuner MCP server URL: `https://api.usetuner.ai/mcp/` ## Open the setup instructions in Tuner Tuner shows the same instructions with your IDs filled in: * While creating an agent, pick **Configure via MCP** in the setup wizard. See the [Quickstart](/docs/getting-started/quickstart#step-2-choose-how-to-configure-it). * For an existing agent, click **Configure with MCP** at the top of **Agent Settings**. The dialog has **Step 1: Connect to your AI client** and **Step 2: Start the setup**, with a prompt you can copy. ![The Configure with MCP dialog: IDE and chat app tabs, the Cursor, Claude Code and Antigravity options, setup steps and the server configuration to paste](https://mintcdn.com/tuner/bavd-UpNNQpDdJnb/images/configure-with-mcp.png?fit=max\&auto=format\&n=bavd-UpNNQpDdJnb\&q=85\&s=e208023b587d13a081ed929d6aace853) *** ## IDEs IDEs authenticate with a Tuner API key sent as a bearer token. Create one on the **API Keys** page; see [API keys and IDs](/docs/getting-started/api-keys). A key is shown only when you create it. ### Cursor **1. Open MCP settings** Go to **Settings > Tools & MCP** and click **Add Custom MCP** to open your `mcp.json`. **2. Paste the configuration** Add the following to your `mcp.json`: ```json theme={null} { "mcpServers": { "tuner": { "type": "streamableHttp", "url": "https://api.usetuner.ai/mcp/", "headers": { "Authorization": "Bearer YOUR_TUNER_API_KEY" } } } } ``` Replace `YOUR_TUNER_API_KEY` with your Tuner API key. ### Claude Code **1. Run the add command** Open your terminal inside **Claude Code** and run: ```bash theme={null} claude mcp add tuner https://api.usetuner.ai/mcp/ --transport http --header "Authorization: Bearer YOUR_TUNER_API_KEY" ``` Replace `YOUR_TUNER_API_KEY` with your Tuner API key. ### Antigravity **1. Open the MCP configuration** Click the **...** dropdown at the top of the editor's agent panel, then **Manage MCP Servers > View raw config** to open `mcp_config.json`. **2. Paste the configuration** Add the following to your `mcp_config.json`: ```json theme={null} { "mcpServers": { "tuner": { "serverUrl": "https://api.usetuner.ai/mcp/", "headers": { "Authorization": "Bearer YOUR_TUNER_API_KEY", "Content-Type": "application/json" } } } } ``` Replace `YOUR_TUNER_API_KEY` with your Tuner API key. *** ## Chatbots Chatbots authenticate with **OAuth**. The first time you add the server, you're redirected to Tuner to sign in and authorize access. ### Claude **1. Add a custom connector** Go to **Customize > Connectors**, click the plus icon, click **Add Custom Connector**, and paste the Tuner MCP server URL: ```text theme={null} https://api.usetuner.ai/mcp/ ``` **2. Connect and authenticate** Click **Connect**. You will be redirected to Tuner to sign in and authorize access. **3. Enable Tuner in your chat** When starting a new chat, click the **+** button and verify **Tuner** is toggled on under **Connectors**. *** ## Start the setup Once connected, paste this into your chat. **Configure with MCP** in Tuner gives you this prompt with your values filled in. ```text theme={null} Set up Tuner observability for this agent using the Tuner MCP. Fetch and follow the 'tuner_setup_agent' prompt from the Tuner MCP server. agent_id: workspace_id: agent_name: direction: INBOUND ``` > [!TIP] > > To find your workspace ID, open **Workspace Settings > General Settings**. Your agent's details are on **Agent Settings > Agent Setup**. See [API keys and IDs](/docs/getting-started/api-keys). You can also ask the assistant to list the agents in your workspace. The `tuner_setup_agent` prompt walks your assistant through defining your call outcomes, intents, data-extraction fields, evals, red flags and alerts in one conversation. ## What the MCP server can do The server gives your assistant these tools, for the workspaces your account or key can access. | Area | What the assistant can do | | - | - | | Workspaces and agents | List and read workspaces and agents, and update an agent | | Calls | List calls, filter them, read a call's details, and list recently red-flagged calls | | Dashboards | Read the Overview numbers and the intent and outcome breakdowns | | Agent configuration | Create, update and delete call outcomes, intents, data-extraction fields, evals, capabilities, tools, red-flag and label rules, and alerts | | Libraries | Read Tuner's predefined evals and call outcome library, the agent's analysis and voice metric settings, and the conditions available for rules and alerts | It also has prompts that guide the assistant through a task. Ask the assistant to fetch one by name: | Prompt | What it does | | - | - | | `tuner_setup_agent` | Configure the agent's instructions and settings | | `tuner_setup_outcomes` | Configure call success and failure outcomes | | `tuner_setup_intents` | Configure call intent categories | | `tuner_setup_data_fields` | Configure data-extraction fields | | `tuner_setup_evals` | Configure evals | | `tuner_setup_red_flags` | Configure labels and red flags | | `tuner_setup_alerts` | Configure alerts | | `tuner_analyze_agent` | Diagnose what is broken in the agent and recommend fixes. See [Diagnose your agent](/docs/mcp/diagnose). | Simulations, datasets, API keys and workspace settings are managed in the dashboard. ## Example prompts Bulk setup from a description: > *"I have a restaurant booking agent. Create the following call outcomes: Reservation Booked (Success), Reservation Modified (Success), Customer Cancelled (Failure), No Availability (Failure), and General Inquiry (Success). Also add user intents for: Make a Reservation, Modify a Reservation, Cancel a Reservation, and Ask About Menu."* Several evals at once: > *"Add these evals: Did the agent confirm the reservation date and time? Did the agent ask for the party size? Did the agent offer alternative times when the requested slot was unavailable?"* Reading your current setup: > *"List all agents in my workspace and show me a summary of how each one is configured."* ## Best practices > [accordion] Be specific, and name the agent > > Detail gets better results. Instead of *"add some call outcomes"*, try *"for my Customer Support agent, add a call outcome called 'Appointment Booked' with type Success, defined as: the customer scheduled an appointment with a confirmed date and time."* If you have multiple agents, always say which one. > [accordion] Use bulk operations for initial setup > > Describe all your outcomes, intents, and evals in one message. The assistant creates them together. > [accordion] Review changes after making them > > Ask your assistant to list the current settings afterwards, so you can verify everything looks right before calls start flowing. > [accordion] Use the dashboard for monitoring > > Use the MCP server for configuration and diagnosis. Track live results and trends over time in the [Tuner dashboard](https://app.usetuner.ai/). *** ## Troubleshooting > [accordion] Connection failed or timed out > > * **Chatbots:** Check that you're using the correct MCP server URL and that your Tuner account is active. > * **IDEs:** Check that your API key is valid and correctly placed in the configuration file. Make sure `https://api.usetuner.ai/mcp/` is reachable. > [accordion] Authentication error > > * **Chatbots:** Disconnect and reconnect. In Claude, go to **Customize > Connectors**, remove Tuner, then add it again. > * **IDEs:** Check that the key hasn't been revoked on the **API Keys** page. If you no longer have it, create a new key and update your configuration file. > [accordion] Tuner not appearing in chat > > * **Claude:** Click the **+** button and check that Tuner is toggled on under **Connectors**. > * **IDEs:** Verify the MCP server configuration is saved correctly and restart the IDE if needed. *** ## Next steps > [card] [Diagnose your agent](/docs/mcp/diagnose) > > Once calls are flowing, use the MCP server to find what's broken, understand why, and fix it. > [card] [Call outcomes and intents](/docs/evaluation/call-classification) > > What you're configuring when you set these up through MCP. # Real-time alerts Source: https://docs.usetuner.ai/docs/observability/alerts Create alerts that email you or call your webhook when enough calls match the conditions you set, see the calls behind each alert, and manage alerts from the Alerts tab. > [!NOTE] > > Alerts are set per agent in **Agent Settings > Alerts**. Conditions use your [evals](/docs/evaluation/overview), [red flags](/docs/evaluation/red-flags), data extraction fields, latency and call details, so set those up first. To deliver alerts to a webhook, add a webhook URL in **Agent Settings > Webhooks**. ## What is an alert? An alert is a notification Tuner sends when calls matching your conditions cross a threshold within a time window, for example "5 calls in 1 hour where **Hallucination** is **FAIL**". Tuner checks your alerts after it finishes analyzing each call and notifies you by **Email**, **Webhook** or both. ## Create an alert **1. Open the Alerts tab** Go to **Agent Settings** and open the **Alerts** tab. It lists your existing alerts with their channels, status and last triggered time. **2. Click Create Alert** Click **Create Alert** to open the alert form. **3. Name the alert and pick a severity** * **Alert name**: a name for the alert, such as "Hallucination spike". * **Description (optional)**: a note for your team. * **Severity**: **Info**, **Warning** (default) or **Critical**. Severity tells your team how urgent the alert is. **4. Add trigger conditions** Under **Trigger Condition**, build each condition from three parts: * **Select field**: what to check. Fields are grouped by source (see [Condition fields](#condition-fields)). * **Op**: how to compare. The operators offered depend on the field (see [Operators](#operators)). * **Select value**: the value to compare against. For a pass/fail eval, pick **PASS** or **FAIL**. Click **Add condition** to add more, up to 10. With two or more conditions, choose **Match:** **ALL (AND)** to require every condition, or **ANY (OR)** to require at least one. **5. Set the threshold** Under **Trigger when**, choose **Count** or **Percentage**. * **Count**: enter a number of calls and pick a time window. The alert fires when that many matching calls occur within the window, for example "10 calls in 1 hour". * **Percentage**: enter **Percentage (%)**, **Minimum calls** and **Time window**. The alert fires when that share of calls match and at least the minimum number of calls match within the window. Percentage mode supports exactly one condition. The time window is **5 mins**, **15 mins**, **1 hour** (default) or **24 hours**. Then pick a **Cooldown**: how long the alert waits after it triggers before it can trigger again. Choose **15 minutes** (default), **1 hour**, **4 hours** or **24 hours**. A longer cooldown sends fewer repeat notifications while calls keep matching. The summary under the panel updates to show the threshold and the cooldown. **6. Choose notification channels** Under **Notification channels**, select one or both: * **Email**: enter one or more addresses, separated by commas. * **Webhook**: Tuner sends an `alert.fired` event to your agent's webhook. If the agent has no webhook URL yet, selecting it prompts you to configure one. See [Webhooks](/docs/integrations/webhooks) for the payload. ![Alert notification channels: Email and Webhook](https://mintcdn.com/tuner/mzoMpdYrZufCNgUL/images/alerts-webhook.png?fit=max\&auto=format\&n=mzoMpdYrZufCNgUL\&q=85\&s=37179b10ac6d702d91b2ff889dea14eb) **7. Save the alert** Click **Save alert**. The alert appears in the list and is active. ## Condition fields The **Select field** list groups fields by source. A group only lists items that exist for this agent. | Group | Fields | Values | | - | - | - | | **Evals** | Each eval on the agent | **PASS** or **FAIL** for pass/fail evals; **1** to **5** for score evals | | **Voice Metrics** | **P50 Latency**, **P75 Latency**, **P90 Latency**, **P95 Latency**, **P99 Latency**, plus any enabled voice metrics | A number in milliseconds | | **Data Fields** | Each data extraction field | A value of the field | | **Red Flags** | Each red flag rule | Fixed to **Occurred** | | **Red Flag Aggregates** | **Red Flag Count** | A number | | **Call Metadata** | **Call Outcome**, **Call Intent**, **Call Outcome Type**, **Call Duration** (ms), **Call Cost**, **Call Ended Reason**, **Extra Metadata** | Text or a number. **Call Ended Reason** is how the call ended, as your provider reports it, for example `customer-ended-call` (Vapi). For **Extra Metadata**, enter only the key in **Metadata key**, for example `customer_id` (nested values use dots, such as `plan.tier`), and a **Value** | ## Operators | Operator | Available for | | - | - | | **Equals (=)**, **Not equal (!=)** | All fields. Red flags use **Equals (=)** only | | **Greater than (>)**, **Less than (\<)**, **Greater than or equal (>=)**, **Less than or equal (\<=)** | Score evals, voice metrics, number data fields, **Red Flag Count**, **Call Duration**, **Call Cost** | | **Is present**, **Is not present**, **Contains**, **Starts with** | **Extra Metadata**, **Call Ended Reason** | **Is present** and **Is not present** take no value. Text comparisons ignore case with every operator. `Customer-Ended-Call` matches `customer-ended-call`, and **Contains** `hangup` matches `Customer_Hangup`. A call with no ended reason matches **Call Ended Reason** only with **Is not present** or **Not equal (!=)**. ## Combine conditions The dashboard combines a flat list of conditions, up to 10, with one **Match:** setting. **ALL (AND)** requires every condition, and **ANY (OR)** requires at least one. The API also accepts nested groups, which combine AND and OR in one alert. For example, an alert can fire when a call is a refund longer than 60 seconds, or when a call has a failed **Hallucination** eval. * A tree nests up to 10 levels deep and holds up to 50 conditions. * **Percentage** mode needs exactly one condition, so it doesn't accept nested groups. The dashboard can't create nested groups. If you create an alert with nested groups through the API, you can read its conditions in the dashboard and change them only through the API. You can still edit the alert's other fields, and saving keeps the conditions as they are. ## When alerts fire * Tuner checks alerts after it analyzes a call. If any analysis step failed for that call, Tuner doesn't check alerts for it. * If the call's outcome has [**Stop Analysis**](/docs/evaluation/call-classification#set-up-call-classification) turned on, Tuner checks alerts as soon as the outcome is saved. For that call: * Conditions on **Evals**, **Data Fields** and **Call Intent** don't match, including **Not equal (!=)**. * **Percentage** alerts on those fields leave the call out of the total. * Conditions on all other fields match as usual. * After an alert fires, it doesn't fire again until its **Cooldown** has passed, even if more calls match. * Paused alerts are not checked. * If you rename an eval or data extraction field, alerts that use it keep working and show the new name. * Calls whose outcome has [**Stop Analysis**](/docs/evaluation/call-classification) turned on are still checked. Evals, data fields and intents Tuner skipped count as not analyzed, so a condition like **Not equal (!=)** on them doesn't match. * If you delete an eval, data extraction field, voice metric or red flag that an alert uses, Tuner pauses the alert until you fix its condition. See [Resume a paused alert](#resume-a-paused-alert). * Calls from a [simulation](/docs/simulation/overview) or a [Replay](/docs/simulation/replays) are not checked. They don't count toward any alert's number of calls or percentage. In **Percentage** mode, the share is matching calls divided by the calls Tuner can check for the condition's field. A call it can't check never counts as a match, even with **Not equal (!=)**. Tuner can check a call when: | Field | Tuner can check the call when | | - | - | | **Evals** and **Data Fields** | The call has a result for the eval or field, even if the result has no value | | **Extra Metadata** | The call's metadata has the key, including with a `null` value. With **Is present** or **Is not present**, every call counts | | **Red Flags** and **Red Flag Count** | Every call | | **Call Ended Reason** | The call has an ended reason. With **Is present** or **Is not present**, every call counts | | **Voice Metrics** and the other **Call Metadata** fields | The call has a value for the field | ## Example alerts > [accordion] Hallucination spike > > **Alert name**: Hallucination spike\ > **Severity**: Critical\ > **Condition**: **Hallucination** **Equals (=)** **FAIL**\ > **Trigger when**: **Count**, 5 calls in **1 hour** > > Notifies you when the agent gives inaccurate information on several calls. > [accordion] Identity verification failures > > **Alert name**: Identity not verified\ > **Severity**: Warning\ > **Condition**: **Identity verification compliance** **Equals (=)** **FAIL**\ > **Trigger when**: **Percentage**, 10% with **Minimum calls** 5, **1 hour** > > Useful for agents that must verify identity before sharing sensitive information. > [accordion] Slow responses > > **Alert name**: Slow responses\ > **Severity**: Warning\ > **Condition**: **P90 Latency** **Greater than (>)** 2500\ > **Trigger when**: **Count**, 15 calls in **1 hour** > > Tells you when many calls have slow agent responses. ## See the calls behind an alert Open the calls that made an alert fire from any channel: * **Email**: click **View calls**. The email shows the count, such as "12 calls triggered this alert", or for a **Percentage** alert the matching calls out of the calls Tuner could check, such as "12 of 40 calls matched the conditions." * **Webhook**: open the `call_logs_url` in the `alert.fired` payload. See [Webhooks](/docs/integrations/webhooks). * **Dashboard**: click a row in the alert's [trigger history](#trigger-history). * **API**: pass the payload's `alert_trigger_id` to [List calls](/api-reference/calls/list-calls). [Call Logs](/docs/observability/call-logs) opens in the alert's workspace and agent with two filters, shown as chips: **Alert** and **Trigger**, such as **Trigger #1042**. Your date range isn't applied while the **Trigger** filter is on. * Remove the **Trigger** chip to see every call that matched the alert in your date range, including calls that matched during the **Cooldown**. * Remove the **Alert** chip to remove both filters. If a link can't open the alert's calls: * If you're signed out, sign in and Call Logs opens with the link's filters. * If you can't open the link's workspace, Call Logs opens for your current agent without the alert filters. * If the link's agent isn't in the workspace, Call Logs opens the workspace's first agent without the alert filters. * If the alert was deleted, Call Logs shows "This alert was deleted." and drops the alert filters. Each time an alert fires, Tuner saves the matching calls counted in its time window. Every link above returns those calls: * Calls that match after the alert fires, including during the **Cooldown**, aren't added to that alert firing's list. * A deleted call drops out of the list. The record of the alert firing stays. * When your [data retention](/docs/observability/data-retention) policy uses the **Full call record** scope, records of an alert firing are deleted once they're older than the retention period. ### Trigger history On the **Alerts** tab, click an alert's **LAST TRIGGERED** time to open **Trigger history**. It lists each time the alert fired, newest first. Click a row to open its calls in **Call Logs**. | Column | What it shows | | - | - | | **Trigger** | The ID of this alert firing, such as `#1042`. It matches `alert_trigger_id` in the webhook. | | **Triggered at** | When the alert fired, in UTC. | | **Condition** | The alert's threshold when it fired. Later edits don't change it. | | **Calls** | The matching calls, such as `12`. For a **Percentage** alert, the matching calls out of the calls Tuner could check, such as `12 of 40`. | * If **LAST TRIGGERED** shows **Never**, the alert hasn't fired and has no trigger history. * Older alert firings show "Calls weren't saved for older triggers." and can't be opened, because Tuner didn't save their calls. * If the history shows "No triggers within your data retention period.", the alert's trigger records are older than your [data retention](/docs/observability/data-retention) period and were deleted. ## Manage alerts ![Alerts management in Tuner](https://mintcdn.com/tuner/tFS1DAQs-KSnIeEa/images/alerts_management.png?fit=max\&auto=format\&n=tFS1DAQs-KSnIeEa\&q=85\&s=326468a0b421cca460f1c0757ac2d62c) The **Alerts** tab lists each alert with its **RULE NAME**, **CHANNELS**, **STATUS** and **LAST TRIGGERED** time. * **Pause or resume**: use the switch in the **STATUS** column. The status shows **Active** or **Paused**. * **Edit**: click the edit icon, change the alert, then click **Update Alert**. The **Cooldown** shows the alert's saved value. If the cooldown was set through the API to a value that isn't one of the options, such as 30 minutes, it appears as an extra option and is kept unless you pick another. Conditions with nested groups are [read-only](#combine-conditions). * **Delete**: click the delete icon and confirm. This can't be undone. Tuner also deletes the alert's [trigger history](#trigger-history). The calls stay in **Call Logs**. ### Resume a paused alert Tuner pauses an alert when an item its conditions use is deleted. The alert's row shows the reason, for example **Eval deleted. Edit to resume.**, and has no switch. | Reason | The alert is paused when | | - | - | | **Eval deleted** | An eval it uses is deleted, or that delete paused the rule behind a red flag it uses and no other active rule applies the red flag | | **Data extraction field deleted** | A data extraction field it uses is deleted, or that delete paused the rule behind a red flag it uses and no other active rule applies the red flag | | **Voice metric deleted** | A voice metric it uses is deleted, or that delete paused the rule behind a red flag it uses and no other active rule applies the red flag | | **Red flag deleted** | The last active rule that applies its red flag is deleted | If a paused red flag rule caused the pause, [resume that rule](/docs/evaluation/red-flags#resume-a-paused-rule) first. To resume the alert, click **Edit alert to resume** and pick a condition that doesn't use the deleted item. Then click **Save and resume**. If a condition still uses a deleted item or a red flag that no active rule applies, the alert stays paused. Otherwise it's active again. ## Best practices * **Start with high-signal alerts.** Alert on clear, critical problems only, so the important ones don't get ignored. * **Tune thresholds after you see real volume.** Too low creates noise; too high misses issues. **Percentage** mode with a **Minimum calls** value helps when volume varies. * **Route by urgency.** Send critical alerts to a webhook connected to a channel your team watches. Email works for the rest. * **Review regularly.** Revisit your alerts when the agent changes. ## Limits | Limit | Value | | - | - | | Alert name | Up to 100 characters | | Description | Up to 1000 characters | | Conditions per alert | 1 to 10 (exactly 1 in **Percentage** mode) | | Condition value | Up to 500 characters | | Count threshold | 1 to 10000 calls (default 10) | | Percentage threshold | More than 0 up to 100 (default 10) | | Minimum calls (Percentage mode) | 1 to 10000 (default 5) | | Time window | 5 mins, 15 mins, 1 hour (default), 24 hours | | Cooldown (time before the same alert can fire again) | 15 minutes (default), 1 hour, 4 hours, 24 hours | | Email addresses field | Up to 1000 characters | Alerts are also available through the public API, in the **Agent Settings** group of the API Reference, starting with [Create alert definition](/api-reference/agent-settings/create-alert-definition) and [List alert conditions](/api-reference/agent-settings/list-alert-conditions). ## Next steps > [card] [Red flags and labels](/docs/evaluation/red-flags) > > Define the rules you can alert on. > [card] [Webhooks](/docs/integrations/webhooks) > > The `alert.fired` payload and how to set up your endpoint. # Call logs Source: https://docs.usetuner.ai/docs/observability/call-logs Find, filter and open every call your agent handled, import older Retell, Vapi and ElevenLabs calls, and read what each tab on the call details page shows. > [!NOTE] > > **Call Logs** is in the sidebar of every agent. Calls appear here once your agent is connected to Tuner (see the [Quickstart](/docs/getting-started/quickstart)). No other setup is needed. **Call Logs** lists every call Tuner received for the selected agent, newest first. Each row shows how Tuner classified the call. Click a row to open the call details page, where you can play the recording, read the transcript and see the analysis. ![The Call Logs page: the search box, the Diagnose Agent, Import older calls and Filters buttons, and the calls table with intent, outcome, red flag tags, sentiment and duration](https://mintcdn.com/tuner/bavd-UpNNQpDdJnb/images/call-logs-list.png?fit=max\&auto=format\&n=bavd-UpNNQpDdJnb\&q=85\&s=1611c6765c0a43cadb36be2e43176a6e) ## Find a call **1. Open Call Logs** Click **Call Logs** in the sidebar. **2. Search** Type in **Search by Call ID or phone number**. The search runs once you enter at least 3 characters. Clear the box to show all calls again. **3. Filter** Click **Filters** and pick values in any group. The table updates as you select. **4. Open the call** Click a row to open its call details page. To copy a Call ID without opening the call, hover over it and click the copy icon. To remove a filter, click **×** on its chip. **Clear all** removes every filter. The **View calls** links on the [Overview dashboard](/docs/observability/overview) open Call Logs already filtered to failed calls or to calls with red flags. Links from an alert open the calls behind one alert firing; see [See the calls behind an alert](/docs/observability/alerts#see-the-calls-behind-an-alert). ## Import older calls If your agent runs on Retell, Vapi or ElevenLabs, you can pull in calls that happened before you connected it to Tuner. **1. Click Import older calls** On **Call Logs**, click **Import older calls**. Tuner queues an import job and shows a confirmation. **2. Wait for the calls to appear** Tuner fetches the calls from your voice provider and analyzes them like new calls. They appear in the table as they finish. The first import covers the last 3 weeks. Later imports start from the previous import, unless that was more than 3 weeks ago. Only one import can run per agent at a time, and your workspace needs a credit balance to start one. For other providers the button is disabled, with the tooltip "Sync is only available for Retell, Vapi and ElevenLabs agents." ## Table columns | Column | What it shows | | - | - | | **CALL-ID** | The provider's call ID, with the call's date and time below it. A status chip appears next to the time for simulation calls and redacted calls (see [Status chips](#status-chips)). | | **INTENT** | The [call intent](/docs/evaluation/call-classification) Tuner detected. | | **OUTCOME** | The [call outcome](/docs/evaluation/call-classification) Tuner assigned. | | **TAGS** | The [labels and red flags](/docs/evaluation/red-flags) your rules added to the call. | | **SENTIMENT** | The caller's sentiment. | | **ENDED REASON** | Why the call ended, as reported by your voice platform. | | **CUSTOMER NUMBER** | The caller's phone number, when there is one. | | **DURATION** | How long the call lasted. | | **COST** | The call cost reported for the call. | ### Status chips | Chip | Meaning | | - | - | | **Simulated** | The call came from a [simulation run](/docs/simulation/overview). | | **Redacted** | [PII redaction](/docs/observability/pii-redaction) ran on the transcript. | | **Partial** | PII redaction completed for only part of the transcript. | | **Failed** | PII redaction did not complete for this call. | Calls without a chip were not simulated and were not redacted, because PII redaction was off when they arrived. ## Filters The **Filters** panel has six groups. | Group | Options | | - | - | | **DATE & DURATION** | **Date Range**: **Last 24 hours**, **Last 7 days** (default), **Last 30 days**, **Last 90 days** or **Custom date picker**. **Call Duration**: a slider in seconds. | | **CALL INTENT** | The intents defined for this agent. | | **CALL OUTCOME** | The outcomes defined for this agent. | | **SENTIMENT** | Positive, Neutral, Negative or Unknown. | | **LABELS & RED FLAGS** | The labels and red flags your rules can add. | | **ALERT** | The agent's [alerts](/docs/observability/alerts), including paused ones. Pick one or more to see every call that matched them, also during an alert's [cooldown](/docs/observability/alerts#see-the-calls-behind-an-alert). | Your search, filters and page are saved in the page URL, so you can share or bookmark a filtered view. ## Call details The call details page has a header, the recording and transcript on the left, and a set of tabs on the right. ![A call's details page: the header with cost and TTFB, the Overview, Evals, Voice Metrics, Data Extraction and Traces tabs, the player and transcript with latency badges, and the side panel with red flags, labels, sentiment and AI models](https://mintcdn.com/tuner/bavd-UpNNQpDdJnb/images/call-details.png?fit=max\&auto=format\&n=bavd-UpNNQpDdJnb\&q=85\&s=d6f736a1d939b89b87d3b4f3c5748857) The header shows the Call ID (with a copy button), the intent and outcome, the duration, date and time, the caller's number, the reason the call ended (**Ended:**), the **COST**, and the **TTFB P50** and **TTFB P90** response times. A status chip appears next to the Call ID when one applies. For a simulation call, the header also shows the Scenario or the replayed Dataset call. The transcript shows each turn with its latency badges. See [Voice metrics](/docs/observability/voice-metrics#per-turn-latency-in-the-transcript) for what each badge means. ### Tabs | Tab | What it shows | | - | - | | **Overview** | **Red Flags**, **Labels** and **Sentiment** for the call, plus **Call Metadata** when your integration sent it. | | **Evals** | Each [eval](/docs/evaluation/overview) result: **PASS**, **FAIL**, a score such as `4/5`, or **N/A** when there's no result, with the evidence behind it. | | **Voice Metrics** | Response time (TTFB p50 and p90), latency by stage, and the longest agent monologue. On replay calls, also [transcription accuracy](/docs/observability/voice-metrics#transcription-accuracy). See [Voice metrics](/docs/observability/voice-metrics). | | **Data Extraction** | The values Tuner extracted into your [data extraction fields](/docs/evaluation/data-extraction). | | **Traces** | The OpenTelemetry span tree for the call. This tab appears only when the call has a trace. See [OpenTelemetry Traces](/docs/observability/traces). | ### Call Metadata The **Call Metadata** section on the **Overview** tab shows the metadata your integration sent with the call. Each group appears only when it has data. | Group | What it shows | | - | - | | **AI Models** | The **STT**, **LLM** and **TTS** models used on the call. | | **AI Usage** | Usage and cost counters: **STT duration**, **LLM tokens**, **TTS characters**, **Input tokens**, **Output tokens**, **LLM cost** and **Voice cost**. | | **Extra Metadata** | Any other keys you sent, shown as JSON. | How to send metadata depends on your integration. See the [LiveKit](/docs/integrations/livekit), [Pipecat](/docs/integrations/pipecat) or [SDK quickstart](/docs/integrations/custom-stack/sdk-quickstart) page, or the `metadata` field of [Create call](/api-reference/calls/create-call). ### Calls removed by retention When your [data retention](/docs/observability/data-retention) policy has erased part of a call, the call details page says so: * A banner reads **Retention policy:** followed by the erasure scope, and explains what was removed. * A **Recording removed** card replaces the audio player. * The transcript area shows **Transcript removed**, or **Transcript and caller data removed**. * If caller data was removed, the header shows **Number removed**, and the **Evals** and **Data Extraction** tabs mark evidence notes and field values as removed. Calls erased with the **Full call record** scope are deleted and no longer appear in **Call Logs**. ## Limits | Limit | Value | | - | - | | Minimum search length | 3 characters | | Rows per page | 10 (default), 20, 30 or 50 | | Call Duration filter range | 0 to 1200 seconds | | Import older calls | Retell, Vapi and ElevenLabs agents only; up to the last 3 weeks; one import per agent at a time | Call Logs data is also available through the public API, in the **Calls** group of the API Reference: [List calls](/api-reference/calls/list-calls), [Get call](/api-reference/calls/get-call) and [List filter options](/api-reference/calls/list-filter-options). ## Next steps > [card] [Find the root cause of a failing call](/docs/observability/root-cause-analysis) > > Work through a single problem call using the call details page. > [card] [Voice metrics](/docs/observability/voice-metrics) > > Read the per-turn latency badges and the Voice Metrics tab. # Data retention Source: https://docs.usetuner.ai/docs/observability/data-retention Set how long Tuner keeps call data and what gets erased when a call expires, for every agent in your workspace. > [!NOTE] > > Data retention is set at the **workspace level**, in **Workspace Settings > Data & privacy**, so every agent uses the same policy. The periods and erasure options you can pick depend on your plan. See [Plan availability](#plan-availability). ## What is data retention? Data retention is how long Tuner keeps the data from a call before deleting it. Every call leaves data behind: the transcript, the recording, the caller's phone number, and the analysis Tuner generated from them. If you work in a regulated industry such as healthcare, finance or legal, you often can't keep that data indefinitely. A retention policy puts a fixed expiry on it: you choose how long call data lives and what gets erased when it expires, within the limits of your plan. ## How retention works A policy has two parts. The **Retention period** sets how long a call is kept. **What to erase** sets which parts of the call are deleted once that period is up. The period starts when Tuner receives the call. Once a call passes it, Tuner erases it automatically at the scope in effect. Erasure is permanent: deleted data can't be recovered. New workspaces start with their plan's default policy. Workspaces created before data retention was available keep their calls indefinitely until someone changes the setting. ## Retention periods The **Retention period** options are 7 days, 14 days, 30 days, 90 days, 6 months and 1 year, plus **Never (keep indefinitely)**, which turns automatic deletion off. **Never** is available on the Enterprise plan only. Pick the shortest period that still covers how your team works: long enough to review and report on calls, short enough to meet your compliance policy. ## What to erase The erasure scope controls how much of the call is removed when it expires. All three scopes delete the transcript and the recording. | Scope | What is removed | What is kept | | - | - | - | | **Transcript & recording** | The call transcript and the recording | Phone number, extracted field values, analysis results and eval scores | | **Transcript, recording & caller data** *(Recommended)* | Everything above, plus the caller's phone number, extracted field values and AI-generated evidence notes | Outcomes, intent labels and eval scores | | **Full call record** | The entire call record | Nothing | **Transcript, recording & caller data** is marked **Recommended**. It removes the verbatim and caller-identifying content and keeps the outcome labels, intent labels, eval scores, usage and cost data, so reporting on expired calls still works. When a call is erased, Tuner deletes the recording files it stored for the call and the raw call payload it received from your voice platform, as well as the recording link. ## Set up data retention **1. Open Data & privacy** Go to **Workspace Settings**, open the **Data & privacy** tab, and find the **Data retention** section. **2. Choose a retention period** Open the **Retention period** dropdown and pick how long calls are kept. Options your plan doesn't include are shown but disabled, with an **Available on** note naming the plan that includes them. ![The Retention period dropdown open, showing 7 days, 14 days, 30 days, 90 days, 6 months, 1 year, and a locked Never option](https://mintcdn.com/tuner/DzmBrhYxYZMOJoGD/images/workspace-dataRetention-periods.png?fit=max\&auto=format\&n=DzmBrhYxYZMOJoGD\&q=85\&s=7d2114cac98f0e8b3c5e93c550d3e2a2) **3. Choose what to erase** Under **What to erase**, select what is deleted when a call reaches the end of its retention period. If you chose **Never (keep indefinitely)**, there's nothing to erase and these options are disabled. ![The Data retention section showing the retention period selector and the three erasure scope options](https://mintcdn.com/tuner/DzmBrhYxYZMOJoGD/images/workspace-dataRetention.png?fit=max\&auto=format\&n=DzmBrhYxYZMOJoGD\&q=85\&s=144f21a77e0d0b3fe0c67a94eb5b4e79) **4. Save changes** Click **Save changes**. If the new period is shorter than the current one, Tuner asks you to confirm in a **Shorten retention period?** dialog, because existing calls older than the new period will be erased. Click **Save changes** again to confirm. ## Plan availability Your plan sets both the retention periods and the erasure scopes you can choose from. | Plan | Retention periods | What to erase | | - | - | - | | **Pay-as-you-go** | 30 days | Full call record | | **Builder** | 30 or 90 days | Any of the three | | **Growth** | 7 days to 1 year | Any of the three | | **Enterprise** | 7 days to 1 year, or Never | Any of the three | On **Pay-as-you-go** there is nothing to configure. Calls are kept for 30 days, then the full call record is erased. On **Builder** you can set the period to 30 or 90 days and pick any of the three erasure scopes. On **Growth** you can set any period from 7 days to 1 year, again with any of the three erasure scopes. **Enterprise** also includes **Never (keep indefinitely)**, the one option that keeps call data instead of erasing it. Periods and scopes outside your plan are visible but disabled, with a **View plans** link. ## Common questions > [accordion] Can I turn data retention off? > > Only by choosing **Never (keep indefinitely)**, which is available on Enterprise. Workspaces created before data retention was available also keep calls indefinitely until the setting is changed. > [accordion] How do I keep call data for longer? > > Pick a longer period, if your plan has one. Builder goes up to 90 days, Growth up to 1 year, and Enterprise includes **Never (keep indefinitely)**. Calls that were already erased don't come back when you change the period. > [accordion] Does the policy apply to calls I already have? > > Yes. The policy covers every call in the workspace, including calls that were there before you saved it. Calls older than the period you set are erased. > > This matters most if you shorten the period. Going from 90 days to 30 days erases the calls between those two marks, so export anything you still need before you save. > [accordion] When is a call erased? > > Once it passes its retention period, counted from when Tuner received it. Erasure runs as a background job once a day, so a call can stay in Tuner for up to a day after it expires. > [accordion] Can an erased call be recovered? > > No. Erasure is permanent and there is no restore. Extending the period later doesn't bring erased data back. > [accordion] If I change the scope, are already-erased calls erased again? > > No. Erasure is forward-only. Each call is erased once, at the scope in effect at that time. A call erased with **Transcript & recording** stays that way even if you later choose **Full call record**. The new scope applies to calls that expire from then on. > [accordion] How do I know a call was erased? > > The call details page shows a **Retention policy:** banner with the scope that was applied, and a **Recording removed** card in place of the audio player. Calls erased with **Full call record** no longer appear in [Call Logs](/docs/observability/call-logs#calls-removed-by-retention). > [accordion] Will my dashboards and reports lose data? > > That depends on the scope. **Transcript, recording & caller data** keeps outcome labels, intent labels, eval scores, usage and cost data, so reporting still works for expired calls even though you can't open the transcript. **Transcript & recording** keeps the analysis results and eval scores as well. > > **Full call record** removes the call completely, so expired calls drop out of your counts and trends. > [accordion] Is the recording also deleted from my voice platform? > > No. Tuner deletes the recording files it stored and the call payload it received from your platform. Any copy kept by your voice platform or telephony provider follows that platform's own retention settings, so set a matching policy there if you need the call gone everywhere. > [accordion] Do I still need PII redaction if I have a retention policy? > > They cover different things. [PII redaction](/docs/observability/pii-redaction) replaces sensitive details in transcripts when a call arrives. A retention policy limits how long call data is kept. With retention alone, the full transcript stays in Tuner for the whole period. With redaction alone, redacted transcripts are kept for as long as your policy allows. > [accordion] Are simulation calls affected? > > No. Simulation calls are never deleted by the retention policy. > [accordion] Are Dataset calls affected? > > No. A [Dataset call](/docs/datasets/overview) keeps its own copy of the caller's audio and transcript, and retention doesn't remove it, even after its source call is erased. Delete Dataset calls you no longer need from the **Dataset** tab. > [accordion] Can I set a different policy for one agent? > > No. The policy is set once per workspace and every agent uses it. > [accordion] What happens to my policy if I change plans? > > If your current period or scope isn't available on the new plan, Tuner switches your workspace to the new plan's default policy. When that means a shorter period, more of your existing calls fall outside it and are erased, so export anything you need before you downgrade. Retention settings are also available through the public API, in the **Workspaces** group of the API Reference: [Get data retention](/api-reference/workspaces/get-data-retention) and [Update data retention](/api-reference/workspaces/update-data-retention). ## Next steps > [card] [PII redaction](/docs/observability/pii-redaction) > > Replace sensitive details in transcripts as calls arrive. > [card] [Call Logs](/docs/observability/call-logs) > > See which calls were erased by your policy. # Dashboards Source: https://docs.usetuner.ai/docs/observability/overview The dashboards Tuner gives each agent: the Overview dashboard with headline metrics, breakdowns and recent red flags, and the Performance Analysis, Eval Analysis and simulation Analytics dashboards. > [!NOTE] > > **Overview** is the first item in the agent sidebar. It needs calls from a connected agent, and the outcome, intent and red flag numbers depend on the [call classification](/docs/evaluation/call-classification) and [red flag rules](/docs/evaluation/red-flags) you've set up. Each agent has an **Overview** dashboard for a daily health check, and analysis dashboards for a closer look. See [Analysis dashboards](#analysis-dashboards). ## Overview The **Overview** dashboard summarizes your agent's performance over the period you select. Use it to tell whether the agent is broadly healthy with isolated issues, or degraded across the board. ![Tuner Overview Dashboard](https://mintcdn.com/tuner/tFS1DAQs-KSnIeEa/images/overview_dashboard.webp?fit=max\&auto=format\&n=tFS1DAQs-KSnIeEa\&q=85\&s=62ac37b3fc18eb19f260adba2adcbe64) ### Headline metrics Five metrics sit at the top. Pick the period with the **7 days**, **30 days** or **90 days** buttons. Each card also shows the change against the previous period of the same length. | Metric | What it is | What to look for | | - | - | - | | **Total Calls** | Calls your agent handled in the period | A sudden drop can mean an integration broke, as well as lower traffic | | **Success Rate** | Share of calls whose outcome is a success type | Compare against the previous period | | **Failed Calls** | Calls whose outcome is a failure type | A higher count with a stable success rate usually means volume grew | | **Calls with Red Flags** | Calls that have at least one red flag | Any rise is worth a look in the red flag list below | | **Red Flag Rate** | Share of calls with at least one red flag | A rising rate means more of your calls trip your rules | When there are matching calls, **Failed Calls** and **Calls with Red Flags** show a **View calls** link that opens [Call Logs](/docs/observability/call-logs) filtered to those calls. Success Rate and Failed Calls depend on how you've defined [call outcomes](/docs/evaluation/call-classification). If these numbers look wrong, check those definitions before debugging the agent. Simulation calls are not counted in the Overview metrics. > [!NOTE] > > Per-call values like duration and cost aren't headline metrics. They appear on each call in **Call Logs**, and you can use them as conditions in [red flag rules](/docs/evaluation/red-flags#condition-sources). ### Breakdowns Two charts show how calls are spread across your own definitions: * **Call Intent Breakdown**: the mix of reasons people called. * **Call Outcome Breakdown**: the mix of results. Read them together. An intent with high volume and a poor outcome share is where to spend your time first. The [MCP diagnosis](/docs/mcp/diagnose) follows the same reasoning. ### Recent red flags The **Recent Red Flags** table lists recent calls that tripped one of your rules, with the **FLAG TYPE**, **CALL ID**, **CALL INTENT**, **OUTCOME** and **TIMESTAMP**. Click **View** to open the call. See [Red flags and labels](/docs/evaluation/red-flags#triage-red-flags) for how to work through the list. Red flags only appear here if you've defined rules. An empty list on a busy agent usually means no rules exist yet. ### Diagnose your agent A banner at the top of the dashboard reads "Run a full diagnosis to trace red flags, hallucinations and latency back to a root cause." Click **Diagnose Agent** to open the **Diagnose agent** dialog. It shows how to connect Tuner to your AI client and gives you a prompt to paste there, already filled in with your agent and workspace IDs. The same button is on **Call Logs**. The button is disabled until the agent has calls. See [Diagnose your agent](/docs/mcp/diagnose) for the full workflow. ## Analysis dashboards Three more dashboards hold detailed charts for the selected agent: | Dashboard | Where to find it | What it's for | | - | - | - | | **Performance Analysis** | Sidebar | Call patterns and performance metrics over time | | **Eval Analysis** | Sidebar | Eval results, compliance and performance patterns | | **Analytics** | **Simulations > Analytics** | Results across your simulation runs | ## Next steps > [card] [Call Logs](/docs/observability/call-logs) > > Search, filter and open the calls behind the numbers. > [card] [Diagnose your agent](/docs/mcp/diagnose) > > Use the MCP to find why something is wrong across every affected call. # PII redaction Source: https://docs.usetuner.ai/docs/observability/pii-redaction Detect sensitive personal information in call transcripts and replace it with typed placeholders before Tuner analyzes the call. > [!NOTE] > > PII redaction is available on the **Growth plan** and is set at the **workspace level**, in **Workspace Settings > Data & privacy**. It applies to every agent in the workspace. ## What is PII? PII stands for **personally identifiable information**: details that identify a specific person, such as their name, phone number or credit card number. Callers often say these out loud, so they end up in your call transcripts. PII redaction finds these details in each transcript and replaces them with a typed placeholder, such as `[NAME]` or `[ADDRESS]`. This matters most for sensitive calls, such as in healthcare or finance. ## How redaction works When redaction is on, Tuner redacts the transcript of each new call before it analyzes the call. The redacted transcript is stored in place of the original. Because analysis runs on the redacted transcript, what Tuner shows afterwards, including the outcome, intent, eval results and the evidence they cite, uses the placeholders. Redaction applies to transcripts. Call recordings are not redacted. ## Turn on redaction **1. Open Data & privacy** Go to **Workspace Settings** and open the **Data & privacy** tab. **2. Turn on PII redaction** Turn on the switch next to **PII redaction**. **3. Choose what to redact** Under **Categories to redact**, select the categories you want. All of them are selected by default, and at least one must stay selected. ![Data & privacy tab showing the PII redaction switch and the list of categories to redact](https://mintcdn.com/tuner/X5QfXXe9LUP5m1J4/images/workspace-dataRedaction.png?fit=max\&auto=format\&n=X5QfXXe9LUP5m1J4\&q=85\&s=fd92f85306ae29c4f347d0f093a4dcae) **4. Save changes** Click **Save changes**. Redaction applies to calls that arrive from this point on. If your plan doesn't include PII redaction, the card shows "PII redaction isn't included in your current plan." and the switch is disabled. Click **View plans** to see the plans that include it. ## What Tuner can redact Each detected entity is replaced with the placeholder shown here. | Category | Example caught | Replaced with | | - | - | - | | **Full name** | "my name is Sarah Thompson" | `[NAME]` | | **Phone number** | "call me on 07700 900123" | `[PHONE_NUMBER]` | | **Email address** | "it's [sarah@email.com](mailto:sarah@email.com)" | `[EMAIL]` | | **Physical address** | "I'm at 42 Baker Street, London" | `[ADDRESS]` | | **SSN / National ID** | "my social is 123-45-6789" | `[SSN]` | | **Credit / debit card number** | "the card ending 4111 1111 1111 1111" | `[CREDIT_CARD]` | | **PIN & passwords spoken aloud** | "my PIN is four eight two one" | `[PIN]` | ## Redaction status on each call Each call that went through redaction shows a status chip next to its Call ID, in [Call Logs](/docs/observability/call-logs#status-chips) and on the call details page. | Chip | Meaning | | - | - | | **Redacted** | The transcript was redacted. | | **Partial** | Redaction completed for only part of the transcript. | | **Failed** | Redaction did not complete for this call. | Calls without one of these chips were not redacted: they came in while redaction was off, or they are simulation calls, which show **Simulated** instead. ## What a redacted call looks like In the transcript, redacted details appear as placeholders in place of the original words. Everything else about the call, including timing and voice metrics, stays the same. ![Call transcript with a spoken address replaced by \[ADDRESS\] placeholders, alongside normal latency badges](https://mintcdn.com/tuner/xq-rKtH5VjBLG9ty/images/call-dataRedaction.png?fit=max\&auto=format\&n=xq-rKtH5VjBLG9ty\&q=85\&s=8107b644bf52ce7b725480bbad80eaf2) ## Good to know * **Workspace-wide.** Redaction applies to every agent in the workspace. There is no per-agent setting. * **Not retroactive.** Only calls that arrive after you turn redaction on are redacted. Existing transcripts are not changed, and redaction can't be undone on a call that was already redacted. * **Simulation calls are excluded.** Generated simulations contain no real caller data. [Replays of Dataset calls](/docs/simulation/replays) play a real caller's recorded audio, and their transcripts aren't redacted either. Reference transcripts you edit are stored as you typed them. Only add calls to your [Dataset](/docs/datasets/overview) that you're allowed to reuse for testing. PII redaction settings are also available through the public API, in the **Workspaces** group of the API Reference: [Get PII redaction](/api-reference/workspaces/get-pii-redaction) and [Update PII redaction](/api-reference/workspaces/update-pii-redaction). ## Next steps > [card] [Data retention](/docs/observability/data-retention) > > Set how long call data is kept before it's erased. > [card] [Call Logs](/docs/observability/call-logs) > > See the redaction status of each call. # Find the root cause of a failing call Source: https://docs.usetuner.ai/docs/observability/root-cause-analysis How to use the call details page to work out why a single call went wrong, and where to go when the problem spans many calls. > [!NOTE] > > You work from the call details page, which you open from [Call Logs](/docs/observability/call-logs) or the **Recent Red Flags** table on the [Overview dashboard](/docs/observability/overview). ## What is a root cause analysis? A root cause analysis goes past spotting that a call failed and works out why it failed. Once you know the cause, you can fix it so the problem doesn't come back. Do one when: * A critical red flag is triggered, such as a hallucination or a missed disclosure. * A user reports a poor experience. * You notice the same issue in several calls in **Call Logs**. ## Analyze a call **1. Open the call** In **Call Logs** or **Recent Red Flags**, click the call to open its details page. **2. Read the transcript** Read the conversation on the left to understand the context. Pay close attention to the turns leading up to the issue, and play the recording if the words alone don't explain it. **3. Check the tabs** Use the tabs on the right: * **Overview**: the red flags, labels and sentiment for the call. * **Evals**: which evals failed, and the evidence each one cites. * **Voice Metrics**: response time and latency by stage. Look for slow turns or a long agent monologue. On a replay call, it also shows transcription accuracy. See [Voice metrics](/docs/observability/voice-metrics). * **Data Extraction**: the values Tuner extracted, to check whether the agent captured the right details. **4. Open the trace when the problem is timing** If the call has a **Traces** tab, open it. The span tree shows the operations behind each turn, so you can tell whether a slow turn was the model, the synthesis or a tool call waiting on your backend. See [OpenTelemetry Traces](/docs/observability/traces). **5. Form a hypothesis** Based on what you found, decide what caused the issue. For example: "The agent hallucinated because the prompt was ambiguous," or "The agent skipped the disclosure because the instruction was missing from the prompt." **6. Check it against other calls** Look for other calls with the same issue in **Call Logs**, using search and filters. If your hypothesis explains them too, you've likely found the cause. ![A call's details page with the Overview, Evals, Voice Metrics, Data Extraction and Traces tabs, the transcript, and the red flags and labels on the call](https://mintcdn.com/tuner/bavd-UpNNQpDdJnb/images/call-details.png?fit=max\&auto=format\&n=bavd-UpNNQpDdJnb\&q=85\&s=d6f736a1d939b89b87d3b4f3c5748857) > [!TIP] > > **Prove the fix.** Add the call to your [Dataset](/docs/datasets/overview), then replay it after you change your agent. The caller says exactly the same thing on every replay, so if it now passes your evals, your fix worked. ## When part of the analysis is missing Tuner analyzes each call in several steps: outcome, intent, data extraction and evals. If one of the intent, data extraction or eval steps fails, the other steps still complete, and their results appear as usual. The results of the failed step are missing from the call. The [Get call](/api-reference/calls/get-call) response lists which steps failed. [Alerts](/docs/observability/alerts) are not checked for a call while any of its steps has failed. ## Common root causes | Cause | What it looks like | | - | - | | **Ambiguous prompt** | The agent's instructions weren't clear, so it behaved in an unexpected way. | | **Speech recognition or understanding errors** | The agent misheard or misunderstood the caller. | | **Integration issues** | A backend system or API the agent depends on failed or responded slowly. | ## Diagnose across all calls Manual analysis is the right tool for one call. To find the cause of a pattern across many calls, such as why one intent keeps failing, use the MCP diagnosis. It reads your calls, red flags and eval results in bulk, finds the pattern and tells you what to fix. Start it from **Diagnose Agent** on the Overview dashboard or in **Call Logs**. ## Next steps > [card] [Diagnose your agent](/docs/mcp/diagnose) > > Analyze patterns across all your calls and get fix recommendations. > [card] [OpenTelemetry Traces](/docs/observability/traces) > > See which operation inside a slow turn took the time. # OpenTelemetry traces Source: https://docs.usetuner.ai/docs/observability/traces Send OpenTelemetry spans from LiveKit Agents, Pipecat, or a custom stack to Tuner and read them as a span tree on the matching call. > [!NOTE] > > Traces appear on the **Traces** tab of a call in **Call Logs**. The LiveKit Python SDK and the Pipecat SDK forward spans for you. Any other stack can send spans over OTLP/HTTP. See [Turn on traces](#turn-on-traces). ## Where traces fit [Voice Metrics](/docs/observability/voice-metrics) tells you which turn was slow and which stage dominated it, on every call and with no setup. A trace tells you what ran inside that stage: the model request, the streaming adapter, each tool call. Use it when the stage number does not explain the delay. An LLM stage that was really a slow tool call looks the same as a slow model in a stage breakdown. In a span tree, the tool call span shows the time. ## Reading the span tree Tuner renders the trace against a time axis, with each bar positioned relative to the start of the session. ![Traces tab showing a span tree with agent_session as the root and nested agent_turn, llm_node, llm_request, tts_node, and user_turn spans, each with a duration and a bar on a shared time axis](https://mintcdn.com/tuner/jSC31eAGS2DXVab0/images/call-traces.png?fit=max\&auto=format\&n=jSC31eAGS2DXVab0\&q=85\&s=2e1f87da1d32a07321e4a9e37b2a68bb) * **Follow the widest bar at each level.** Above, `agent_turn` is 4.84s and the `tts_node` under it is 4.62s, so synthesis took most of that turn. * **Siblings overlap.** `llm_node` and `tts_node` both start at 00:00, because synthesis streams on the first tokens. Children do not sum to their parent, the same way the pipeline stages do not sum to TTFB. * **Collapse large traces.** The call above has 171 spans. Collapse to the turn level, then expand the one turn you care about. Click a span to open its details. ![Span detail panel showing the Span, Timing, Status, Attributes, and Resource groups for a turn span lasting 11.52 seconds](https://mintcdn.com/tuner/jSC31eAGS2DXVab0/images/call-traces-span-detail.png?fit=max\&auto=format\&n=jSC31eAGS2DXVab0\&q=85\&s=b9ddbc75c3d2c5bafabef2ef14e76ffe) Span names come from your framework. See [LiveKit traces](/docs/integrations/livekit#opentelemetry-traces) or [Pipecat traces](/docs/integrations/pipecat#opentelemetry-traces). ## Turn on traces Setup lives with your integration. > [card] [LiveKit traces](/docs/integrations/livekit#opentelemetry-traces) > > Install the `traces` extra of `tuner-livekit-sdk` (Python, 0.1.10 or later). > [card] [Pipecat traces](/docs/integrations/pipecat#opentelemetry-traces) > > Install the `traces` extra of `tuner-pipecat-sdk` (0.2.8 or later) and set `enable_tracing=True`. > [card] [Custom stack traces](/docs/integrations/custom-stack/direct-api#opentelemetry-traces) > > Export spans from any stack with an OTLP HTTP exporter. On LiveKit and Pipecat, the SDK sends spans with the API key you already configured and tags each span with the call's ID. `forward_traces` defaults to `True` on both SDKs; pass `forward_traces=False` to stop. A **Traces** tab appears on the call once spans have arrived and matched. Calls with no trace show no tab. ## How spans are matched to a call Tuner matches a trace to a call on the `tuner.call_id` span attribute. The value must equal the `call_id` you sent with the call. Only one span in the trace needs the attribute; Tuner applies it to the whole trace, including spans that arrived earlier. Spans can arrive before or after the call. Tuner stores them and links them when both are present. The SDKs set the attribute for you. ## Ingest requirements These apply when you send spans yourself. The SDKs already meet them. | Requirement | Value | | - | - | | Endpoint | `POST https://api.usetuner.ai/api/v1/traces` | | Protocol | OTLP over HTTP with protobuf encoding (`Content-Type: application/x-protobuf`). gRPC and OTLP/JSON are not accepted. | | Authentication | `Authorization: Bearer tr_api_...` with a workspace API key. See [API keys](/docs/getting-started/api-keys). | | Workspace | The workspace must have at least one agent with provider **Custom API**, **LiveKit**, **Pipecat** or **Dograh**. Otherwise spans are rejected. | | Maximum request body | 4 MB | | Call match | A `tuner.call_id` attribute on at least one span in the trace | ## What Tuner stores | | | | - | - | | **Stored** | The span tree: names, timings, parent relationships, status. Metrics and configuration attributes: model names, time to first byte, token counts, turn latency, endpointing settings, tool names and outcomes. | | **Not stored** | Conversation content. Transcripts, LLM inputs and outputs, TTS text, system prompts, and tool call arguments and results are discarded on arrival. | The attribute filter is an allowlist, so a framework upgrade cannot start sending content that Tuner then keeps. Expect around 30 KB per five-minute call. > [!NOTE] > > Traces are separate from the call record, which is still governed by [PII Redaction](/docs/observability/pii-redaction) and [Data Retention](/docs/observability/data-retention). ## Next steps > [card] [Voice metrics and latency](/docs/observability/voice-metrics) > > The per-turn stage breakdown you start from before opening a trace. > [card] [Root cause analysis](/docs/observability/root-cause-analysis) > > Working through a single failing call end to end. # Voice metrics and latency Source: https://docs.usetuner.ai/docs/observability/voice-metrics How Tuner measures the latency of each turn and each pipeline stage (EOU, STT, LLM and TTS), how it scores transcription accuracy on replay calls, and where to read both on a call. > [!NOTE] > > **No setup required for latency.** Tuner captures per-turn latency and voice metrics for every call once your agent is connected. Which stages you see depends on what your voice platform or SDK reports (see [Provider variation](#provider-variation)). > > **Transcription accuracy** appears only on calls from a [replay](/docs/simulation/replays) of a Dataset call. ## How Tuner measures a call A single end-to-end latency number hides where the time went. Tuner breaks each turn of the conversation into its pipeline stages and shows the timing per turn, per stage and across the call. You read it in two places on the [call details page](/docs/observability/call-logs#call-details): * **The transcript**: latency badges on each turn. * **The Voice Metrics tab**: response time at p50 and p90, latency by stage, the longest agent monologue and, on replay calls, [transcription accuracy](#transcription-accuracy). ## Pipeline stages Every agent response passes through four stages, each measured on its own: **EOU**, **STT**, **LLM** and **TTS**. The stages overlap in real time. Speech-to-text runs while the customer is still talking, and endpointing runs alongside transcription. Because of this, the stage timings don't add up to the total response latency. The **Voice Metrics** tab shows each stage as its own bar on a shared time axis so you can compare them. ![Voice Metrics tab showing EOU, STT, LLM and TTS latency ranges on a shared axis, with p50 and p90 for each stage](https://mintcdn.com/tuner/-VzrpkorJtB1cCIE/images/voice_metrics.png?fit=max\&auto=format\&n=-VzrpkorJtB1cCIE\&q=85\&s=ca8b7cf4145b22cd9bdca1ae7977c0b3) | Stage | What it measures | What to look for | | - | - | - | | **EOU** (end of utterance) | How long the system waited, after the customer stopped speaking, before deciding the turn was over | High EOU on a turn where the customer paused mid-thought usually means the endpointer waited out a silence timeout. High EOU across the whole call points at conservative endpointing settings. | | **STT** (speech-to-text) | Time from when the customer stopped speaking until the transcript was finalized | High STT on every turn points at the STT provider or the network path to it. High STT on a few turns often means a long utterance or poor audio. | | **LLM** | Time from the first LLM call to the first token sent to TTS: how quickly the model started producing speakable output | LLM time that grows over the call usually means the growing conversation history is slowing the model. A single slow turn often means a tool call. | | **TTS** (text-to-speech) | Time from the first token received to the first audio byte from the TTS service | High TTS can mean TTS provider latency or network issues. Low TTS with high overall latency means the bottleneck is elsewhere. | > [!NOTE] > > The exact point each stage is measured from can vary by integration. See your framework's integration page for details. ## Read the stage breakdown For each stage, the **Voice Metrics** tab draws a bar from p50 to p90 on a shared time axis: * **p50** (median): the typical turn for that stage. * **p90** (90th percentile): the slow tail. Nine out of ten turns were faster than this. The length of each bar matters as much as its position. A stage that sits at 300 ms at p50 but reaches 900 ms at p90 is inconsistent, and that is often a bigger problem than a stage that is steadily slow. A short bar means the stage is predictable. A long one means something makes it spike, so look there first. If the call has no per-stage data, the tab shows "Stage latency not available for this call." To see whether a change, like a new speech-to-text provider or model, made a stage faster, replay the same [Dataset calls](/docs/datasets/use-cases/benchmarking) before and after it. The caller audio is identical on every run, so any difference comes from your change. ## TTFB: time to first byte **TTFB** is the delay the customer experiences: the time from the end of the customer's speech to the start of the agent's speech. TTFB is measured directly. It isn't the sum of the four stages, which overlap. The stage breakdown explains where the delay came from by showing which stage was slowest and which varied most. Under **TIME TO FIRST BYTE**, the tab shows **TTFB p50** and **TTFB p90**, each with a rating: | Rating | TTFB | | - | - | | **Good** | Under 1.5 s | | **Moderate** | 1.5 s to 2.5 s | | **Slow** | Over 2.5 s | A good p50 with a slow p90 means most turns are fine but some are much slower, often because of a few slow tool calls or long model turns. The call header also shows **TTFB P50** and **TTFB P90**. ## Per-turn latency in the transcript The transcript shows latency badges on each turn, so you can see where in the conversation the delay happened. Hover over a badge to see what it measures. ![Transcript showing per-turn latency badges for agent and customer turns, plus a Node Transition and tool call](https://mintcdn.com/tuner/-VzrpkorJtB1cCIE/images/transcript_latency_metrics.png?fit=max\&auto=format\&n=-VzrpkorJtB1cCIE\&q=85\&s=3850231fc0226d494abb5b91dda64f9a) ### Agent turns | Badge | What it measures | | - | - | | **Latency** | End-to-end response latency for this turn, from the end of the customer's speech to the start of the agent's speech. Its color follows the TTFB rating above. | | **STT** | Time from when the customer stopped speaking until the transcript was finalized | | **LLM** | Time from the first LLM call to the first token sent to TTS | | **TTS** | Time from the first token received to the first audio byte from TTS | An agent turn that the customer cut off is marked **Interrupted**. ### Customer turns | Badge | What it measures | | - | - | | **STT** | Time from when the customer stopped speaking until the transcript was finalized | | **EOU** | Endpointing delay before the turn was considered complete | ### Node transitions When the agent moves between workflow nodes, a **Node Transition** row appears in the transcript between the customer's message and the agent's response. Expand it to see which nodes were entered. This helps with agents built on graph-based or stateful workflows: you can see when the agent changed state and compare it with any change in latency. ### Tool calls When the agent calls a tool, a row appears in the transcript at the moment of the call, with the tool name and how long it took. Expand it to see the **Input** and the **Output** (or **Error**). Tool time falls inside the LLM stage for that turn, so if a turn has a high **LLM** value, check its tool calls first. ## Provider variation The stages available, and how precise they are, depend on your voice platform and stack. Not every platform reports all four stages separately. Some report only a combined latency, and EOU is only available from stacks that report it, such as the Tuner LiveKit and Pipecat SDKs. When a stage isn't reported, Tuner leaves it out of the breakdown instead of showing it as zero. If a turn shows only a **Latency** badge, your platform isn't reporting per-stage timing for that turn. ## Conversation metrics Under **CONVERSATION**, the tab shows **Longest agent monologue**: the longest uninterrupted agent response in the call. Long monologues make it more likely that the customer disengages. | Rating | Longest agent monologue | | - | - | | **Good** | Under 15 s | | **Moderate** | 15 s to 30 s | | **Long** | Over 30 s | Other call-level signals, such as sentiment, are captured as data extraction fields. See [Predefined evals](/docs/evaluation/predefined-evals) for what Tuner checks out of the box. ## Transcription accuracy Transcription accuracy shows how well your agent's speech-to-text heard a replayed caller. Tuner compares the reference transcript of each caller turn in the Dataset call with what your agent's transcript shows the caller said, and scores the difference as a word error rate. The card appears at the top of the **Voice Metrics** tab, on calls from a [replay](/docs/simulation/replays#transcription-accuracy) only. Tuner scores the call once it ends. ### Read the card ![The Transcription accuracy card showing a 96.5% score rated Good, counts of misheard, missed and added words, the verification line, and the What went wrong list](https://mintcdn.com/tuner/Z16wBZIv2BPLqt5V/images/transcription-accuracy-card.png?fit=max\&auto=format\&n=Z16wBZIv2BPLqt5V\&q=85\&s=af6cf185c77c44dca877f247576ec87a) | Part of the card | What it shows | | - | - | | **Score** | The share of words your agent heard correctly, as a percentage, with a **Good**, **Fair** or **Poor** badge. | | **Misheard** | Words the agent's transcript has instead of the words the caller said. | | **Missed** | Words the caller said that the agent's transcript doesn't have. | | **Added** | Words in the agent's transcript that the caller didn't say. | | **Words compared** | How many words the reference transcripts have. | | Speech-to-text line | The speech-to-text provider and model your agent used, when the call reports them. | | **Last verified** | When a caller turn's transcript was last verified. | | Verification line | How many caller turns have a verified transcript. See [Verification line](#verification-line). | | **What went wrong** | One row per mismatch, with **Caller said** next to **Replay heard**. Hidden when the score is 100%. | | **Reference transcript** | The reference transcript of each caller turn, with its **Draft** or **Verified** state. Collapsed by default. | If your agent's call ended before every caller turn played, the card says **Call ended early** and how many turns were scored, for example **scored 3 of 5 turns**. The score is the share of reference words that aren't misheard, missed or added. Tuner compares all the caller turns that played against everything your agent transcribed from the caller as one text, so where your agent's speech-to-text splits the audio doesn't matter. It ignores case, punctuation and filler words like "um" and "uh", and it treats numbers, symbols and currencies written differently as the same words. ### Ratings | Rating | Score | | - | - | | **Good** | 97% and above | | **Fair** | 93% to under 97% | | **Poor** | Under 93% | ### Verification line The score is only as good as the reference transcripts. Tuner writes a draft transcript for each caller turn when you add the call. You can [edit and verify](/docs/datasets/add-calls#edit-and-verify-transcripts) each one. The line under the score shows where you are: | Verified turns | Line | Link | | - | - | - | | All | **Reference transcripts verified for all N turns** | None | | Some | **Reference transcripts verified for X of N turns**, followed by "unverified turns may inflate this score" | **Verify remaining turns** | | None | **No reference transcripts verified**, followed by "this score is based on our own drafts and is indicative only" | **Verify transcripts** | The links open the Dataset call, where you verify the transcripts. ### Outdated scores When you edit, verify or unverify a transcript after a call was scored, the card shows an **Outdated** badge. Editing never recalculates a call on its own. Click **Recalculate** to score the call again against the current transcripts. The card then shows the new score. ![The Transcription accuracy card with an Outdated badge and a Recalculate button above the score](https://mintcdn.com/tuner/Z16wBZIv2BPLqt5V/images/transcription-accuracy-outdated.png?fit=max\&auto=format\&n=Z16wBZIv2BPLqt5V\&q=85\&s=31ef841383f9e584cec183384a2d0221) ### Calls that aren't scored Tuner shows no card on a call that isn't a replay. For a replay it can't score, the card says why. | Reason | What to do | | - | - | | The call has no caller speech in your agent's transcript | Check that your agent's speech-to-text is working. | | The turns that played have fewer than 10 words to compare | Replay a Dataset call with more caller speech. | | The agent's language isn't supported | Transcription accuracy supports English, Spanish, French, German, Arabic and Italian. | | Tuner doesn't know which caller turns played | The call didn't record turn timings. Run the replay again. | ### Limits | Limit | Value | | - | - | | Minimum words to score a call | 10 | | Supported languages | English, Spanish, French, German, Arabic, Italian | | Mismatches listed under **What went wrong** | 50. The card shows how many there were in total. | | Transcript length per caller turn | 5,000 characters | You can recalculate a call through the public API: see [Recalculate Transcription Accuracy](/api-reference/calls/recalculate-transcription-accuracy) in the **calls** group of the API Reference. ## Going deeper with traces The stage breakdown tells you which stage of a turn was slow. It doesn't tell you what ran inside that stage. If your agent is built on LiveKit Agents or Pipecat, you can send its OpenTelemetry spans to Tuner and get a span tree per call, showing the model request, the synthesis stream and each tool call, with the timing of each. The call then has a **Traces** tab. Voice metrics measure the latency your customer perceived, on every call, with no setup. A trace shows the operations that produced that latency, and needs a one-time exporter change in your agent. See [OpenTelemetry Traces](/docs/observability/traces). ## Next steps > [card] [Predefined evals](/docs/evaluation/predefined-evals) > > The 27 evals Tuner ships with, and what each one checks. > [card] [Find the root cause of a failing call](/docs/observability/root-cause-analysis) > > Use the transcript, tabs and metrics together to debug a call. # Credits and usage Source: https://docs.usetuner.ai/docs/resources/credits What uses credits in Tuner, how each feature is counted, and where to see and top up your workspace balance. Tuner meters usage in **credits**. Each workspace has one credit balance, shared by all its agents. Analyzing calls, running simulations and analyzing uploaded audio draw from that balance. Plans, prices and the credit rate for each feature are on the [pricing page](https://usetuner.ai/pricing). ## What uses credits Each analysis is counted separately, so a call uses credits for each feature that runs on it. Simulated calls are analyzed the same way as production calls, so their Call Outcomes, Intents, Data extraction and evals are counted in addition to simulation minutes. | Feature | How it's counted | Rate | | - | - | - | | [**Call Outcomes**](/docs/evaluation/call-classification) | Once per analyzed call | [Pricing page](https://usetuner.ai/pricing) | | [**Intents**](/docs/evaluation/call-classification) | Once per analyzed call | [Pricing page](https://usetuner.ai/pricing) | | [**Data extraction**](/docs/evaluation/data-extraction) | Once per analyzed call | [Pricing page](https://usetuner.ai/pricing) | | [**Pass/Fail** evals](/docs/evaluation/custom-evals) | Per call, once for each Pass/Fail eval on the agent | [Pricing page](https://usetuner.ai/pricing) | | [**Score 1-5** evals](/docs/evaluation/custom-evals) | Per call, once for each Score 1-5 eval on the agent | [Pricing page](https://usetuner.ai/pricing) | | [**Voice metrics**](/docs/observability/voice-metrics) | Once per analyzed call | [Pricing page](https://usetuner.ai/pricing) | | [**Call Simulation**](/docs/simulation/overview) | Per minute of connected call time, including partial minutes. Replays are counted the same way. | Shown as **Rate: N credits / minute** in the **Run Simulation** and **New Replay** dialogs | | [**Dataset** uploads](/docs/datasets/add-calls) | Per minute of uploaded audio, charged once when the Dataset call is **Ready** | 1.5 credits per minute of audio | A call analysis is charged after it completes. If an analysis fails and is retried, the failed attempt isn't charged. [**PII redaction**](/docs/observability/pii-redaction) has its own check when you turn it on: Tuner confirms your plan includes it. Tuner doesn't record per-call usage for it. ## What doesn't use credits | Action | Why | | - | - | | Simulated calls that never connect | Only calls where the SIP leg to your agent connected are charged. | | Simulated calls that end on an error or time out | Only calls that end normally are charged: the call was hung up (`disconnected`), it reached the max call duration (`duration_limit_reached`), or a replay played every caller turn (`clips_exhausted`). See [Run statuses](/docs/simulation/run-statuses). | | Adding a production call to your [Dataset](/docs/datasets/overview) | No usage is recorded when a Dataset call is created from a production call. Replaying it later uses simulation minutes. | | Uploads that fail or are canceled | The upload charge is recorded only when the Dataset call reaches **Ready**. | | [Red flags, labels](/docs/evaluation/red-flags) and [alerts](/docs/observability/alerts) | These aren't metered features. | ## Where to see your balance | Place | What it shows | | - | - | | **Credits** widget at the bottom of the sidebar | Your current balance and a **Top up** button that opens **Workspace Settings > Billing**. It turns amber when the balance is below 30 credits and red at zero. | | **Workspace Settings > Billing** | **CREDIT BALANCE REMAINING**, the total credits used so far, and **TOP UP CREDITS**. | | **Run Simulation** and **New Replay** dialogs | The simulation rate per minute and your balance, before you start. | | Dataset upload | The cost before you extract: 1.5 credits per minute of audio, then an estimate for the selected file. | ## Add credits | Option | Where | What it does | | - | - | - | | **TOP UP CREDITS** | **Workspace Settings > Billing** | Choose a credit pack with the slider, then click **Buy N credits for \$X**. Checkout opens in Stripe. The balance updates after payment. | | **Add Coupon** | **Workspace Settings > Billing** | Enter a code in **Apply Coupon**. Depending on the code, it adds credits directly, applies a discount to your plan, or opens checkout for a credit pack. | | **Estimate Usage** | **Workspace Settings > Billing** | Opens the [pricing page](https://usetuner.ai/pricing). | | **YOUR PLAN** | **Workspace Settings > Billing** | Shows and changes your plan. Plan contents are on the [pricing page](https://usetuner.ai/pricing). | ## When your balance reaches zero At zero, a banner says new calls won't be processed until you top up, with a **Buy credits** button. Tuner blocks the following until you add credits: | Action | What happens | | - | - | | New calls sent through an integration or the API | Rejected with "Workspace has insufficient credits". | | Importing or syncing calls on **Call Logs** | Doesn't start. See [Call Logs](/docs/observability/call-logs). | | Running a simulation or a replay | Doesn't start: "You have no credits remaining." | | Analyzing an uploaded recording | **Analyze audio** is disabled: "You're out of credits. Top up to analyze audio." | | Adding a Dataset call, from a production call or an upload | The submit button is disabled: "You're out of credits. Top up to create a Dataset call." | # FAQ Source: https://docs.usetuner.ai/docs/resources/faq Short answers to common questions about Tuner, with links to the pages that cover each feature. ## General questions > [accordion] What is Tuner? > > Tuner is an observability, evaluation and simulation platform for voice AI agents. It scores every call against the evals you define, flags the calls that went wrong, and places test calls against your agent. See [Welcome to Tuner](/docs/getting-started/welcome-to-tuner). > [accordion] Who is Tuner for? > > Developers who integrate voice agents through the SDKs or API, and product and operations teams who own an agent's quality and work in the dashboard. > [accordion] How does Tuner work? > > Tuner integrates with your voice AI platform to automatically ingest call data. > > * For **Retell** and **Vapi**, you connect your platform key in the setup wizard and Tuner receives calls automatically. > * For **LiveKit**, **Pipecat** and custom stacks, you add the Tuner SDK or send calls to the API. > > Tuner then classifies each call, runs your evals and voice metrics, and shows the results in **Call Logs** and on the **Overview** dashboard. See the [Quickstart](/docs/getting-started/quickstart). > [accordion] What voice AI platforms do you support? > > Any of them. Tuner does not run your agent or plug into your platform's internals. The only thing an integration does is **send the call to Tuner**, and once Tuner has the call it handles everything else. > > Which route you take depends only on what you build on: > > * **[Retell](/docs/integrations/retell), [Vapi](/docs/integrations/vapi), or [Dograh](/docs/integrations/dograh)**: a guided setup in the dashboard, no code. > * **[LiveKit](/docs/integrations/livekit) or [Pipecat](/docs/integrations/pipecat)**: install that framework's Tuner SDK. > * **Anything else**: the [custom stack](/docs/integrations/custom-stack/overview) route, using either the custom SDK or the Custom API. > > What each route involves is under [Technical Questions](#technical-questions) below. > [accordion] What languages does Tuner support? > > It depends which side of the product you mean. > > **Observability and evals** work in whatever language your agent handles. Tuner analyzes the transcript you send it, and the eval judges read that transcript in the language the call actually happened in. An Arabic call is scored by the same evals as an English one, with no per-language configuration and no separate agent for each language. Eval prompts themselves can be written in English or in the language of the call. > > **Call Simulation** has a fixed list, because the Simulated Caller has to speak. It supports these languages and accents: > > | Language | Accents | > | - | - | > | English | US, UK, AU | > | Spanish | ES, MX | > | French | FR, CA | > | German | DE, AT, CH | > | Arabic | SA, EG, AE | > | Italian | IT | > | Hindi | IN | > > See [Languages and accents](/docs/simulation/run-a-simulation#languages-and-accents). > > So an agent that takes calls in a language outside the simulation list can still be fully monitored and evaluated. Only the generation of test calls is limited. > [accordion] What kind of insights can I get from Tuner? > > * **Overview metrics**: total calls, success rate, failed calls, calls with red flags and red flag rate. > * **Call classification**: call intent and call outcome for each call, set up on **Agent Settings > Analysis Setup**. > * **Issue detection**: red flags from rules on evals, voice metrics, data fields and call metadata, such as a failed hallucination eval or high latency. > * **Call details**: the transcript, eval results, voice metrics and extracted data for every call. > [accordion] Can I test my agent on my own call recordings? > > Yes. Build a [Dataset](/docs/datasets/overview) from real calls: pick them from production, or upload recordings you already have, even on your first day. Tuner replays the caller's side against your agent exactly as it was said, so you can reproduce a call that failed, prove your fix, and compare models or providers on your own callers. > [accordion] How does Tuner measure transcription accuracy? > > On a replay of a Dataset call, Tuner compares the reference transcript of each caller turn with what your agent's speech-to-text heard, and scores the difference. The result is a percentage with a **Good**, **Fair** or **Poor** rating on the call's **Voice Metrics** tab. See [Transcription accuracy](/docs/observability/voice-metrics#transcription-accuracy). ## Technical questions > [accordion] Can my self-hosted voice agent connect to Tuner? > > Yes. Where your agent runs makes no difference, because Tuner never runs your agent and needs no access to your infrastructure. > > The whole integration is one idea: **get the call to Tuner**. Once Tuner receives it, everything after that is handled for you, including the transcript, per-turn timing, classification, evals, red flags, and alerts. There is nothing else to wire up. > > How you send the call depends only on what you build on: > > * **Retell, Vapi, ElevenLabs, or Dograh**: a guided setup in the dashboard. Add your platform key and pick your agent, or drop the **Tuner** node into your Dograh workflow. No code, and Tuner configures the receiving side for you. > * **LiveKit or Pipecat**: install that framework's Tuner SDK, [LiveKit](/docs/integrations/livekit) or [Pipecat](/docs/integrations/pipecat), and attach it to your session. It captures the call as it happens and sends it when the call ends. > * **Any other platform, or a stack you built yourself**, for example Plivo, Bland, or Twilio: use the [custom stack](/docs/integrations/custom-stack/overview) route. On Python, the [custom SDK](/docs/integrations/custom-stack/sdk-quickstart) attaches observers to your own STT, LLM, and TTS and does the capture for you. In any other language, build the call payload yourself and POST it to the [Custom API](/docs/integrations/custom-stack/direct-api). Both arrive in Tuner as the same thing. > > Self-hosted or managed changes nothing on any of these routes. Calls travel one way, out from your stack to Tuner over HTTPS, so Tuner needs no route into your network. [Call Simulation](/docs/simulation/overview) is the one exception: to place a test call, your agent either has to be reachable at a SIP URI you give Tuner, or able to dial a SIP URI Tuner gives it. > [accordion] Where is your API documentation? > > In the [API Reference](/api-reference/calls/create-call) tab. To authenticate, create a key on **API Keys** and send it as `Authorization: Bearer `. See [API keys and IDs](/docs/getting-started/api-keys). > [accordion] What is the difference between a Workspace ID and an Agent Remote ID? > > * **Workspace ID**: identifies your workspace. API calls send it as `workspace_id`. > * **Agent Remote ID**: links an agent in Tuner to the calls you send for it. API calls send it as `agent_remote_identifier`. How it's set depends on your provider; see below. > [accordion] How do I find my Workspace ID and Agent Remote ID? > > * **Workspace ID**: on **Workspace Settings > General Settings**. > * **Agent Remote ID**: on **Agent Settings > Agent Setup**, in the **Agent Connection** card. > * **Retell, Vapi and ElevenLabs**: it's the agent's ID on that platform, taken from the agent you pick when creating the agent in Tuner. > * **LiveKit, Pipecat, Dograh and custom stacks**: Tuner generates it when you create the agent. > > See [API keys and IDs](/docs/getting-started/api-keys). ## Security and privacy > [accordion] Can Tuner itself be deployed on-premises? > > This is a different question from where your agent runs, and the two get mixed up often. > > * **Your voice agent** can run anywhere, including entirely on your own infrastructure. See the question above on connecting a self-hosted voice agent. > * **Tuner** runs as a hosted cloud service on the Pay as You Go, Builder, and Growth plans. **On-premise deployment is available on Enterprise**, alongside SOC 2 and HIPAA compliance, custom integrations, and a DPA on request. It is set up with the Tuner team, so contact [hi@usetuner.ai](mailto:hi@usetuner.ai) to talk through it. > > If your concern is what Tuner stores, [PII redaction](/docs/observability/pii-redaction) replaces sensitive details in transcripts and [data retention](/docs/observability/data-retention) sets how long call data is kept before it is erased. > [accordion] How does Tuner handle sensitive caller data (PII)? > > On the **Growth plan**, you can turn on **PII redaction**. Tuner then detects sensitive details in each call transcript (names, phone numbers, email and physical addresses, SSN / national ID, card numbers, and spoken PINs or passwords) and replaces them with labels like `[NAME]`. Recordings are not redacted. Each call shows its redaction status: **Redacted**, **Partial** or **Failed**. > > The setting is workspace-wide, so it applies to every agent in the workspace. See [**Data Redaction (PII)**](/docs/observability/pii-redaction) for the full walkthrough. ## Billing and credits > [accordion] How does pricing work? > > Tuner charges in **credits**. Each analysis a call goes through uses credits, so you pay for what you run. Your plan sets your monthly credit allowance and which features you can use. Plans, prices and credit rates are on [usetuner.ai/pricing](https://usetuner.ai/pricing). For what uses credits and how each is counted, see [Credits and usage](/docs/resources/credits). > [accordion] How do I buy more credits? > > Top up at any time on **Workspace Settings > Billing**. See [Credits and usage](/docs/resources/credits#add-credits). > [accordion] What happens when I run out of credits? > > At zero balance, Tuner stops processing new calls and you can't start simulation runs or replays until you add credits. See [Credits and usage](/docs/resources/credits). > [accordion] Where can I see my credit balance? > > At the bottom of the sidebar and on **Workspace Settings > Billing**. ## Next steps > [card] [Troubleshooting](/docs/resources/troubleshooting) > > Fixes for common problems. > [card] [Glossary](/docs/resources/glossary) > > Definitions of the terms used across Tuner. # Glossary Source: https://docs.usetuner.ai/docs/resources/glossary Definitions of the terms used across Tuner and its documentation. The terms used across Tuner, in alphabetical order. Each links to the page that covers it. | Term | Definition | | - | - | | **Agent** | The voice AI application you monitor with Tuner, such as a customer support bot, appointment scheduler, or sales assistant. Each agent has its own evals and settings. | | **Agent Remote ID** | The identifier that links an agent in Tuner to the calls you send for it, sent as `agent_remote_identifier`. For Retell, Vapi and ElevenLabs it's the agent's ID on that platform; for SDK and API agents Tuner generates it. Shown on **Agent Settings > Agent Setup**. See [API keys and IDs](/docs/getting-started/api-keys). | | **Alert** | A notification sent when calls matching the conditions you set reach a threshold in a time window, for example more than 5 red-flagged calls in an hour. An alert can combine several conditions. Delivered by email or webhook. See [Alerts](/docs/observability/alerts). | | **API key** | A workspace key starting with `tr_api_` that SDKs, the public API and MCP clients send as `Authorization: Bearer `. Created on **API Keys** and shown once. See [API keys and IDs](/docs/getting-started/api-keys). | | **Call Logs** | The page that lists every call for the selected agent, with filters and search. Open a call to see its transcript, evals, voice metrics, extracted data and traces. See [Call Logs](/docs/observability/call-logs). | | **Call Outcome** | How a call ended, defined by you as a success or a failure. Add outcomes from Tuner's outcome library or create your own. Call outcomes drive your success rate. See [Call outcomes and intents](/docs/evaluation/call-classification). | | **Call Simulation** | Real SIP test calls between your agent and a Simulated Caller: Tuner dials in for inbound agents, or your agent dials out for outbound agents. Each simulated call is scored against the same evals, intents and call outcomes configured for production. See [Call simulation](/docs/simulation/overview). | | **Caller Turn** | One stretch of the caller speaking in a [Dataset call](/docs/datasets/overview), with its start and end time in the original recording. A replay plays a call's caller turns in order, waiting for your agent to answer after each one. | | **Correlation ID** | The `X-Correlation-Id` header Tuner adds to each inbound simulated call. Your integration sends it back with the call so Tuner can link the call to its run. See [How simulated calls are linked](/docs/simulation/run-statuses#how-simulated-calls-are-linked). | | **Dataset** | Your agent's collection of Dataset calls, built on the **Dataset** tab under **Simulations**. Replay it to reproduce a failure, prove a fix, or compare setups on your own calls. See [Datasets](/docs/datasets/overview). | | **Dataset Call** | The caller's side of one real call, cut into caller turns, ready to replay against your agent. You add one from a production call or an uploaded stereo recording. See [Add Dataset calls](/docs/datasets/add-calls). | | **Eval** | A check of whether your agent did something specific or followed a guideline during a call, for example confirming appointment details before ending the call. Use one from the [predefined eval library](/docs/evaluation/predefined-evals) or [write your own](/docs/evaluation/custom-evals). Evals run automatically on every call. See [Evals and guardrails](/docs/evaluation/overview). | | **Guardrail** | A rule that defines what "bad" looks like for your agent, such as a red-flag rule or an alert. See [Evals and guardrails](/docs/evaluation/overview). | | **Hallucination** | When the agent gives incorrect, made-up, or misleading information, such as a wrong price or a booking that didn't happen. The predefined Hallucination eval checks for it. | | **Intent** | What the caller wanted from the call. For an appointment scheduling agent, intents might include "Book Appointment," "Reschedule," "Cancel," or "Check Availability." Set up on **Agent Settings > Analysis Setup**. See [Call outcomes and intents](/docs/evaluation/call-classification). | | **Label** | A tag applied to a call when a label rule matches, used to categorize calls without marking them as a problem. See [Red flags and labels](/docs/evaluation/red-flags). | | **Overview** | The dashboard for the selected agent: **Total Calls**, **Success Rate**, **Failed Calls**, **Calls with Red Flags** and **Red Flag Rate**, the **Call Intent Breakdown** and **Call Outcome Breakdown** charts, and recent red flags. See [Overview dashboard](/docs/observability/overview). | | **Pressure Test** | A Simulated Caller that stress-tests your agent with difficult situations, such as unhappy customers, scope-boundary requests, or attempts to bypass your process. Pressure Tests are generated from your configured evals. See [Call simulation](/docs/simulation/run-a-simulation#the-simulation-mix). | | **Red Flag** | A tag applied to a call when a red-flag rule matches, for example when an eval fails. Red flags appear on the Overview dashboard and in Call Logs, so you can see which calls need attention first. See [Red flags and labels](/docs/evaluation/red-flags). | | **Reference Transcript** | What the caller said in each caller turn of a Dataset call, taken from the source call's transcript or transcribed by Tuner. You can edit it and mark it **Verified**. A replay always plays the audio, and uses the transcript to score [transcription accuracy](/docs/observability/voice-metrics#transcription-accuracy). | | **Replay** | A simulated call that plays the caller turns of a Dataset call into a live call with your agent, so the caller is identical on every run. Every replay is graded against your agent's Pass/Fail evals. See [Replays](/docs/simulation/replays). | | **Replay Run** | A group of replays started together from **New Replay**: up to 10 Dataset calls, each replayed 1 to 20 times, with at most 20 calls in total. | | **Routine Caller** | A Simulated Caller that follows your agent's normal, cooperative workflows. Routine Callers are generated from your agent's configured intents to test the happy path. See [Call simulation](/docs/simulation/run-a-simulation#the-simulation-mix). | | **Rule** | The conditions that apply a label or red flag to a call, set on **Agent Settings > Evaluation Rules**. A rule has one or more conditions on evals, voice metrics, data fields or call metadata, and matches when all or any of them match. See [Red flags and labels](/docs/evaluation/red-flags). | | **Runs** | The tab under **Simulations** that lists your simulation runs as cards. Open a run to see its calls with **#**, **Type**, **Evals**, **Outcome**, **Intent** and **Dur.** columns, and click a call for its full details. See [Run statuses](/docs/simulation/run-statuses). | | **Scenario** | One situation for a Simulated Caller to play: the caller's persona, intent and what to test. Tuner writes new Scenarios for each simulation run. Scenarios in the Scenario Library show their origin: **Manual** for ones you wrote, **Saved from run** for ones kept from a run. See [Scenario Library](/docs/simulation/scenarios). | | **Sentiment** | The emotional tone of the caller in the conversation, shown on each call's **Overview** tab. | | **Simulated Caller** | The AI caller that talks to your agent on a simulated call. Each one is a Routine Caller or a Pressure Test. See [Call simulation](/docs/simulation/overview). | | **Simulation Mix** | The ratio of Routine Callers to Pressure Tests in a simulation run. You set it with a slider in the **Run Simulation** dialog. | | **Simulation Run** | A group of simulated calls started together from the **Run Simulation** dialog: 5 to 20 calls, 10 by default. Runs appear on the **Runs** tab. | | **Simulation Setup** | The **Agent Settings > Simulation Setup** tab, where you set how Tuner reaches your agent for simulation. Inbound agents use the **SIP Settings** card for the SIP URI and credentials Tuner dials. Outbound agents use the **Outbound Trigger Endpoint** card. See [Inbound simulation](/docs/simulation/inbound/setup) and [Outbound simulation](/docs/simulation/outbound). | | **SIP** | Session Initiation Protocol, the signaling standard voice platforms use to start, manage, and end calls. Tuner uses SIP so simulation calls travel the same path as a real phone call. See [Inbound simulation](/docs/simulation/inbound/setup). | | **SIP Call-ID** | A unique identifier carried with each SIP call. Tuner can use it to link a simulated call to its run. See [How simulated calls are linked](/docs/simulation/run-statuses#how-simulated-calls-are-linked). | | **SIP URI** | A SIP address, the internet equivalent of a phone number, for example `sip:agent@sip.vapi.ai`. In inbound simulation, Tuner dials your agent's SIP URI; in outbound simulation, Tuner gives your system a SIP URI to dial. See [Inbound simulation](/docs/simulation/inbound/setup) and [Outbound simulation](/docs/simulation/outbound). | | **Transcript** | The written record of the conversation between the caller and the agent, turn by turn, with speaker labels and timing. | | **Transcription accuracy** | On a replay call, the share of the caller's words your agent's speech-to-text heard correctly, with a **Good**, **Fair** or **Poor** rating. See [Transcription accuracy](/docs/observability/voice-metrics#transcription-accuracy). | | **Turn-taking Settings** | The **Advanced turn-taking** values a replay uses to decide when your agent has finished speaking and when to play the next caller turn: initial agent wait, silence threshold, minimum speech, inter-turn delay, and max wait. See [Replays](/docs/simulation/replays#turn-taking-settings). | | **Voice metrics** | Measurements Tuner computes for every call, such as per-turn latency for each pipeline stage and the longest agent monologue. See [Voice metrics](/docs/observability/voice-metrics). | | **Workspace ID** | The identifier of your workspace, sent as `workspace_id` in API calls. Shown on **Workspace Settings > General Settings**. See [API keys and IDs](/docs/getting-started/api-keys). | ## Next steps > [card] [Evals and guardrails](/docs/evaluation/overview) > > How evals and guardrails judge your agent's calls. > [card] [Call simulation](/docs/simulation/overview) > > Run simulations to test your agent. # Troubleshooting Source: https://docs.usetuner.ai/docs/resources/troubleshooting Fixes for common problems with sending calls to Tuner, red flags, alerts, simulation and the Overview dashboard. Short answers to common problems. Each links to the page that covers the feature. ## API and data integration > [accordion] Calls are not appearing in Tuner > > If you've sent calls through the SDK or API but they don't appear in **Call Logs**, check these first: > > 1. **API key**: send a valid Tuner API key in the `Authorization` header as `Authorization: Bearer tr_api_...`. Create and manage keys on the **API Keys** page; a revoked key stops working immediately. See [API keys and IDs](/docs/getting-started/api-keys). > 2. **Workspace ID**: check the `workspace_id` query parameter. Find it on **Workspace Settings > General Settings**. > 3. **Agent Remote ID**: `agent_remote_identifier` must match the **Agent Remote ID** of an agent in that workspace, shown on **Agent Settings > Agent Setup**. > 4. **API response**: a `401` means the API key is invalid. A `422` lists the fields that are missing or wrong. > [accordion] 'Agent not found' error > > The `agent_remote_identifier` you sent doesn't match any agent in the workspace. > > Go to **Agent Settings > Agent Setup** and copy the **Agent Remote ID** from the **Agent Connection** card. Check that you send exactly that value, to the workspace that agent belongs to. > [accordion] 422 validation error > > The request body is invalid. The response has a `detail` field listing each problem. > > Common causes: > > * `call_id` is missing or not a string. > * A required field is missing. > * A field has the wrong data type, for example a string for a number field. > * A timestamp is in the wrong format. > > See [Create Call](/api-reference/calls/create-call) for the expected payload. ## Dashboard and features > [accordion] Data is not being processed correctly > > If calls appear in **Call Logs** but their results look wrong (for example, evals not running), contact support with the call ID and a description of the problem. > [accordion] Red flags are not triggering > > 1. **Check the rule**: go to **Agent Settings > Evaluation Rules** and review the rule for the red flag. Check each condition's field, operator and value, and whether the rule matches all or any of them. > 2. **Check the rule isn't paused**: a rule on a deleted eval, data extraction field or voice metric is paused. See [Resume a paused rule](/docs/evaluation/red-flags#resume-a-paused-rule). > 3. **Check the data**: open the call in [Call Logs](/docs/observability/call-logs) and check whether it meets the condition. > > See [Red flags and labels](/docs/evaluation/red-flags). > [accordion] Alerts are not being sent > > 1. **Check the alert**: in **Agent Settings > Alerts**, check that the alert is on and its conditions and threshold are correct. > 2. **Check the alert isn't paused**: an alert on a deleted eval, data extraction field, voice metric or red flag is paused. See [Resume a paused alert](/docs/observability/alerts#resume-a-paused-alert). > 3. **Check the recipients**: make sure the email addresses are correct. > 4. **Check your spam folder**: alert emails can be filtered as spam. > > See [Alerts](/docs/observability/alerts). > [accordion] Overview dashboard shows no data > > 1. **Select an agent**: make sure the right agent is selected under **Select Agent** in the sidebar. > 2. **Check the time period**: make sure the period (**7 days**, **30 days** or **90 days**) includes the calls. > 3. **Check that calls arrived**: open **Call Logs**. > > If **Call Logs** shows calls but **Overview** doesn't, the calls may still be processing. Wait a few minutes and refresh. ## Simulation > [accordion] Simulated calls show as Unreported > > Tuner placed the call, but your integration didn't send it back with the ID Tuner put on it. Open **Call Logs** and look for the call. If it's there, check what links it to the run. If it isn't, check that your integration is sending calls. > > See [Fix an Unreported run](/docs/simulation/run-statuses#fix-an-unreported-run). ## Next steps > [card] [FAQ](/docs/resources/faq) > > Answers to common questions about Tuner. > [card] [Contact support](mailto:support@usetuner.ai) > > Email the Tuner team. # SIP providers Source: https://docs.usetuner.ai/docs/simulation/inbound/other-platforms Get a SIP URI and credentials from your phone or SIP provider for inbound simulation of LiveKit, Pipecat and custom-stack agents. > [!NOTE] > > For LiveKit, Pipecat and custom-stack agents. Get the SIP URI here, then paste it into Tuner as described in [Set up inbound simulation](/docs/simulation/inbound/setup). Tuner needs a **SIP URI** and, if your edge uses digest auth, a **username** and **password**. Your provider also has to pass Tuner's call, with its Call-ID and `X-Correlation-Id` header, on to your agent. See [How simulated calls are linked](/docs/simulation/run-statuses#how-simulated-calls-are-linked). Pick your provider. If you already have a SIP URI, skip this page and [paste it into Tuner](/docs/simulation/inbound/setup). > [tab] Twilio > > ### SIP setup > > **What is Twilio?** [Twilio](https://www.twilio.com/) is a cloud communications platform that lets you place and receive phone calls programmatically. A Twilio **SIP Domain** gives you a SIP address that Tuner can dial. Each call to the domain makes Twilio call the domain's Voice URL, which is your webhook. > > Create a SIP Domain for inbound simulation only, because a domain has one Voice URL. Attach a **Credential List** for authentication, and set the Voice URL to your webhook (HTTP POST). > > * SIP URI shape: `sip:@.sip.twilio.com` > * Username / Password: the values from your Credential List. > > Follow Twilio's docs for the current Console steps: > > * [SIP Domains](https://www.twilio.com/docs/voice/api/sip-interface) > > Paste the result into the **SIP Settings** card in **Agent Settings > Simulation Setup**. > > ### Syncing the Call-ID > > Twilio sends Tuner's `X-Correlation-Id` header to your webhook as `SipHeader_X-Correlation-Id`, with the SIP Call-ID as `SipCallId`. It doesn't copy them to a media stream WebSocket or to a new SIP call. Forward them from the webhook as described in **Enable simulation** for [LiveKit](/docs/integrations/livekit#carrier-in-front-of-livekit), [Pipecat](/docs/integrations/pipecat#enable-simulation) or [Custom stack](/docs/integrations/custom-stack/sdk-quickstart#enable-simulation). > > * [Media Streams: Custom Parameters](https://www.twilio.com/docs/voice/media-streams/websocket-messages#custom-parameters) > [tab] Telnyx > > ### SIP setup > > **What is Telnyx?** [Telnyx](https://telnyx.com/) is a communications platform similar to Twilio that provides voice, SMS, and SIP trunking on its own private IP network. Its **SIP URI calling** feature exposes your SIP Connection at `sip:@sip.telnyx.com` so external clients like Tuner can dial it directly. > > On an active **SIP Connection** with **credential authentication**, enable **Receive SIP URI calls**. If your server handles the call with Call Control, use a **Call Control** application with a SIP subdomain instead. Tuner dials `sip:@.sip.telnyx.com`, and the application's webhook gets the call. > > * SIP URI shape: `sip:@sip.telnyx.com` > * Username / Password: the same credential pair. > > Follow Telnyx's docs for the current portal steps: > > * [SIP URI calling](https://developers.telnyx.com/docs/voice/sip-trunking/features/sip-uri-calling) > * [Credential types](https://developers.telnyx.com/docs/voice/sip-trunking/authentication/credential-types) > > Paste the result into the **SIP Settings** card in **Agent Settings > Simulation Setup**. > > ### Syncing the Call-ID > > With Call Control, Telnyx sends Tuner's `X-Correlation-Id` header to your webhook in the `call.initiated` event's `custom_headers`. The event has no SIP Call-ID, so the header links the call. Telnyx doesn't copy the header to a media stream or a transfer. Forward it from the webhook as described in **Enable simulation** for [LiveKit](/docs/integrations/livekit#carrier-in-front-of-livekit), [Pipecat](/docs/integrations/pipecat#enable-simulation) or [Custom stack](/docs/integrations/custom-stack/sdk-quickstart#enable-simulation). > > * [SIP Trunking](https://developers.telnyx.com/docs/voice/sip-trunking) > * [Call Control: Media streaming](https://developers.telnyx.com/docs/voice/programmable-voice/media-streaming) > [tab] Plivo > > ### SIP setup > > [Plivo](https://www.plivo.com/) provides SIP trunking and programmable voice. Copy your SIP endpoint URI and credentials from the Plivo console, then paste them into the **SIP Settings** card in **Agent Settings > Simulation Setup**. > > * [Plivo SIP trunking](https://www.plivo.com/docs/sip-trunking/) > > ### Syncing the Call-ID > > Plivo uses XML to control calls. SIP headers may need to be forwarded as extra headers on the stream element. > > * [Plivo Stream API](https://www.plivo.com/docs/voice/api/stream/) > [tab] Exotel > > ### SIP setup > > [Exotel](https://exotel.com/) exposes SIP endpoints through its platform configuration. Copy the SIP URI and credentials your Exotel setup provides, then paste them into the **SIP Settings** card in **Agent Settings > Simulation Setup**. > > * [Exotel developer docs](https://developer.exotel.com/) > > ### Syncing the Call-ID > > Exotel surfaces call metadata through its App Bazaar applet configuration. Custom parameters need to be set in the applet to forward SIP identifiers. > [tab] Jambonz > > ### SIP setup > > [Jambonz](https://www.jambonz.org/) is an open-source CPaaS for SIP and WebRTC. Configure an inbound SIP trunk or application endpoint, then paste the URI and credentials into the **SIP Settings** card in **Agent Settings > Simulation Setup**. > > * [Jambonz docs](https://www.jambonz.org/docs/) > > ### Syncing the Call-ID > > Jambonz delivers SIP information on the call-hook webhook (HTTP), not the WebSocket. You'll need to bridge the two in your server code. If the call passes through multiple SIP hops, look for an `X-CID` header. > [tab] Daily > > ### SIP setup > > [Daily](https://www.daily.co/) supports SIP/PSTN dial-in for real-time audio sessions. Copy the SIP URI from your Daily project settings, then paste it into the **SIP Settings** card in **Agent Settings > Simulation Setup**. > > * [Daily SIP / PSTN dial-in docs](https://docs.daily.co/reference/rest-api/dialin) > > ### Syncing the Call-ID > > Daily includes SIP information directly in the dial-in settings payload. No extra configuration is needed. > [tab] LiveKit SIP bridge > > ### SIP setup > > **What is the LiveKit SIP bridge?** It is an **optional** add-on service for LiveKit projects that lets a normal phone call (SIP) enter a LiveKit room so your agent worker can talk to the caller. If you are building on LiveKit, you can choose to use this bridge as your phone ingress, or you can keep using your own SIP provider (Twilio, Telnyx, etc.) instead. > > 1. **SIP URI:** copy your project's SIP URI from the LiveKit Cloud console (shape: `sip:.sip.livekit.cloud`). > > ![LiveKit Cloud, project SIP URI](https://mintcdn.com/tuner/ymjXbsRhUG5GDj0_/images/simulation/siptrunkplace.png?fit=max\&auto=format\&n=ymjXbsRhUG5GDj0_\&q=85\&s=50b3d610a900e89716012dbed1363655) > > 2. **Username / Password:** the `auth_username` / `auth_password` on your **inbound SIP trunk** (not your LiveKit API key). > > ![LiveKit, inbound trunk digest credentials](https://mintcdn.com/tuner/ymjXbsRhUG5GDj0_/images/simulation/siptrunkjsonform.png?fit=max\&auto=format\&n=ymjXbsRhUG5GDj0_\&q=85\&s=cb6dbc9df799a8a5c8a00462211009a0) > > 3. Add a **dispatch rule** so inbound calls reach your agent worker. > > ![LiveKit, dispatch rule](https://mintcdn.com/tuner/ymjXbsRhUG5GDj0_/images/simulation/dispatchform.png?fit=max\&auto=format\&n=ymjXbsRhUG5GDj0_\&q=85\&s=c533ffb8d1cc79e40d96a01b1566ad14) > > Follow LiveKit's docs for current steps: > > * [Inbound trunk](https://docs.livekit.io/sip/trunk-inbound/) > * [SIP trunk setup](https://docs.livekit.io/telephony/start/sip-trunk-setup/) > * [Dispatch rule](https://docs.livekit.io/sip/dispatch-rule/) > > Paste the SIP URI and inbound-trunk credentials into the **SIP Settings** card in **Agent Settings > Simulation Setup**. > > ### Syncing the Call-ID > > When using the LiveKit SIP bridge, SIP metadata is available as participant attributes within the LiveKit room. > > * [LiveKit SIP docs](https://docs.livekit.io/sip/) > * [Connecting to LiveKit (Tuner guide)](/docs/integrations/livekit) > [tab] Other / custom > > ### SIP setup > > If you terminate SIP yourself (Asterisk, FreeSWITCH, Kamailio, or similar), you have direct access to the SIP URI and credentials. Paste them into the **SIP Settings** card in **Agent Settings > Simulation Setup**. > > ### Syncing the Call-ID > > You have direct access to the `Call-ID` header. Pass it to Tuner through whichever integration method you use. No provider-specific configuration is needed. > > * [Create Call API](/api-reference/calls/create-call) ## Next steps > [card] [Run a simulation](/docs/simulation/run-a-simulation) > > Configure your Simulation Mix and start a run. > [card] [Run statuses](/docs/simulation/run-statuses) > > What each run status and call result means. # Set up inbound simulation Source: https://docs.usetuner.ai/docs/simulation/inbound/setup Let Tuner call your agent for simulation: find your platform, give Tuner the SIP URI, and check the connection. > [!NOTE] > > Your agent must already be [connected to Tuner](/docs/getting-started/quickstart) and sending real calls, with its **Call Direction** set to **Inbound**. For inbound simulation, Tuner calls your agent the same way a phone call reaches it. For most platforms that means a **SIP URI** Tuner can call, plus a username and password if your SIP endpoint requires them. ## Find your platform | Your agent runs on | What to do | | - | - | | Retell | Nothing. See [Retell](#retell). | | Vapi | Create a free Vapi SIP trunk and paste its SIP URI into Tuner. See [Vapi](#vapi). | | ElevenLabs | Paste the SIP URI of an ElevenLabs SIP trunk number assigned to your agent. See [ElevenLabs](#elevenlabs). | | Dograh | Build the SIP URI from your Dograh settings. See [Dograh](#dograh). | | LiveKit, Pipecat or a custom stack | Use the SIP URI from your phone or SIP provider, and add the simulation step to your integration. See [LiveKit, Pipecat and custom stacks](#livekit-pipecat-and-custom-stacks). | Every platform except Retell ends the same way: you paste the SIP URI into the **SIP Settings** card in **Agent Settings > Simulation Setup** and click **Verify & Save**. Tuner places a short test call to check the connection. ![Tuner Agent Settings, SIP Settings (SIP URI, username, password)](https://mintcdn.com/tuner/ymjXbsRhUG5GDj0_/images/simulation/sip-settings.png?fit=max\&auto=format\&n=ymjXbsRhUG5GDj0_\&q=85\&s=2a1b0de8f19925d16279808972da8c3a) ## Retell Retell agents need no setup. Tuner starts each simulation call through Retell, using your agent's Agent Remote ID and the Retell API key saved on its integration, so there's no SIP URI and the **SIP Settings** card isn't shown. Retell supports inbound simulation and [replays](/docs/simulation/replays). Outbound simulation isn't available for Retell agents. ## Vapi **1. Create a free Vapi SIP trunk** 1. Open the [Vapi dashboard](https://dashboard.vapi.ai/) and go to **Phone Numbers**. 2. Click **Create Phone Number** and choose **Free Vapi SIP**. 3. Fill in the **SIP Identifier** (it becomes part of your SIP URI), a **Label** for your own reference, and a **Username** and **Password**. 4. Click **Import SIP URI**. Your SIP URI is `sip:@sip.vapi.ai`. ![Creating a Free Vapi SIP trunk (Phone Numbers > Free Vapi SIP)](https://mintcdn.com/tuner/ymjXbsRhUG5GDj0_/images/simulation/vapi-create-sip-trunk.png?fit=max\&auto=format\&n=ymjXbsRhUG5GDj0_\&q=85\&s=d21464ed501b58a00a3999d5c0583ba5) > [!WARNING] > > **Save the username and password now.** Vapi shows the password only once. If you lose it, delete the trunk and create a new one. **2. Link your assistant** Simulation calls won't connect without this step. 1. In **Phone Numbers**, click your SIP trunk. 2. Under **Inbound Settings**, set **Assistant** to the assistant Tuner should reach. 3. Click **Save**. ![Link your Vapi assistant to the SIP trunk in Inbound Settings](https://mintcdn.com/tuner/ymjXbsRhUG5GDj0_/images/simulation/vapi-link-assistant.png?fit=max\&auto=format\&n=ymjXbsRhUG5GDj0_\&q=85\&s=16f16587ea8987d12934cce38593935e) **3. Paste it into Tuner** In **Agent Settings > Simulation Setup**, in the **SIP Settings** card, enter the **SIP URI**. Under **Authentication (optional)**, enter the **Username** and **Password** from the first step. Click **Verify & Save**. > [accordion] Troubleshooting Vapi > > | Issue | What to check | > | - | - | > | Calls fail to connect | The assistant is linked to the trunk. The credentials match in Vapi and Tuner. The URI is exactly `sip:identifier@sip.vapi.ai`. | > | Assistant is silent | The assistant has a prompt and is active, not a draft or paused. | > | Not verified in Tuner | No trailing spaces in the URI or password. Click **Verify & Save** again. | ## ElevenLabs **1. Assign your agent to a SIP trunk number** In ElevenLabs, use a SIP trunk phone number with your agent assigned to it for inbound calls. Its SIP URI is `sip:+@sip.rtc.elevenlabs.io`, with the number's digits in place of ``. **2. Paste it into Tuner** In **Agent Settings > Simulation Setup**, in the **SIP Settings** card, enter the **SIP URI**. The field shows the example `sip:+@sip.rtc.elevenlabs.io:5060;transport=tcp`. Click **Verify & Save**. Tuner links ElevenLabs calls to their run itself, so there is no integration step. See [How simulated calls are linked](/docs/simulation/run-statuses#how-simulated-calls-are-linked). ## Dograh Before you start: * Dograh **v1.48.0** or later. Earlier versions don't reliably send Tuner the SIP call ID, so simulation calls can land in Call Logs as production traffic instead of linking to their run. * The Tuner node enabled on your Dograh workflow, and the workflow **published**. Inbound calls run the published version, so a Tuner node that exists only in a draft sends nothing to Tuner. See [Connecting to Dograh](/docs/integrations/dograh). * In Dograh, a phone number under **Telephony configurations** > **Dograh Cloudonix SIP** > **Phone numbers** with its **Inbound workflow** set to your agent. A short extension such as `101` works; it doesn't need to be a real number. See [Dograh's SIP guide](https://docs.dograh.com/integrations/telephony/dograh-sip) if you haven't set one up. **1. Build the SIP URI** The URI is `sip:
@`: | Part | Where to find it in Dograh | | - | - | | Address | The **Address** of your phone number under **Phone numbers**, for example `101` | | Hostname | **SIP connectivity** > **Inbound** > **Hostname** | For example: `sip:101@a1b2c3d4-0000-0000-0000-9f8e7d6c5b4a.sip.cloudonix.net`. If the **UDP/TCP** port under **SIP connectivity** isn't `5060`, add it to the end, for example `sip:101@:9060`. **2. Paste it into Tuner** In **Agent Settings > Simulation Setup**, in the **SIP Settings** card, enter the **SIP URI**. Dograh's inbound endpoint doesn't use SIP authentication, so leave **Username** and **Password** empty. Click **Verify & Save**. > [!NOTE] > > **Known issue.** With both authentication fields empty, verification can fail with "endpoint did not answer." Enter any placeholder values, for example `tuner` and `tuner`. Dograh never checks them. > [accordion] Troubleshooting Dograh > > | Issue | What to check | > | - | - | > | "Endpoint did not answer" on **Verify & Save** | If the authentication fields are empty, see the known issue above. Otherwise check that the address matches a phone number in Dograh, that number has an inbound workflow, and the port is in the URI if it isn't 5060. | > | Agent answers but nothing reaches Tuner | Publish the workflow so the Tuner node is in the published version. | > | Calls land in Call Logs instead of the run | Check that **Call Direction** is **Inbound** and Dograh is on v1.48.0 or later. | > | `603 Declined` | On a self-hosted Dograh, check that your backend is publicly reachable. | ## LiveKit, Pipecat and custom stacks **1. Get your SIP URI** Use the SIP URI and credentials from your phone or SIP provider. [SIP providers](/docs/simulation/inbound/other-platforms) covers Twilio, Telnyx, Plivo, Exotel, Jambonz, Daily and LiveKit SIP. **2. Paste it into Tuner** In **Agent Settings > Simulation Setup**, in the **SIP Settings** card, enter the **SIP URI**. If your SIP endpoint uses digest authentication, open **Authentication (optional)** and enter the **Username** and **Password**. Otherwise leave them empty. Click **Verify & Save**. **3. Add the simulation step to your integration** Your integration has to send each call back with the ID Tuner put on it, so Tuner can link the call to the run. Follow **Enable simulation** on your [LiveKit](/docs/integrations/livekit#enable-simulation), [Pipecat](/docs/integrations/pipecat#enable-simulation) or [custom stack](/docs/integrations/custom-stack/sdk-quickstart#enable-simulation) integration page. On LiveKit, the SDK does this for you. ## Check it works Follow [Run your first simulation](/docs/simulation/overview#run-your-first-simulation). If calls show **Unreported**, the call reached your agent but didn't link back to the run. See [Fix an Unreported run](/docs/simulation/run-statuses#fix-an-unreported-run). Replays of your [Dataset](/docs/datasets/overview) calls reach your agent the same way, so once simulations connect, replays will too. Replays also work with [outbound simulation](/docs/simulation/outbound). ## How SIP works You don't need this to set up simulation. It helps when a call doesn't connect. > [accordion] What is SIP and why does Tuner use it? > > **SIP** (Session Initiation Protocol, [RFC 3261](https://datatracker.ietf.org/doc/html/rfc3261)) is the protocol voice platforms use to start, manage and end calls. Tuner uses it so simulated calls reach your agent through the same path as a real phone call: the same audio pipeline, transcription, prompt and tools. > [accordion] What happens when Tuner places a call > > 1. Tuner sends a SIP `INVITE` to your SIP URI. It carries a SIP `Call-ID` and an `X-Correlation-Id` header that Tuner generated for this call. > 2. If your SIP endpoint uses digest authentication, it replies with a `407 Proxy Authentication Required` challenge, and Tuner sends the `INVITE` again with your username and password. > 3. Your endpoint accepts the call and passes it to your agent. Audio flows both ways, and to your agent it's a normal inbound call. > 4. When the call ends, your integration sends it to Tuner with one of those IDs, and Tuner links it to the run. See [How simulated calls are linked](/docs/simulation/run-statuses#how-simulated-calls-are-linked). > > A typo in the URI sends the `INVITE` to the wrong place, and wrong credentials fail the `407` challenge. Either way, the call never connects. > [accordion] Anatomy of a SIP URI > > ```text theme={null} > sip:user-part@host > ``` > > * **`sip:`**: the scheme, like `https://` for web addresses. You may see `sips:` for SIP over TLS; paste it as shown. > * **`user-part`**: an identifier your provider assigns, such as Vapi's SIP Identifier or a Twilio or Telnyx credential username. Sometimes there isn't one and the host is enough. > * **`host`**: the public address of your SIP endpoint, for example `sip.vapi.ai`, `sip.telnyx.com` or `your-project.sip.livekit.cloud`. > > A URI can also carry parameters after the host, such as `;transport=tcp`. Copy whatever your provider's console shows. Tuner dials with the transport the URI names (`tcp`, `tls` or `udp`). A `sips:` URI without a `transport` parameter uses TLS. Without either, Tuner picks the transport itself. ## Next steps > [card] [Run a simulation](/docs/simulation/run-a-simulation) > > Every option in the Run Simulation dialog. > [card] [Run statuses](/docs/simulation/run-statuses) > > What each run status and call result means. # Set up outbound simulation Source: https://docs.usetuner.ai/docs/simulation/outbound Set up simulation for agents that place calls: Tuner triggers your endpoint, your agent dials the Simulated Caller, and the call links back to the run. > [!NOTE] > > Your agent must already be integrated with Tuner and sending real calls through [LiveKit](/docs/integrations/livekit), [Pipecat](/docs/integrations/pipecat), [Vapi](/docs/integrations/vapi), [ElevenLabs](/docs/integrations/elevenlabs) or a [Custom stack](/docs/integrations/custom-stack/overview), with its **Call Direction** set to **Outbound**. You configure outbound simulation in **Agent Settings > Simulation Setup**. Outbound simulation tests agents that **place** calls. Tuner can't call into an outbound agent, so the flow is reversed: Tuner tells your system **who to call**, and your agent calls the **Simulated Caller** that plays the customer in each Scenario. For LiveKit, Pipecat and Custom stack agents, "who to call" is a [SIP URI](/docs/simulation/inbound/setup#how-sip-works) such as `sip:@sip.usetuner.ai`, where `` is a 26-character ID unique to the Scenario, instead of a phone number like `+15551234567`. It goes in the same field your API already uses for the number, and your platform dials it like any other call. Vapi and ElevenLabs agents use a phone number on their platform instead; see [Vapi](#vapi) and [ElevenLabs](#elevenlabs). ## Find your platform | Your agent runs on | What to do | | - | - | | Vapi | Give Tuner a Vapi phone number to call from. No trigger endpoint or code. See [Vapi](#vapi). | | ElevenLabs | Give Tuner an ElevenLabs SIP trunk number that dials Tuner. No trigger endpoint or code. See [ElevenLabs](#elevenlabs). | | LiveKit, Pipecat or a custom stack | Give Tuner the endpoint that starts your outbound calls, and send the dialed SIP URI back as `recipient`. See [Configure the trigger endpoint](#configure-the-trigger-endpoint) and [Send the call back with `recipient`](#send-the-call-back-with-recipient). | | Retell or Dograh | Outbound simulation isn't available. | The rest of this page covers the trigger endpoint, then Vapi and ElevenLabs. ## How it works 1. **You describe your call-starting API to Tuner, once.** Every outbound agent has an endpoint that starts a call. You give Tuner that endpoint, and Tuner uses it for every simulated call. 2. **Tuner builds the Scenarios.** Each run generates Simulated Callers with a persona, an intent and something to test, the same as inbound simulation. Each gets its own SIP URI. 3. **Tuner triggers your endpoint once per Scenario**, putting the SIP URI where your body expects the number, plus any Scenario and test profile values you ask for. 4. **Your agent dials and the conversation happens.** From your agent's side this is an ordinary outbound call. 5. **You sync the call back with the SIP URI in `recipient`.** See [How simulated calls are linked](/docs/simulation/run-statuses#how-simulated-calls-are-linked). 6. **Your production evals run**, and results appear on the **Runs** tab of **Simulations**. See [Run statuses](/docs/simulation/run-statuses). ## Configure the trigger endpoint Open **Agent Settings > Simulation Setup**. The **Outbound Trigger Endpoint** card is where you describe your API to Tuner: ![Agent Settings, Simulation Setup, Outbound Trigger Endpoint](https://mintcdn.com/tuner/u_QkO-I-xmqsmFti/images/simulation/outbound-simulation-general.png?fit=max\&auto=format\&n=u_QkO-I-xmqsmFti\&q=85\&s=05654a1c1de8bd09725535b9769dca2d) **1. Enter the Trigger URL** **Trigger URL** is the endpoint on your side that places an outbound call. Tuner always sends a `POST` with `Content-Type: application/json`. * It must use `https`. * Its host must resolve to a public address. Private, internal and loopback addresses are rejected. **2. Add headers** Under **Headers**, click **Add Header** for each header your endpoint needs, such as an `Authorization` token. Enter the **Key** and **Value**. In a header value, `{{integration.api_key}}` is replaced with the API key saved on your agent's integration when Tuner triggers a call. **3. Write the body** **Body** is a JSON template in **your** endpoint's shape. The key names are yours (`destination`, `to`, `phoneNumber` and so on). Put each placeholder inside a JSON string, and Tuner replaces it before sending: | Placeholder | Required | Replaced with | | - | - | - | | `{{sipUriToDial}}` | Yes | The SIP URI of the Simulated Caller. This is the number your system dials. | | `{{scenario.intent}}` | No | The Scenario's intent, exactly as written in **Analysis Setup > Call Intents**. Make sure your agent reads the same string. | | `{{profile.}}` | No | The value of `` in the run's [test profile](/docs/simulation/test-profiles). A key the profile doesn't have, or a run without a profile, gives an empty string. | The body must be valid JSON and include `{{sipUriToDial}}`, or **Save** stays disabled. **4. Save** Click **Save**. Tuner checks the endpoint before it saves: it sends a `POST` to the **Trigger URL** with your headers as entered and no body. Saving fails if the URL can't be reached, the check takes longer than 15 seconds, or the endpoint returns `401`, `403`, `404`, `410`, `503` or `504`. Once saved, every simulation run triggers your endpoint once per Scenario. ### Example Say your endpoint takes a `destination` and dials it. Somewhere inside, there's a line like this (LiveKit shown, same concept on any stack): ```python theme={null} await ctx.api.sip.create_sip_participant( api.CreateSIPParticipantRequest( sip_call_to=destination, # the phone number, or Tuner's SIP URI in simulation ... ) ) ``` In Tuner, you mirror that endpoint with `{{sipUriToDial}}` in the `destination` field, since that's where the number normally goes: **Trigger URL** ```text theme={null} POST https://api.yourdomain.com/voice/outbound ``` **Headers** | Key | Value | | - | - | | `Authorization` | `Bearer YOUR_TOKEN` | **Body** ```json theme={null} { "destination": "{{sipUriToDial}}", "task": "{{scenario.intent}}", "customerName": "{{profile.caller_name}}" } ``` ![The example endpoint configured in Tuner, Agent Settings > Simulation Setup](https://mintcdn.com/tuner/u_QkO-I-xmqsmFti/images/simulation/outbound-simulation-example.png?fit=max\&auto=format\&n=u_QkO-I-xmqsmFti\&q=85\&s=8eecd0a94eba702c22bb7a9772b4dcf2) ## Send the call back with `recipient` When your integration syncs the finished call to Tuner, the dialed SIP URI must be in the **`recipient`** field, **exactly as Tuner sent it**. Whatever key you put `{{sipUriToDial}}` under, that's the value to send back. Tuner links the call on the token in the URI, so a phone number or another SIP URI doesn't link. If the SIP Call-ID of the call reaches Tuner unchanged, Tuner can also link on that. Don't rely on it, because a carrier or proxy between your agent and Tuner can change it. Set it up on your integration page: [LiveKit](/docs/integrations/livekit#enable-simulation), [Pipecat](/docs/integrations/pipecat#enable-simulation) or [Custom stack](/docs/integrations/custom-stack/sdk-quickstart#enable-simulation). For a custom stack, send the value as `recipient` in the [Create Call API](/api-reference/calls/create-call) payload. > [!TIP] > > Want evals to use the intent or test profile values? Echo them back in the call's metadata when you sync: `extra_metadata` on the LiveKit plugin or Pipecat observer, or `metadata` in the Create Call payload. See [Evaluating agents with dynamic instructions](/docs/evaluation/dynamic-agents). ## Vapi Vapi outbound agents don't use a trigger endpoint. Tuner starts each call through Vapi's API from your assistant (the agent's Agent Remote ID), using your Vapi integration's API key and a Vapi phone number that dials Tuner. You give Tuner that number's **VAPI Phone Number ID**. Open **Agent Settings > Simulation Setup**. Under **Do you already have a VAPI Phone Number ID?**, choose one: > [tab] Yes, I have one > > Enter the phone number resource ID from your Vapi dashboard in **VAPI Phone Number ID** and click **Save**. Tuner checks that the number exists in your Vapi account before it saves. > [tab] No, I don't have one > > Run the 3-step setup: > > 1. Paste your **Vapi API key** (from **Org Settings > API Keys** in Vapi) and click **Continue**. Tuner uses it only in this browser session to run the steps below and never saves it. > 2. **Create SIP Trunk Credential**: click **Approve & Run** to create a SIP trunk in Vapi that points to Tuner's simulation endpoint. > 3. **Register Phone Number**: click **Approve & Run** to register a phone number in Vapi linked to that trunk. > 4. **Save to Tuner**: click **Save to Tuner** to save the new phone number ID to your outbound config. > > Each step also shows the `curl` command it runs, which you can copy and run yourself. To change the number later, edit **VAPI Phone Number ID** and click **Save**. ## ElevenLabs ElevenLabs outbound agents don't use a trigger endpoint. Open **Agent Settings > Simulation Setup**. The **Outbound Trigger Endpoint** card shows an **ElevenLabs Phone Number ID** field. Choose one: > [tab] Let Tuner create it > > When no number is saved, the card shows **What Tuner creates in ElevenLabs**, a preview of the request Tuner sends to ElevenLabs, with your API key hidden. Click **Create phone number**. > > Tuner uses your saved ElevenLabs API key to create a SIP trunk number labeled `Tuner Outbound`, assigned to your agent, with Tuner's SIP host as its outbound address. If your account already has a `Tuner Outbound` number that points at Tuner, Tuner reuses it. Tuner then saves the number's ID to your outbound config. A message says **ElevenLabs phone number created.** or **Reused existing ElevenLabs phone number.** > [tab] Use an existing number > > Create a SIP trunk phone number in ElevenLabs with Tuner's SIP host as its outbound address. In Tuner, enter the number's ID in **ElevenLabs Phone Number ID** and click **Save**. > > Tuner checks that the number exists in your ElevenLabs account, that it's a SIP trunk number, and that its outbound address host is Tuner's SIP host. If a check fails, the error shows under the field. If the host doesn't match, the card shows **This number doesn't route calls to Tuner, so simulations can't reach your agent.** Click **Fix automatically** to have Tuner create its own number instead. To change the number later, edit **ElevenLabs Phone Number ID** and click **Save**. If no number is saved, the [Run a simulation](/docs/simulation/run-a-simulation) dialog asks you to configure your **ElevenLabs Phone Number ID** before the run starts. Click **Configure →** to open **Simulation Setup**. Once a number is saved, the dialog shows it under **Calls triggered via:** as `ElevenLabs · `. Tuner starts each call through ElevenLabs' outbound call API from your agent (the agent's Agent Remote ID), using your ElevenLabs API key and the saved number. The number's outbound trunk address must be Tuner's SIP host, so ElevenLabs dials the Simulated Caller through Tuner. If ElevenLabs accepts a call request but can't place the call, Tuner counts it as a failed dial. Check the number's outbound trunk address and the agent ID. Before it places each call, Tuner checks that your ElevenLabs account has credits left. If it has none, Tuner doesn't place the call and marks it failed. See [Troubleshooting](#troubleshooting). ## Limits | Limit | Value | | - | - | | **Trigger URL** length | 2,048 characters | | Header **Key** length | 200 characters | | Header **Value** length | 2,048 characters | | Endpoint check on **Save** | 15 seconds | | ElevenLabs retries after a rate-limit error, per call | 3 | The outbound config is also available through the public API: see [Save Outbound Config](/api-reference/agent-settings/save-outbound-config) in the **Agent Settings** group of the API Reference. ## Troubleshooting > [accordion] Simulated calls show up as ordinary production calls > > The synced call's `recipient` didn't match the SIP URI Tuner sent: it was never set, was modified (for example cut down to a phone number), or a different value was sent. A call is linked only when Tuner first saves it, so run the Scenario again after you fix it. Compare the URI your endpoint received byte for byte with the `recipient` on the synced call. In the run, these calls show as **Unreported**. > [accordion] Tuner triggers my endpoint but no call arrives > > The dial failed on your side. Check your platform's logs, and confirm your trunk can dial a SIP URI. Some configurations only allow phone numbers. > [accordion] Save fails with a Trigger URL error > > Tuner checks the endpoint when you click **Save**. Confirm the URL uses `https`, is publicly reachable, accepts a `POST` with the **Headers** you entered and an empty body, and responds within 15 seconds without `401`, `403`, `404`, `410`, `503` or `504`. > [accordion] My endpoint returns an error to Tuner > > Check the **Headers** saved in **Simulation Setup**, and confirm the body template matches the shape your endpoint expects. > [accordion] ElevenLabs calls fail because the account is out of credits > > Tuner checks your ElevenLabs credits before each call. If the account has none left, Tuner doesn't place the call. If ElevenLabs refuses a call request or ends a call because the account is out of credits or over its quota, Tuner fails that call for the same reason. > > When every call in the run fails before it's placed, the run card says **Your ElevenLabs account is out of credits or over its quota. Top up or raise the limit in ElevenLabs, then run again.** Top up or raise the limit in ElevenLabs, then run the Scenarios again. > [accordion] ElevenLabs calls fail because of a concurrent call limit > > ElevenLabs refuses new calls when your plan's concurrent call limit is reached. Tuner waits and retries the call up to 3 times. If ElevenLabs still refuses it, the call fails. > > When every call in the run fails this way, the run card says **ElevenLabs refused the calls because your plan's concurrent call limit was reached. Run fewer scenarios at once or raise the limit in ElevenLabs, then run again.** Run fewer Scenarios at once, or raise the limit in ElevenLabs. ## Next steps > [card] [Run a simulation](/docs/simulation/run-a-simulation) > > Configure your Simulation Mix and start a run. > [card] [Test Profiles](/docs/simulation/test-profiles) > > Give the Simulated Caller an identity and pass its fields to your endpoint. # Introduction to Call Simulation Source: https://docs.usetuner.ai/docs/simulation/overview What Call Simulation is, what your setup needs, and how to run your first simulation. > [!NOTE] > > Call Simulation lives under **Simulations** in the Tuner app. You need an agent that's already [connected to Tuner](/docs/getting-started/quickstart) and sending real calls. Then set up [inbound](/docs/simulation/inbound/setup) or [outbound](/docs/simulation/outbound) simulation so Tuner can reach it. ## What is Call Simulation? Call Simulation places real voice calls between your agent and a **Simulated Caller** that plays a customer. It works in both call directions: **inbound**, where Tuner calls your agent over SIP, and **outbound**, where Tuner triggers your endpoint and your agent calls the Simulated Caller. Each call is scored with the evals, Call Outcomes and Intents you've already set up for your live agent. There's no separate scoring to configure. ![The simulation landing page before your first run](https://mintcdn.com/tuner/ymjXbsRhUG5GDj0_/images/simulation/empty-state.png?fit=max\&auto=format\&n=ymjXbsRhUG5GDj0_\&q=85\&s=a17834489b904925df0c691b91825105) ## What your setup needs | Setup | Inbound simulation | Outbound simulation | | - | - | - | | [Retell](/docs/integrations/retell#enable-simulation) | [No setup](/docs/simulation/inbound/setup#retell) | Not available | | [Vapi](/docs/integrations/vapi#enable-simulation) | [Add the SIP URI in Tuner](/docs/simulation/inbound/setup#vapi) | [A **VAPI Phone Number ID** or the in-app wizard](/docs/simulation/outbound#vapi), no code | | [LiveKit](/docs/integrations/livekit#enable-simulation) | [Add the SIP URI in Tuner](/docs/simulation/inbound/setup#livekit-pipecat-and-custom-stacks), no code (SDK 0.1.11+) | [Add the trigger endpoint in Tuner](/docs/simulation/outbound#configure-the-trigger-endpoint), then [pass `recipient`](/docs/integrations/livekit#enable-simulation) (Python SDK only) | | [Pipecat](/docs/integrations/pipecat#enable-simulation) | [Add the SIP URI in Tuner](/docs/simulation/inbound/setup#livekit-pipecat-and-custom-stacks), then [forward and attach the SIP data](/docs/integrations/pipecat#enable-simulation) | [Add the trigger endpoint in Tuner](/docs/simulation/outbound#configure-the-trigger-endpoint), then [pass `recipient`](/docs/integrations/pipecat#enable-simulation) | | [Custom stack](/docs/integrations/custom-stack/sdk-quickstart#enable-simulation) | [Add the SIP URI in Tuner](/docs/simulation/inbound/setup#livekit-pipecat-and-custom-stacks), then [send the SIP data](/docs/integrations/custom-stack/sdk-quickstart#enable-simulation) | [Add the trigger endpoint in Tuner](/docs/simulation/outbound#configure-the-trigger-endpoint), then [send `recipient`](/docs/integrations/custom-stack/sdk-quickstart#enable-simulation) | | Dograh | [Add the SIP URI in Tuner](/docs/simulation/inbound/setup#dograh) (Dograh v1.48.0+) | Not available | ## Run your first simulation **1. Set up your agent once** Do the step for your setup and call direction in the table above. **2. Start a run** Go to **Simulations** and click **Run Simulation**. The defaults are a good first run: **AI generated** Scenarios, 10 calls with 30% Pressure tests, and a 3-minute max call duration. To change them, see [Run a simulation](/docs/simulation/run-a-simulation). **3. Run** The dialog shows the credit rate per minute and your balance. Click **Run**. **4. Read the results** The run appears on the **Runs** tab with a status and a result for each call. Click a call to see its transcript and eval results. If calls show **Unreported**, Tuner didn't receive the matching call from your integration. See [Fix an Unreported run](/docs/simulation/run-statuses#fix-an-unreported-run). ## What you can customize Every run is set in the **Run Simulation** dialog. For example, you can: * **Change the mix** of Routine callers and Pressure tests, and the number of calls (5 to 20). * **Narrow the targets** to the Intents or Pass/Fail evals you just changed. * **Pick the language and accent** the Simulated Caller speaks. * **Add background noise**, like a café or a car, at low, medium or high intensity. * **Attach a test profile**, so the Simulated Caller has a name, account details or a reason for calling. * **Cap the call length** between 1 and 12 minutes. > [card] [Explore every option in Run a simulation](/docs/simulation/run-a-simulation) > > Each setting explained, with the 6 languages and 14 accents, the four noise environments and the run limits. ## Three ways to test The first run uses AI-generated Scenarios. You can also rerun saved ones or replay real calls. > [card] [Generated runs](/docs/simulation/run-a-simulation) > > Tuner writes new Scenarios each run: Routine callers from your Intents and Pressure tests from your Pass/Fail evals. > [card] [Scenario Library](/docs/simulation/scenarios) > > Save Scenarios and rerun the same ones to check a fix. > [card] [Replays](/docs/simulation/replays) > > Play the caller's recorded turns from a real call into a live call with your agent. ## FAQ > [accordion] Does simulation cost credits? > > Yes. Simulation is billed per minute of connected call time. You're charged only for calls that connected and ended normally: the call was hung up, it reached the max call duration, or, for a replay, every caller turn was played. Calls that never connect or end on an error aren't charged. The rate is shown in the **Run Simulation** dialog before you start. See [Credits and usage](/docs/resources/credits). > [accordion] Can I run simulation on an agent that's already in production? > > Yes. Simulation calls are excluded from the metrics on the Overview dashboard. > [accordion] Why does my run show Unreported? > > Tuner placed the calls, but your integration didn't send them back with the ID Tuner put on them, so Tuner couldn't link them to the run. See [Fix an Unreported run](/docs/simulation/run-statuses#fix-an-unreported-run). ## Next steps > [card] [Run a simulation](/docs/simulation/run-a-simulation) > > Every option in the Run Simulation dialog: the mix, targets, language, noise and test profiles. > [card] [Run statuses](/docs/simulation/run-statuses) > > What each status and call result means, and how to fix a run. # Replays Source: https://docs.usetuner.ai/docs/simulation/replays Replay a real call from your Dataset against your agent with the exact same caller audio, to reproduce a failure, prove a fix, or compare two setups. ## What is a replay? When you change your agent, you need to know what got better and what broke. A replay plays a call from your [Dataset](/docs/datasets/overview) back to your agent, and Tuner scores it with your evals, so you can compare the result with the run before. Use replays to: * Reproduce a call that failed. * Prove that a fix worked. * Compare two setups, like a new model or provider, on the same calls. ![The same Dataset call replayed three times before a fix, failing every time, and three times after it, passing every time](https://mintcdn.com/tuner/SUvdaDyWHmpRoVGZ/images/datasets/fix-before-after.png?fit=max\&auto=format\&n=SUvdaDyWHmpRoVGZ\&q=85\&s=4c6754303d4679a0993f0d7884486843) *** ## Dataset or Scenario Library? Tuner has two ways to test your agent again, and they are separate features. What differs is the caller. > [card] [Dataset](/docs/datasets/overview) > > The caller is a recording of a real call, played back exactly as it was said. You replay it from the **Replays** tab. > [card] [Scenario Library](/docs/simulation/scenarios) > > The caller is a Simulated Caller who follows a Scenario you saved. You rerun it from the **Scenarios** tab. | | Dataset | Scenario Library | | - | - | - | | **Built from** | Real calls: a production call, or a recording you upload | A Custom Scenario you write, or one saved from a simulation run | | **The caller is** | The real caller's recorded audio | A Simulated Caller following the Scenario | | **Same caller every run?** | Yes, the recorded audio is identical | No, the caller improvises: similar, not identical | | **Language, noise, test profile** | Whatever the real call had | Chosen on every run | | **Agents** | Inbound and outbound | Inbound and outbound | | **Where** | **Dataset** and **Replays** tabs | **Scenarios** and **Runs** tabs | | **Best for** | Reproducing a real failure, proving a fix, comparing setups | Regression Runs after every change, and edge cases you write yourself | *** ## Replay a Dataset call **1. Pick the calls to replay** Go to **Simulations > Replays** and click **New Replay**. Next to **Calls**, click **Change** and tick up to 10 Dataset calls. * Calls that are still extracting, or that failed, can't be picked. Add at least one **Ready** call to your [Dataset](/docs/datasets/add-calls) first. * Replays run against inbound and outbound agents. Set up [inbound](/docs/simulation/inbound/setup) or [outbound](/docs/simulation/outbound) simulation first. Outbound simulation isn't available for Retell and Dograh, so their agents replay inbound only. ![The New Replay dialog with three Dataset calls selected, each replayed three times](https://mintcdn.com/tuner/bVl6uahM1YhEolIF/images/simulation/new-replay.png?fit=max\&auto=format\&n=bVl6uahM1YhEolIF\&q=85\&s=c37c891883c371ec6c98af1b2bd9dfc6) **2. Run it** Tuner calls your agent and plays each caller turn from the recorded call. * Set **Times to replay each call** (1 to 20, at most 20 calls in total) and **Max call duration** (1 to 12 minutes). **Longest possible call** warns you if a call won't fit. * Click **Run**. The run appears on the **Replays** tab and fills in as calls finish. * Tuner waits for your agent's greeting, plays each caller turn in full, even if your agent talks over it, and waits for your agent's reply before the next turn. After the last turn it waits for one more reply, then hangs up. A call also ends if your agent hangs up or it reaches the max call duration. * The caller never reacts to what your agent says. They say what they said in the original call. See [The caller doesn't adapt](/docs/datasets/use-cases/capturing-failures#the-caller-doesnt-adapt). * To change how long Tuner waits for your agent, see [Turn-taking settings](#turn-taking-settings). **3. Read the results** Every replay is graded, so you can see what changed. ![A replay run with nine calls: six passed and three failed](https://mintcdn.com/tuner/bVl6uahM1YhEolIF/images/simulation/replays-tab.png?fit=max\&auto=format\&n=bVl6uahM1YhEolIF\&q=85\&s=ede1ba6f055a2469f1ba2b436ac9b542) * Each run card shows how many calls **passed** and **failed**, and the calls, repeats, and turn-taking settings it used. * Every call is graded against all of your agent's **Pass/Fail** evals. A green check means none failed. A red X means at least one failed, or the call didn't run. If your agent has no Pass/Fail evals, calls count as **ran** and the run measures latency only. * Each call also gets a [transcription accuracy](#transcription-accuracy) score. * Click a row to open the call. A **Replay call** banner names the Dataset call it came from, and **Replay details** shows the source call and the exact settings used. The recording is stereo: caller on the left, agent on the right. * To compare two setups, keep the same calls, repeats, max call duration, and turn-taking settings, then compare the run cards and open matching calls. There's no side-by-side view yet. See [Benchmarking](/docs/datasets/use-cases/benchmarking#compare-two-setups). ![The Replay call banner on a call's details page](https://mintcdn.com/tuner/bVl6uahM1YhEolIF/images/simulation/replay-call-banner.png?fit=max\&auto=format\&n=bVl6uahM1YhEolIF\&q=85\&s=26a6bb9200eeafed127a2f29dd8f84b5) *** ## Transcription accuracy A replay plays the same caller audio every time, so Tuner knows what the caller said. It compares the reference transcript of each caller turn with what your agent's speech-to-text heard, and scores the result as a percentage with a **Good**, **Fair** or **Poor** rating. To read it, open a replay call and go to the **Voice Metrics** tab. The **Transcription accuracy** card lists the words your agent misheard, missed or added. See [Transcription accuracy](/docs/observability/voice-metrics#transcription-accuracy) for every part of the card. The score depends on the reference transcripts. Before you trust it, [verify the transcripts](/docs/datasets/add-calls#edit-and-verify-transcripts) of the Dataset call. After you edit one, click **Recalculate** on the card to update a call that was already scored. *** ## Turn-taking settings This is optional. Expand **Advanced turn-taking** in **New Replay** to change how long Tuner waits for your agent. ![Advanced turn-taking settings with the default values](https://mintcdn.com/tuner/bVl6uahM1YhEolIF/images/simulation/replay-turn-taking.png?fit=max\&auto=format\&n=bVl6uahM1YhEolIF\&q=85\&s=1b9439f5ab45f469a34168f2effee594) | Setting | Default | What it does | | - | - | - | | **Initial agent wait (ms)** | 12,000 | How long to wait for the agent's greeting before the first caller turn | | **Silence threshold (ms)** | 700 | How much silence counts as the agent having finished | | **Minimum speech (ms)** | 250 | Agent speech shorter than this doesn't count as a reply | | **Inter-turn delay (ms)** | 300 | The pause before the next caller turn plays | | **Max wait (ms)** | 15,000 | The longest Tuner waits for the agent before moving on | *** ## Limits | Limit | Value | | - | - | | Per run | 1 to 10 calls, each 1 to 20 times, at most 20 calls in total | | Max call duration | 1 to 12 minutes | | Runs in progress per agent | 1, shared by all simulation runs. A run whose calls have all ended (for example, one that's **Analyzing**) doesn't block a new one. | Replays are also available through the public API, in the **Replay testing** group of the API Reference: [Create Replay Run](/api-reference/replay-testing/create-replay-run) and [List Replay Runs](/api-reference/replay-testing/list-replay-runs). To score a call again after you edit a transcript, use [Recalculate Transcription Accuracy](/api-reference/calls/recalculate-transcription-accuracy) in the **calls** group. ## Next steps > [card] [Introduction to Datasets](/docs/datasets/overview) > > Save the calls you want to replay: failures, hard callers, and edge cases. > [card] [Scenario Library](/docs/simulation/scenarios) > > Write a Scenario once, rerun it on every change, and catch Failures before your callers do. # Run a simulation Source: https://docs.usetuner.ai/docs/simulation/run-a-simulation Start a simulation run from the Run Simulation dialog: choose Scenarios, set the Simulation Mix, and set the language, background noise, test profile and max call duration. > [!NOTE] > > Runs start from **Simulations** in the Tuner app. Your agent needs [inbound](/docs/simulation/inbound/setup) or [outbound](/docs/simulation/outbound) simulation set up first. See [What your setup needs](/docs/simulation/overview#what-your-setup-needs). ## Start a run **1. Choose what to run** Go to **Simulations** and click **Run Simulation**. Next to **Scenarios:**, keep **AI generated** to have Tuner write new Scenarios, or click **Change ›** and choose **From library** to rerun saved ones (see [Scenario Library](/docs/simulation/scenarios)). For AI-generated Scenarios, set **Number of simulations** (5 to 20, default 10) and drag the **Simulation mix** slider between **All routine** and **All pressure**. The default is 30% Pressure tests. See [The Simulation Mix](#the-simulation-mix). ![Run Simulation dialog, set count, mix, targets, and language](https://mintcdn.com/tuner/WNxh86kKl8WHmepD/images/simulation/run-simulation-modal.png?fit=max\&auto=format\&n=WNxh86kKl8WHmepD\&q=85\&s=e8065312b469ffeacf13c24dcfaec771) **2. Narrow the targets (optional)** Click **Narrow down ›** next to **Routine callers cover:** to limit Routine callers to some of your Intents, or next to **Pressure tests target:** to limit Pressure tests to some of your Pass/Fail evals. Unselected Intents and evals don't get Scenarios in this run. ![Choose which evals Pressure Tests should target](https://mintcdn.com/tuner/ymjXbsRhUG5GDj0_/images/simulation/pressure-test-targets.png?fit=max\&auto=format\&n=ymjXbsRhUG5GDj0_\&q=85\&s=9910c151c93e75ef0acf4b7de7802728) **3. Set up the calls** Under **Call settings**: * **Max call duration**: use **-** and **+** to cap each call (1 to 12 minutes, default 3). See [Max call duration](#max-call-duration). * **Language:** click **Change** to pick the language and accent the Simulated Caller speaks. See [Languages and accents](#languages-and-accents). * **Environment:** click **Change ›** to add [background noise](#background-noise). The default is **No environment**. * **Test profile:** click **Change** to give the Simulated Caller a [test profile](#test-profiles). The default is **No profile**. ![Choose simulation language and accent](https://mintcdn.com/tuner/WNxh86kKl8WHmepD/images/simulation/simulation-language-accent.png?fit=max\&auto=format\&n=WNxh86kKl8WHmepD\&q=85\&s=6b72816512d30149d9f39d7277e0ab41) **4. Run** The dialog shows the credit rate per minute and your balance. Click **Run**. The run appears on the **Runs** tab. See [Run statuses](/docs/simulation/run-statuses). ## The Simulation Mix | | Routine callers | Pressure tests | | - | - | - | | **What they do** | Play your everyday customers: cooperative, on topic, working through your agent's normal workflows | Play the difficult ones: unhappy customers, edge cases, people trying to get around your process or asking for something out of scope | | **What you learn** | How your agent handles the expected path | Where your agent breaks: hallucination, scope boundaries, escalation handling and other failure modes | | **How they're generated** | From your agent's configured Intents | From your agent's Pass/Fail evals | The same intent said in different ways produces different conversations. Running more calls covers more of these variations. Every new run also checks that something you already fixed hasn't broken again. To rerun the exact same Scenarios, save them to your [Scenario Library](/docs/simulation/scenarios). ## Max call duration **Max call duration** caps how long any single simulated call can run, from 1 to 12 minutes (default 3). A call ends when your agent hangs up or the cap is reached, so the cap keeps a Simulated Caller from looping against an agent that's stuck. ## Languages and accents In the **Run Simulation** dialog, click **Change** next to **Language:** to choose the language and accent of the Simulated Caller. | Language | Accents | | - | - | | **Arabic** | **AE**, **EG**, **SA** | | **English** | **AU**, **UK**, **US** | | **French** | **CA**, **FR** | | **German** | **AT**, **CH**, **DE** | | **Hindi** | **IN** | | **Italian** | **IT** | | **Spanish** | **ES**, **MX** | Use this to test multilingual agents, or to check your agent still performs when callers have a different accent from your default. ## Background noise Background noise mixes an ambient recording into the Simulated Caller's side of the call, so you can see how your agent's transcription and turn-taking hold up when the caller is in a café or driving. In the **Run Simulation** dialog, click **Change ›** next to **Environment:**, pick **Café**, **Office**, **Street** or **Car**, and set the **Noise intensity** to **Low**, **Medium** or **High**. ![Environment selector in the Run Simulation dialog, showing No environment, Café, Office, Street, and Car](https://mintcdn.com/tuner/NLZ7V1-Ab8zhXrfm/images/backgroundNoise.png?fit=max\&auto=format\&n=NLZ7V1-Ab8zhXrfm\&q=85\&s=3de4123b6005389a49684d33adcdb7be) Intensity works the same way across every environment, so Street at Low and Café at Low sit at the same level against the caller's voice. The noise runs for the whole call, including while the caller is silent, so your agent hears it during its own turns too. It applies the same way to inbound and outbound simulations, since it's mixed into the Simulated Caller's audio. The setting applies to every call in the run and shows on the run card, so you can tell which conditions a result came from. Leave it at **No environment** to test on clean audio. ## Test profiles A **test profile** gives the Simulated Caller a specific identity and context before the call starts, such as a new user, an angry repeat caller or someone in a rush. Each profile is a name plus key-value fields, like `caller_name`, `issue` or `appointment_date`. Create profiles on the **Test Profiles** tab of **Simulations**, then pick one next to **Test profile:** in the **Run Simulation** dialog. It applies to every call in the run. ![Test Profiles list showing New User, Angry User, and Rushed User profiles](https://mintcdn.com/tuner/PYCfj3jGJxD0uL63/images/testProf.png?fit=max\&auto=format\&n=PYCfj3jGJxD0uL63\&q=85\&s=875e71af58ed3238d8f9b357ebaf8be3) See [Test Profiles](/docs/simulation/test-profiles) for the full guide. ## Limits | Limit | Value | | - | - | | Number of simulations (AI generated) | 5 to 20, default 10 | | Simulation mix | 0% to 100% Pressure tests, default 30% | | Scenarios from library per run | 1 to 20 | | Max call duration | 1 to 12 minutes, default 3 | | Runs in progress per agent | 1, shared by all simulation runs. A run whose calls have all ended doesn't block a new one. | Simulation runs are also available through the public API: see [Run AI-Generated Scenarios](/api-reference/simulation/run-ai-generated-scenarios) and [Run Saved Scenarios](/api-reference/simulation/run-saved-scenarios) in the **Simulation** group of the API Reference. ## Next steps > [card] [Run statuses](/docs/simulation/run-statuses) > > What each run status and call result means. > [card] [Scenario Library](/docs/simulation/scenarios) > > Save Scenarios and rerun the same ones. # Run statuses Source: https://docs.usetuner.ai/docs/simulation/run-statuses What each simulation run status and call result means, how to fix Unreported and Analysis failed, and how simulated calls are linked to a run. A simulation run reports a status for the run and a result for each call. This page lists every value and how to fix runs that don't complete. ## Where runs appear Every simulation run appears as a card on the **Runs** tab of **Simulations**. The card header shows when the run started, what it ran (for example "7 routine · 3 pressure", or "5 from library", plus the language, test profile and environment), a counts line and a status badge. Click the card to expand it. ![An expanded run card on the Runs tab: the counts line "3 passed · 7 failed", the Complete badge, and the per-call table with result icons, Type, Evals, Outcome, Intent and duration](https://mintcdn.com/tuner/6TrbntNcJS8frrHh/images/simulation/run-card-expanded.png?fit=max\&auto=format\&n=6TrbntNcJS8frrHh\&q=85\&s=f8a322dfbbf177304b934bb349c88f0a) ## Run status | Status | Badge | What it means | | - | - | - | | **Generating** | Blue, spinner | Tuner is writing the Scenarios for this run. | | **Pending** | Blue, spinner | The Scenarios are ready and the calls haven't started. | | **Running** | Blue, pulsing dot | Calls are in progress. A run whose calls have all ended stays **Running** until the first call reaches Tuner from your agent. | | **Analyzing** | Blue, spinner | Every call has ended. Tuner is still waiting for at least one call to arrive from your agent or for its evals. | | **Complete** | Green | Every call ran and was analyzed. Check the counts line for how many passed. | | **Partial** | Amber | Some calls didn't run, went **Unreported** or hit **Analysis failed**, and the rest were analyzed (or the problems were of more than one kind). | | **Failed** | Red | No call was analyzed and every call failed to run, or the run itself failed. Expand the card to see the reason. | | **Unreported** | Amber, unplugged-cable icon | Every call ran, but none of them arrived from your agent. See [Fix an Unreported run](#fix-an-unreported-run). | | **Analysis failed** | Red, clipboard-with-X icon | Every call arrived, but evals couldn't be completed for any of them. See [Fix Analysis failed](#fix-analysis-failed). | Only **Unreported** and **Analysis failed** show a tooltip when you hover the badge. It says what went wrong and what to check, as in the fix sections below. ## Call results Expand a run to see one row per call, with the columns **#**, **Type** (**Routine** or **Pressure**), **Evals**, **Outcome**, **Intent** and **Dur.** The icon at the start of each row shows the call's result: | Result | Icon | What it means | | - | - | - | | **Passed** | Green check | A Routine call passes when none of its Pass/Fail evals failed. A Pressure call with a target eval passes or fails on that eval alone. | | **Failed** | Red X | An eval that decides the result failed, or the call didn't run. | | **Unreported** | Amber, unplugged-cable icon | The call ran, but no matching call arrived from your agent within 15 minutes. | | **Analysis failed** | Red, clipboard-with-X icon | The call arrived, but its evals didn't come back within 10 minutes. Results that arrive later are still scored. | | **Ran** | Green check | The call ran in a run with no evals to grade, for example a replay with no Pass/Fail evals selected. | | **Pending** | Gray clock, dashed circle | The call hasn't started or is still in progress. | | **Evaluating** | Blue spinner | The call ended and Tuner is analyzing it. | Hover an **Unreported** or **Analysis failed** icon for the same tooltip as on the run badge. Hovering a **Ran** check shows "Ran — no evals were expected for this run". The other icons have no tooltip. A call whose outcome has [**Stop Analysis**](/docs/evaluation/call-classification) turned on counts as done and shows **Passed**, since Tuner skips its evals. Once Tuner has received a call, click its row to open the [call details](/docs/observability/call-logs). On the **Scenarios** tab and on a Scenario's page, the same results show as **Passed**, **Failed**, **Unreported**, **Analysis failed** or **Pending**. ## Counts line The counts line next to the badge sums up the calls, for example "6 passed · 2 failed · 2 remaining". It can show: | Count | What it counts | | - | - | | **passed** and **failed** | Calls with a result. | | **ran** | Calls that ran in a run with no evals to grade. | | **remaining** | Calls still pending or being evaluated, while the run is **Pending**, **Running** or **Analyzing**. | | **not run** | Once the run has settled, calls that didn't run. | | **unreported** and **analysis failed** | Calls flagged with those results. These show as soon as a call is flagged, even while the rest of the run is still going. | ## Fix an Unreported run **Unreported** means Tuner placed the call but never received a matching call from your agent's integration. For ElevenLabs agents, Tuner fetches the agent's conversations from ElevenLabs once more when a call is flagged **Unreported**. If it finds the matching conversation, the call links and its result updates. A conversation that ElevenLabs ended because the account ran out of credits links this way and shows as **Failed**. **1. Look for the call** Open **Call Logs** and look for the call. **2. If it's there, check the link** Tuner couldn't match it to the simulation. Find your case in [Why a call doesn't link](#why-a-call-doesnt-link). **3. If it isn't there, check the integration** Check that your integration is sending calls to Tuner. ### Why a call doesn't link | What you see | Cause | Fix | | - | - | - | | Inbound LiveKit agent behind a carrier, proxy or bridge: the call is in **Call Logs** and the run shows **Unreported** | The hop starts a new SIP call with a new Call-ID, so only Tuner's `X-Correlation-Id` header can link the call. Either the hop doesn't copy the header, or the LiveKit inbound trunk drops it (the default). | Forward the header with `forward_to_sip` from your carrier webhook. See [LiveKit: Carrier in front of LiveKit](/docs/integrations/livekit#carrier-in-front-of-livekit). Then set the trunk's `include_headers` option. See [LiveKit: Enable simulation](/docs/integrations/livekit#enable-simulation). | | Inbound Pipecat or Custom stack agent behind Twilio or Telnyx: the call is in **Call Logs** and the run shows **Unreported** | Your webhook starts the media stream without Tuner's data, so neither the header nor the Call-ID reaches your bot. | In the webhook, pass `extract_sip(...)` to `forward_to_websocket(..., ws_url=...)`. It adds the data as Twilio `` parameters or Telnyx stream `custom_parameters`. In the bot, call `attach_sip(extract_sip(start, provider=...))`. See [Pipecat](/docs/integrations/pipecat#enable-simulation) and [Custom stack](/docs/integrations/custom-stack/sdk-quickstart#enable-simulation). | | Inbound ElevenLabs agent: the call is in **Call Logs** and the run shows **Unreported** | The conversation in ElevenLabs doesn't carry Tuner's `X-Correlation-Id` header. A hop between Tuner and ElevenLabs can drop it. | Check that the SIP URI in **Simulation Setup** points straight at `sip.rtc.elevenlabs.io`. If it does, contact support with the ElevenLabs conversation ID. | | Outbound: the call is in **Call Logs** and the run shows **Unreported** | `recipient` is missing or isn't the exact SIP URI Tuner sent to your trigger endpoint. | Send the URI back unchanged. See [Set up outbound simulation](/docs/simulation/outbound). | | You send a provider ID such as a Twilio `CallSid` as the Call-ID | Tuner links only on the values it generated. A provider's own ID doesn't match. | Send the SIP Call-ID or the `X-Correlation-Id` header. With a Tuner SDK, `extract_sip` picks the right field for each carrier. It uses the carrier ID only as a fallback, and that call still doesn't link. See [The Call-ID may arrive under a different name](#the-call-id-may-arrive-under-a-different-name). | | You sent the call to Tuner once, it didn't link, and you fixed the setup | A call is linked only when Tuner first saves it. Sending the same call again is rejected as a duplicate. | Run the Scenario again. | ### The Call-ID may arrive under a different name This applies when your integration sends the SIP Call-ID itself. On LiveKit, the Tuner SDK does this for you. When Tuner dials your agent, it sends a standard SIP `INVITE` that contains a `Call-ID` header: ``` INVITE sip:your-agent@provider.example SIP/2.0 Call-ID: 2jf9wCCXfwgxKkTOfLcEsA5LD6f ... ``` Your SIP provider accepts the call and surfaces the `Call-ID` to your application, which passes it back to Tuner. SIP is a standard, but every provider wraps it in its own platform, so the value may not arrive as sent: * **Renamed field**: the provider exposes it as `SipCallId` or `sip_call_id`. The value is the same, but the key differs. * **Nested inside metadata**: the value is inside an object such as `sip.headers["Call-ID"]`. * **Not forwarded by default**: if your agent gets audio from a carrier's media stream, for example Pipecat or a custom stack behind Twilio or Telnyx, the carrier sends the SIP data to your HTTP webhook and the audio to a separate WebSocket. You have to forward the fields to the WebSocket as custom parameters. * **Replaced with a provider ID**: the provider gives you its own identifier (a `CallSid`, `call_control_id` or `call_sid`). This isn't the Call-ID Tuner sent, and it doesn't link. * **New Call-ID on a new call leg**: a bridge, PBX or carrier that starts a new call generates a new Call-ID. In this case, send the `X-Correlation-Id` header instead. Tuner adds it to every inbound simulated call, and it links the call as long as your hop copies it: `forward_to_sip` for LiveKit, `forward_to_websocket` for media streams. With a Tuner SDK, `extract_sip(payload, provider=...)` handles the renamed `SipCallId` field, nested `custom_headers`, Twilio's `SipHeader_` prefix, and uses carrier IDs only as a fallback. Check your provider's documentation for how it surfaces SIP headers. When in doubt, capture a test call and inspect the raw payload your application receives. ## Fix Analysis failed **Analysis failed** means the call arrived but its evals couldn't be completed. Run the Scenario again. If it keeps happening, contact support. ## How simulated calls are linked When Tuner places or triggers a simulated call, it puts an ID on the call. Your integration sends the call to Tuner after it ends, with that ID. Tuner matches the ID to the simulated call and adds the call to the run. A call that isn't linked is still ingested, but it appears as production traffic and the simulated call shows **Unreported** after 15 minutes. ```mermaid theme={null} flowchart LR A["Tuner places or triggers
the call and adds an ID"] --> B["Your agent takes the call"] B --> C["Your integration sends the
call to Tuner with that ID"] C --> D{"Does the ID match a simulated
call of this agent?"} D -->|"Yes"| E["Linked: the call joins the run"] D -->|"No"| F["Saved as production traffic.
The run shows Unreported."] ``` | Agent | What Tuner sends | What links the call | Where to set it | | - | - | - | - | | Inbound (LiveKit, Pipecat, Custom stack, Dograh) | The `X-Correlation-Id` header and the SIP Call-ID of the call Tuner placed | Either the header, sent back as `sip_headers`, or the Call-ID, sent back as `sip_call_id` | [LiveKit](/docs/integrations/livekit#enable-simulation), [Pipecat](/docs/integrations/pipecat#enable-simulation), [Custom stack](/docs/integrations/custom-stack/sdk-quickstart#enable-simulation), [Dograh](/docs/integrations/dograh#enable-simulation) | | Outbound (LiveKit, Pipecat, Custom stack) | A SIP URI such as `sip:TOKEN@route` to your trigger endpoint | The `recipient`: that SIP URI, sent back exactly as received. The Call-ID also links when it arrives unchanged. | [LiveKit](/docs/integrations/livekit#enable-simulation), [Pipecat](/docs/integrations/pipecat#enable-simulation), [Custom stack](/docs/integrations/custom-stack/sdk-quickstart#enable-simulation) | | Retell and Vapi | Tuner links these calls itself | Nothing to set | | | ElevenLabs | Inbound: the `X-Correlation-Id` header, which ElevenLabs stores as the `sip_x_correlation_id` dynamic variable. Outbound: the conversation ID ElevenLabs returns when Tuner places the call, and the token Tuner sends as the number to dial. | Tuner reads these values from the conversation itself | Nothing to set | The rules Tuner applies: * **Only Tuner's own values link.** The `X-Correlation-Id` value must be 32 hexadecimal characters. The user part of the `recipient` SIP URI must be the 26-character token Tuner sent. A phone number, another SIP URI or a provider ID is ignored. * **The call's agent must match.** Tuner looks only at the simulated calls of the agent that sent the call. * **Direction doesn't matter.** Tuner tries every value your integration sends, whether the agent is inbound or outbound. * **A call is linked once.** Tuner links a call when it first saves it, and doesn't link it later. If the values you send match more than one simulated call, Tuner links none of them. > [accordion] Why a carrier can break the link > > A SIP header or Call-ID reaches your agent only if every hop keeps it. A trunk, session border controller or proxy can drop `X-` headers. A carrier that bridges the call starts a new SIP call, with a new Call-ID, and doesn't copy custom headers unless you tell it to. Tuner can't see what happens between its call and your agent, so a link that works on one provider can fail on another. If linking fails, compare the Call-ID and `X-Correlation-Id` on the call Tuner placed with what your integration reports. For Twilio and Telnyx, the SDKs' `forward_to_sip` and `forward_to_websocket` copy Tuner's data onto the next hop. ## Next steps > [card] [Scenario Library](/docs/simulation/scenarios) > > Save Scenarios from a run and rerun them to check a fix. > [card] [Call Logs](/docs/observability/call-logs) > > Open a simulated call's details once it reaches Tuner. # Scenario library Source: https://docs.usetuner.ai/docs/simulation/scenarios Write a Scenario once, rerun it on every change, and catch Failures before your callers do. Your Scenario Library is your regression suite for Voice AI. > [!NOTE] > > Your Scenario Library lives on the **Scenarios** tab under **Simulations**. To rerun Scenarios, you need an agent set up for [inbound](/docs/simulation/inbound/setup) or [outbound](/docs/simulation/outbound) simulation, and at least one Pass/Fail eval. ## What is the Scenario Library? Voice agents change all the time: a new prompt, a new model, a new voice. Any change can quietly break a call that used to work. The Scenario Library is how you check. It's where your Scenarios live, and together they are your regression suite. A Scenario is one saved situation for a Simulated Caller to play on a real voice call with your agent. Write it once, rerun it after every change, and Tuner scores each call with the same Evals you already use. A Scenario that passed last release and fails today shows up as a Failure. A normal simulation writes new Scenarios every time, and they live only inside that run. In the library, a Scenario is saved on its own, so you can keep it and rerun it whenever you want. ![The Scenarios tab with five saved Scenarios, showing each one's type, origin, tags, and last result](https://mintcdn.com/tuner/5O0FSWu22E_s5lB0/images/simulation/scenarios-tab.png?fit=max\&auto=format\&n=5O0FSWu22E_s5lB0\&q=85\&s=c7708b64e81c63cc1be4f02d09c1485b) *** ## Two ways to add a Scenario > [card] [Write a Custom Scenario](#write-a-custom-scenario) > > Write the situation yourself, like a rushed patient or a customer who keeps pushing back. You don't need to run anything first. > [card] [Save to library](#save-to-library-from-a-run) > > Keep an AI-generated Scenario from a simulation you already ran, like one that caught a Failure. Either way, you [rerun them](#rerun-after-every-change) the same way. *** ## Write a Custom Scenario **1. Open the Scenario editor** Go to **Simulations > Scenarios** and click **New scenario**. ![The New scenario form with a name, type, situation, goal, stop conditions, intent, target eval, and tags filled in](https://mintcdn.com/tuner/5O0FSWu22E_s5lB0/images/simulation/new-scenario.png?fit=max\&auto=format\&n=5O0FSWu22E_s5lB0\&q=85\&s=0ce3e7f221ce68a273750bbcf9def96a) **2. Describe the Scenario** Only **Name** and **Situation** have to be filled in. * **Type** is **Routine** for an everyday request or **Pressure** for a difficult caller. It's a label for scoring and filtering. Your **Situation** is what makes the Simulated Caller act that way, so describe any pushback there. * **Situation** is written to the caller, as "you": who they are, their mood, what they want, and how they react when things don't go their way. For example, "You're calling from your car to move your cleaning to Friday the fourteenth. The line is noisy and you're in a hurry." * **Goal**, **First line**, and **Stop conditions** are optional. They say what the caller is trying to get done, the first thing they say, and when they're done. A call still ends only when your agent hangs up or the max call duration is reached. **3. Choose how it's scored** * Pick an **Intent** if the call is about one of your agent's Intents. If your agent places calls, the Intent is also sent to your trigger endpoint as `{{scenario.intent}}`. See [Outbound simulation](/docs/simulation/outbound#configure-the-trigger-endpoint). * For a Pressure Scenario, pick a **Target eval**, the Pass/Fail eval the call is meant to trip. The Scenario passes or fails on that eval alone. * Add **Tags** to group and find your Scenarios later. **4. Save** Click **Save**, or **Save and run** to save it and open **Run Simulation** with this Scenario selected. To check what the Simulated Caller is told from your text, expand **Preview simulator prompt**. It's read-only and never blocks saving. In the app, a Scenario you write yourself is labeled **Manual**. *** ## Save to library from a run **1. Run a normal simulation** Start a run with **AI generated** Scenarios, as in [Run a simulation](/docs/simulation/run-a-simulation), and wait until its calls have ended. You can save from a run that's **Analyzing**, **Complete**, **Partial**, **Unreported** or **Analysis failed**. See [Run status](/docs/simulation/run-statuses#run-status). **2. Pick the Scenarios to keep** On the **Runs** tab, expand the run and tick the calls you want to keep, one or several. A bookmark marks calls that are already in your library. **3. Save to library** Click **Save to library**, give each one a name, and optionally add **Tags for all**. Calls that didn't connect can still be saved, since the Scenario itself is valid. Then click **Save 2 scenarios** (the number matches your selection). Your new Scenarios appear on the **Scenarios** tab, marked **Saved from run**. ![A finished simulation run with two calls selected and the Save to library button](https://mintcdn.com/tuner/bVl6uahM1YhEolIF/images/simulation/save-to-library.png?fit=max\&auto=format\&n=bVl6uahM1YhEolIF\&q=85\&s=e3ea4ef42549fe262a5176d2eab07c23) Tuner saves each call's **Situation**, **Goal**, **Stop conditions**, type, **Intent**, and **Target eval**. It doesn't save the language, background noise, or test profile, because you choose those each time you run. The call you saved from becomes the first entry in the Scenario's **Run history**, so you can compare later runs against the Failure it caught. *** ## Rerun after every change A run started from your library is a Regression Run. Do one at launch, after every deployment, after a prompt edit, after swapping an LLM, STT, or TTS provider, and any time a production call shows you a new edge case. **1. Pick the Scenarios to rerun** Use whichever is closest: * On the **Scenarios** tab, open a row's menu and click **Run this scenario**. * On a Scenario's own page, click **Run this scenario**. * In **Run Simulation**, click **Change** next to **Scenarios**, choose **From library**, tick up to 20 Scenarios, and click **Done**. ![The From library picker in Run Simulation with three Scenarios ticked](https://mintcdn.com/tuner/5O0FSWu22E_s5lB0/images/simulation/from-library.png?fit=max\&auto=format\&n=5O0FSWu22E_s5lB0\&q=85\&s=ab83f24a50a4633ec9c0d0d273d59328) **2. Set up the call and run** The **Run Simulation** dialog works as in any simulation. Choose the max call duration, language and accent, background noise, and test profile, then click **Run**. Each Scenario places one call, and you can rerun the same Scenario under different conditions each time. The dialog shows the number of calls and the credit rate before you run. *** ## Read the results The run appears on the **Runs** tab, marked with how many Scenarios came from your library. Every call is graded against all of your agent's **Pass/Fail** evals, and a Pressure Scenario with a **Target eval** passes or fails on that eval. * On the **Scenarios** tab, **Last result** shows how each Scenario did on its latest run: **Passed**, **Failed**, **Unreported**, **Analysis failed** or **Pending**. A call that never connected also shows **Failed**. See [Call results](/docs/simulation/run-statuses#call-results) for what each one means. * Click a Scenario to open it. **Run history** shows how it did on its last runs, like "Passed 3 of last 5 runs", with a **View call** link for each one. That's how you see when it passed, when it hit a Failure, and that your fix held. * The Simulated Caller follows the situation but improvises, so the wording and length of each call can differ. To play back the exact same caller audio, use a [replay of a Dataset call](/docs/simulation/replays) instead. ![A saved Scenario with its situation and goal, and a run history of three passes out of the last five runs](https://mintcdn.com/tuner/bVl6uahM1YhEolIF/images/simulation/scenario-history.png?fit=max\&auto=format\&n=bVl6uahM1YhEolIF\&q=85\&s=4a1bf79fbf29a086d3dc3396258aa1e5) *** ## Manage your Scenarios * **Search** by name, situation, goal, first line, or tag, and filter by **Routine** or **Pressure**. * **Edit** a Scenario at any time. Past runs keep the version they ran, so old results don't change. * **Duplicate** a Scenario to start a new one from a copy. * **Delete** a Scenario to remove it from the library and from new runs. Past results are kept. *** ## Limits | Limit | Value | | - | - | | Scenarios per run | 1 to 20, each runs once | | Max call duration | 1 to 12 minutes, default 3 | | Runs in progress per agent | 1, shared by all simulation runs. A run whose calls have all ended (for example, one that's **Analyzing**) doesn't block a new one. | | **Name** | 1 to 200 characters | | **Situation** | 1 to 8,000 characters | | **Goal** | Up to 2,000 characters | | **First line** | Up to 500 characters | | **Stop conditions** | Up to 1,000 characters | | **Tags** | Up to 20 per Scenario, each up to 50 characters | | Scenarios saved from a run at once | Up to 100 | Scenarios are also available through the public API. Building and managing them is in the **Scenarios** group of the API Reference, and rerunning them ([Run Saved Scenarios](/api-reference/simulation/run-saved-scenarios)) or saving them from a run ([Save Scenarios To Library](/api-reference/simulation/save-scenarios-to-library)) is in the **Simulation** group. ## Next steps > [card] [Replays](/docs/simulation/replays) > > Play back a real call from your Dataset with the exact same caller audio. > [card] [Introduction to Call Simulation](/docs/simulation/overview) > > Generate new Scenarios to find failures you haven't seen yet. # Test profiles Source: https://docs.usetuner.ai/docs/simulation/test-profiles Create test profiles that tell the Simulated Caller who they are and what they know before the call starts, and use them in simulation runs. > [!NOTE] > > Test profiles live on the **Test Profiles** tab under **Simulations**. They apply to simulation runs, so you need an agent set up for [inbound](/docs/simulation/inbound/setup) or [outbound](/docs/simulation/outbound) simulation to use them. ## What are test profiles? A **test profile** is a named set of key-value fields that the Simulated Caller is given before the call starts. With it, the caller can play a specific type of customer, such as a new user who doesn't know the product, an angry user on a repeat call, or someone in a rush, and refer to their own name, issue and reason for calling. Without a test profile, the Simulated Caller has no caller-specific context. * Profile data is **snapshotted when the run starts**. Editing or deleting a profile later doesn't change results from that run. * Profiles are **scoped to the agent**. Profiles created for one agent aren't visible to other agents in your workspace. *** ## The Test Profiles tab Go to **Simulations** and open the **Test Profiles** tab to manage profiles for your agent. ![Test Profiles list showing New User, Angry User, and Rushed User profiles with their field tags](https://mintcdn.com/tuner/PYCfj3jGJxD0uL63/images/testProf.png?fit=max\&auto=format\&n=PYCfj3jGJxD0uL63\&q=85\&s=875e71af58ed3238d8f9b357ebaf8be3) Each profile card shows: * **Profile name**: what you see when selecting it in the **Run Simulation** dialog. * **Field tags**: the key names defined in the profile (for example `caller_name`, `issue`, `urgency`). When no profiles exist yet, the tab shows **No test profiles yet**. *** ## Create a profile **1. Open the form** Click **Create Profile** on the **Test Profiles** tab. ![Create test profile modal with profile name and key-value field inputs](https://mintcdn.com/tuner/PYCfj3jGJxD0uL63/images/createtestProf.png?fit=max\&auto=format\&n=PYCfj3jGJxD0uL63\&q=85\&s=aff8d6e15e0302a8b42959b428813627) **2. Name the profile** Enter a **Profile name** that identifies the caller, for example *Angry User*, *New patient, first visit* or *Rushed Caller*. **3. Add fields** Under **Profile fields**, click **Add field** for each key-value pair. The **key** is the variable name (for example `caller_name`, `issue`, `urgency`) and the **value** is what the Simulated Caller knows (for example `Jane Doe`, `billing error`, `high`). * Keys start with a letter or underscore and contain only letters, numbers and underscores. Each key can appear once. * Values are plain strings, one level deep, with no nested objects. > [!NOTE] > > For **outbound agents**, you can also pass a field to your trigger endpoint: write `{{profile.}}` in the trigger body, for example `{{profile.caller_name}}`. Tuner replaces it with the field's value. A key the profile doesn't have, or a run without a profile, gives an empty string. See [Set up outbound simulation](/docs/simulation/outbound#configure-the-trigger-endpoint). **4. Save** Click **Save**. A profile needs a name and at least one field. *** ## Use a profile in a run In the **Run Simulation** dialog, under **Call settings**, click **Change** next to **Test profile:**. ![Run Simulation dialog showing Test profile selector with No profile, New User, Angry User, and Rushed User options](https://mintcdn.com/tuner/PYCfj3jGJxD0uL63/images/create_test_prof_run.png?fit=max\&auto=format\&n=PYCfj3jGJxD0uL63\&q=85\&s=e015ba990161315488dbaf475abd0405) Choose one: * **No profile**: the Simulated Caller has no caller-specific context. This is the default. * Any profile from your list: the Simulated Caller is given its fields before the call starts. Then click **Done**. The profile applies to every call in the run, and you can combine it with any Simulation Mix, language or environment. For example, run 10 calls with the *Angry User* profile focused on escalation-handling Pressure tests. *** ## Edit a profile Click the pencil icon on a profile card to open **Edit test profile**. You can rename the profile, add fields, change keys or values, and remove fields. Click **Save**. Changes apply to future runs only. Runs that already used the profile keep the snapshot taken when they started. *** ## Delete a profile Click the trash icon on a profile card, then confirm in **Delete test profile**. Deleting a profile can't be undone, but past runs that used it keep their snapshotted profile data. *** ## Limits | Limit | Value | | - | - | | **Profile name** | 1 to 255 characters | | Fields per profile | Up to 50 (at least 1 in the app) | | Field key | Starts with a letter or underscore; letters, numbers and underscores only | | Field value | Up to 1,000 characters | Test profiles are also available through the public API, in the **Simulation** group of the API Reference. ## Next steps > [card] [Introduction to Call Simulation](/docs/simulation/overview) > > How the Simulation Mix, Routine callers and Pressure tests work together. > [card] [Set up outbound simulation](/docs/simulation/outbound) > > Pass test profile fields to your trigger endpoint.