Govern your voice agent
Point a LiveKit, Pipecat or OpenAI Agents SDK voice agent at Forgebench and every model call it makes is governed. That covers Transcription of the caller, the LLM turn and Speech Synthesis of the reply. Each call is budget-checked, guardrailed, metered in its own unit and audited. Configure each client with the gateway URL and key, a supported model, and a shared conversation ID.
Voice is available on Pro and Enterprise. On other plans the routes
return 402 with code plan_required. Policy, Voice Assets and Consent Records
are covered in Voice governance.
What is governed
| Step | Route | Measured in |
|---|---|---|
| LLM turn | POST /v1/chat/completions | tokens |
| Transcription (batch) | POST /v1/audio/transcriptions | audio seconds |
| Transcription (streaming) | WS /v1/realtime?intent=transcription, WS /v1/listen | audio seconds |
| Speech Synthesis | POST /v1/audio/speech | characters |
| Speech-to-speech conversation | WS /v1/realtime?intent=conversation | tokens, per reply |
Each call is one Governed Call with one audit entry and one metering event. A Voice Conversation is the Governed Calls that share a session value, so a phone call shows as one conversation in the trace views.
Usage Units and pricing
Voice is priced in the unit the provider bills (its Usage Unit), not converted to tokens.
| Governed Call | Usage Unit | Catalog price shown as |
|---|---|---|
| Chat completion | tokens | per 1K tokens |
| Transcription | audio seconds | per minute |
| Speech Synthesis | characters | per 1K characters |
| Image generation | images | per image |
GET /v1/models reports this per model: unit is one of tokens,
images, audio_seconds, characters or pages, and unit_price_usd is the price of
one second, one character, one image or one page (null for token models, which keep their
per-1K prices).
Prices are the provider's cost, with no Forgebench markup. Budgets are in dollars, so a Transcription draws down the same budget as a chat call. The minimum charge for chat calls doesn't apply to audio: a two-second Transcription is charged what it cost. See the per-unit note in the Gateway catalog.
The OpenAI-compatible routes
The routes follow the OpenAI audio API, so any OpenAI client works once you point its base URL at Forgebench.
POST /v1/audio/transcriptions: multipart withfile,model, and optionallylanguage,prompt,response_format(json,text,verbose_json) andmetadata(a JSON string).POST /v1/audio/speech: JSON withmodel,input,voice, and optionallyresponse_format(mp3,opus,wav,pcm,flac),speedandmetadata. The response body is audio; the trace id is in theX-Forgebench-Trace-Idresponse header.- Voice Conversation key:
metadata.sessionif present, otherwise theX-Forgebench-Sessionrequest header. - The default upload limit is 25 MiB. Audio measured over 600 seconds is
rejected with
413before provider dispatch. For formats without a readable duration, the gateway uses a conservative size bound for reservation, capped at the duration limit. Implausible container headers return422 invalid_audio. - Checks run in this order: authentication and role (
401,403), plan (402plan_required), then budget (402with a budget code). - A voice policy refusal is
422disclosure_missing, or403voice_not_allowed/marking_required. See Voice governance. - Speech Synthesis audio is buffered: you receive it when synthesis finishes, not as it is produced.
- Speech input is limited to 40,000 characters.
speedmust be greater than zero and at most 4. Unsupported top-level speech options such asinstructionsandstream_formatare ignored.
from forgebench import (
Forgebench, BudgetExceededError, PermissionDeniedError, ValidationError,
)
client = Forgebench(api_key="sk_...", base_url="https://api.forgebench.ai")
try:
heard = client.audio.transcriptions.create(
open("caller.wav", "rb"),
"gpt-4o-transcribe",
language="en",
session="call-8841",
)
spoken = client.audio.speech.create(
"gpt-4o-mini-tts",
"Hi, I'm an AI assistant. How can I help?",
"alloy",
response_format="mp3",
session="call-8841",
)
print(heard.text, len(spoken.audio), spoken.trace_id)
except BudgetExceededError as e:
print("budget:", e.code)
except PermissionDeniedError as e:
print("blocked:", e.code) # model_not_allowed, voice_not_allowed, marking_required
except ValidationError as e:
print("refused:", e.code) # disclosure_missingimport { readFile } from "node:fs/promises";
import {
Forgebench,
BudgetExceededError,
PermissionDeniedError,
UnprocessableEntityError,
} from "@seedlinglabs/forgebench-sdk";
const forgebench = new Forgebench({ baseUrl: "https://api.forgebench.ai", apiKey: "sk_..." });
try {
const heard = await forgebench.audio.transcriptions.create({
file: { data: await readFile("caller.wav"), filename: "caller.wav", contentType: "audio/wav" },
model: "gpt-4o-transcribe",
language: "en",
session: "call-8841",
});
const spoken = await forgebench.audio.speech.create({
model: "gpt-4o-mini-tts",
input: "Hi, I'm an AI assistant. How can I help?",
voice: "alloy",
response_format: "mp3",
session: "call-8841",
});
console.log(heard.text, spoken.audio.byteLength, spoken.traceId);
} catch (e) {
if (e instanceof BudgetExceededError) console.log("budget:", e.code);
else if (e instanceof PermissionDeniedError) console.log("blocked:", e.code);
else if (e instanceof UnprocessableEntityError) console.log("refused:", e.code);
else throw e;
}import ai.forgebench.Forgebench;
import ai.forgebench.SpeechParams;
import ai.forgebench.TranscriptionParams;
import ai.forgebench.errors.BudgetExceededException;
import ai.forgebench.errors.PermissionDeniedException;
import ai.forgebench.errors.ValidationException;
import ai.forgebench.types.SpeechAudio;
import ai.forgebench.types.Transcription;
import java.nio.file.Path;
Forgebench client = Forgebench.builder()
.apiKey("sk_...")
.baseUrl("https://api.forgebench.ai")
.build();
try {
Transcription heard = client.audio().transcriptions().create(TranscriptionParams.builder()
.file(Path.of("caller.wav"))
.model("gpt-4o-transcribe")
.language("en")
.session("call-8841")
.build());
SpeechAudio spoken = client.audio().speech().create(SpeechParams.builder()
.model("gpt-4o-mini-tts")
.input("Hi, I'm an AI assistant. How can I help?")
.voice("alloy")
.responseFormat("mp3")
.session("call-8841")
.build());
System.out.println(heard.getText() + " " + spoken.getAudio().length + " " + spoken.getTraceId());
} catch (BudgetExceededException e) {
System.out.println("budget: " + e.getCode());
} catch (PermissionDeniedException e) {
System.out.println("blocked: " + e.getCode()); // model_not_allowed, voice_not_allowed, marking_required
} catch (ValidationException e) {
System.out.println("refused: " + e.getCode()); // disclosure_missing
}# Batch Transcription
curl -X POST https://api.forgebench.ai/v1/audio/transcriptions \
-H "Authorization: Bearer $FORGEBENCH_API_KEY" \
-H "X-Forgebench-Session: call-8841" \
-F [email protected] \
-F model=gpt-4o-transcribe \
-F language=en
# Speech Synthesis: the audio goes to reply.mp3; -D - prints the response
# headers, including X-Forgebench-Trace-Id
curl -X POST https://api.forgebench.ai/v1/audio/speech \
-H "Authorization: Bearer $FORGEBENCH_API_KEY" \
-H "X-Forgebench-Session: call-8841" \
-H "Content-Type: application/json" \
-D - -o reply.mp3 \
-d @- <<'EOF'
{
"model": "gpt-4o-mini-tts",
"input": "Hi, I'm an AI assistant. How can I help?",
"voice": "alloy",
"response_format": "mp3"
}
EOFAgents built in Forgebench stream their answer as server-sent events from
POST /v1/agents/{id}/run with "stream": true. The console's live talk mode
uses this. Send the Voice Conversation key as metadata.session in the body or
in the X-Forgebench-Session header.
The agent run stream
The response is text/event-stream with three kinds of frame, in order:
- Content deltas, one per model chunk, in the same shape as a chat stream
(
data: {"object": "chat.completion.chunk", "choices": [{"delta": {"content": "..."}}]}). - One final frame with the whole answer:
data: {"type": "agent.run.completed", "answer": "...", "trace_id": "...", "cost_usd": 0.0021, "citations": [...]}.cost_usdis the metered cost of the run andcitationsare the knowledge chunks that grounded it (an empty list for an ungrounded agent). data: [DONE].
If the run fails after the first byte, the stream carries an error frame
instead of the completed frame and ends without [DONE]:
event: error
data: {"error": {"code": "upstream_error", "message": "..."}}Refusals that happen before the model is called come back before the first byte, as a normal JSON error with the same body as the non-streaming call:
402: workspace, agent or key budget (for exampleagent_budget_exceeded)403: a model the key may not call404: the agent doesn't exist400: a guardrail or agent tool binding can't be enforced over a stream
Budget is reserved and the audit entry written before the first byte. Metering
settles once, after the stream ends. A run that fails before any output
releases its reservation. Without stream, the endpoint returns the cited JSON
answer.
try:
for event in client.agents.run(agent_id, message="Where is my order?", stream=True, session="call-8841"):
print(event)
except BudgetExceededError:
print("over budget, nothing was spent")try {
for await (const event of forgebench.agents.run(agentId, {
message: "Where is my order?",
stream: true,
session: "call-8841",
})) {
console.log(event);
}
} catch (e) {
if (e instanceof BudgetExceededError) console.log("over budget, nothing was spent");
else throw e;
}import ai.forgebench.AgentRunStream;
import ai.forgebench.MessageRunParams;
import ai.forgebench.errors.BudgetExceededException;
import com.fasterxml.jackson.databind.JsonNode;
MessageRunParams params = MessageRunParams.builder("Where is my order?")
.session("call-8841")
.build();
try (AgentRunStream events = client.agents().runStream(agentId, params)) {
for (JsonNode event : events) {
System.out.println(event);
}
} catch (BudgetExceededException e) {
System.out.println("over budget, nothing was spent");
}# -N prints each event as it arrives; a 402 comes back as JSON before the stream opens
curl -N -X POST https://api.forgebench.ai/v1/agents/$AGENT_ID/run \
-H "Authorization: Bearer $FORGEBENCH_API_KEY" \
-H "X-Forgebench-Session: call-8841" \
-H "Content-Type: application/json" \
-d '{"message": "Where is my order?", "stream": true}'Point your framework at Forgebench
Create an sk_... key in API keys, then set the base URL on each
model client to https://api.forgebench.ai/v1. The framework holds only the
Forgebench key, never your provider credentials.
LiveKit Agents
import os
from livekit.agents import AgentSession
from livekit.plugins import openai
from openai import AsyncOpenAI
FORGEBENCH = "https://api.forgebench.ai/v1"
SESSION = "call-8841"
client = AsyncOpenAI(
base_url=FORGEBENCH,
api_key=os.environ["FORGEBENCH_API_KEY"],
default_headers={"X-Forgebench-Session": SESSION},
)
session = AgentSession(
llm=openai.LLM(model="gpt-4o-mini", client=client, extra_body={"session_id": SESSION}),
tts=openai.TTS(model="gpt-4o-mini-tts", voice="alloy", client=client),
stt=openai.STT(model="gpt-4o-transcribe", client=client, use_realtime=False),
# Keep your normal VAD and transport configuration.
)- Python's OpenAI LLM, STT, and TTS plugins accept a custom
AsyncOpenAIclient. STT also acceptsbase_url,api_key, anduse_realtimedirectly. - This example selects batch STT. For realtime STT, use a gateway model and
confirm the client sends
/v1/realtime?intent=transcription. Speech-to-speech sessions are not supported. - The shared client sends the audio session header. The LLM's
extra_bodysends top-levelsession_id, which chat requires to join the voice turn. Close the client when the pipeline shuts down. See the LiveKit OpenAI plugin source.
Pipecat
from openai import DefaultAsyncHttpxClient
from pipecat.services.openai.llm import OpenAILLMService
from pipecat.services.openai.stt import OpenAISTTService
from pipecat.services.openai.tts import OpenAITTSService
FORGEBENCH = "https://api.forgebench.ai/v1"
SESSION = {"X-Forgebench-Session": "call-8841"}
llm = OpenAILLMService(
api_key="sk_...",
base_url=FORGEBENCH,
default_headers=SESSION,
settings=OpenAILLMService.Settings(
model="gpt-4o-mini",
extra={"extra_body": {"session_id": "call-8841"}},
),
)
stt = OpenAISTTService(
api_key="sk_...", base_url=FORGEBENCH,
http_client=DefaultAsyncHttpxClient(headers=SESSION),
settings=OpenAISTTService.Settings(model="gpt-4o-transcribe"),
)
tts = OpenAITTSService(
api_key="sk_...", base_url=FORGEBENCH,
http_client=DefaultAsyncHttpxClient(headers=SESSION),
settings=OpenAITTSService.Settings(model="gpt-4o-mini-tts", voice="alloy"),
)base_url is documented on OpenAILLMService, OpenAISTTService,
OpenAITTSService, OpenAIRealtimeSTTService and DeepgramSTTService.
default_headers is documented on OpenAILLMService. The STT and TTS services
accept an http_client argument and pass it to their OpenAI client; the example
sets the session header there. See the STT base client
and TTS client.
Create services per conversation when their session header differs.
The LLM's Settings.extra supplies OpenAI request arguments; its nested
extra_body sends session_id for voice-turn joining. See the
Pipecat request builder.
Close injected HTTP clients when the pipeline shuts down.
For streaming Transcription:
from pipecat.services.deepgram.stt import DeepgramSTTService
from pipecat.services.openai.stt import OpenAIRealtimeSTTService
# OpenAI realtime-transcription protocol
stt = OpenAIRealtimeSTTService(
api_key="sk_...",
base_url="wss://api.forgebench.ai/v1/realtime",
settings=OpenAIRealtimeSTTService.Settings(model="gpt-4o-transcribe"),
)
# or Deepgram protocol
stt = DeepgramSTTService(api_key="sk_...", base_url="wss://api.forgebench.ai")Pipecat's OpenAI realtime client appends ?intent=transcription to base_url;
do not add that query yourself. It sends the model in session.update.
Its stock connector adds only the authorization header, so adding a session
requires a connection adapter; adding a query to base_url would produce a
malformed URL. Deepgram uses its query model or the configured default; verify
that its outgoing path is /v1/listen. Both clients must select catalogued
models. See
Pipecat's OpenAI STT reference.
OpenAI Agents SDK
from agents.voice import OpenAIVoiceModelProvider
provider = OpenAIVoiceModelProvider(
base_url="https://api.forgebench.ai/v1",
api_key="sk_...",
)OpenAIVoiceModelProvider(base_url=, api_key=) is documented. To attach it to a
VoicePipeline, see the Agents SDK voice pipeline docs. The provider uses this
client for batch Transcription, Speech Synthesis and the streaming
Transcription WebSocket.
To route the agent's LLM turns through Forgebench too, set OPENAI_BASE_URL and
OPENAI_API_KEY to the same values, or use a custom chat model client as the
Agents SDK docs describe.
The provider takes either base_url and api_key, or an openai_client, not
both. To set audio session headers, pass an AsyncOpenAI client constructed
with default_headers. Use OpenAIChatCompletionsModel for agent credentials;
native Responses rejects agent keys. Send top-level session_id on LLM calls
to join the voice turn. See the Agents SDK model configuration.
Setting the session
| Framework | Default session header |
|---|---|
| Pipecat LLM | Yes, default_headers (documented) |
| Pipecat STT and TTS | Via http_client default headers |
| Pipecat OpenAI streaming Transcription | Requires a connection adapter to add a session |
| LiveKit Agents | Via a custom OpenAI client; chat also needs session_id |
| OpenAI Agents SDK | Via openai_client with default headers; chat also needs session_id |
| Forgebench SDKs | Audio and agent-run session helpers; chat needs session_id in its body |
For audio and agent-run requests, metadata.session takes precedence over the
session header. Chat completions joins a live voice turn using top-level
session_id, so send the same opaque value there.
Streaming Transcription
Streaming Transcription is a WebSocket that speaks the provider's own protocol, so existing clients connect unchanged.
| Protocol | URL |
|---|---|
| OpenAI realtime-transcription | wss://api.forgebench.ai/v1/realtime?intent=transcription |
| Deepgram | wss://api.forgebench.ai/v1/listen |
Any other intent on /v1/realtime is closed with code 1008. For
speech-to-speech, see Speech-to-speech conversations.
Model. Taken from ?model= if present, otherwise from the first
session.update event, otherwise the agent's or key's default.
Authentication. Any one of:
Authorization: Bearer sk_...(OpenAI clients) orAuthorization: Token sk_...(Deepgram clients)- an
api-keyheader - a WebSocket subprotocol:
openai-insecure-api-key.sk_...for OpenAI-protocol clients, ortoken, sk_...for Deepgram - the console session cookie, for the console itself
Budget. A connection is one Governed Call. Forgebench reserves budget in blocks of 60 audio seconds and renews as audio flows. When the budget can't cover another block, the current utterance may finish (up to 15 more seconds), then the connection closes with a budget error event. At close you're charged for the audio relayed, using the provider's reported duration when available, as one metering event in audio seconds.
Without a voice profile, streaming connects directly to OpenAI or Deepgram without route failover. With profile routing enabled, it selects a compatible model and credential at connect time. On a provider-side connection loss, it can reconnect to a compatible route, with at most two reconnects and ten seconds of reconnect-dial time by default. The utterance in flight can be lost or repeated; client disconnects, request errors, and budget exhaustion are not retried. Gemini and Vertex streaming transcription are not supported.
Speech-to-speech conversations
A speech-to-speech model hears the caller and answers in audio over one WebSocket, with no separate transcription and synthesis steps. Connect an OpenAI Realtime client to Forgebench and it works unchanged.
wss://api.forgebench.ai/v1/realtime?intent=conversation&model=gpt-realtimeIf you leave out intent and the model is a speech-to-speech model, Forgebench
treats the connection as a conversation. This is what the OpenAI SDKs send.
| Model | Provider |
|---|---|
openai-gpt-realtime, openai-gpt-realtime-mini | OpenAI |
openai-gpt-realtime-2.1, openai-gpt-realtime-2.1-mini | OpenAI |
gemini-2.5-flash-native-audio, gemini-3.1-flash-live | Google Gemini Live |
You can pass either the Forgebench name above or the provider's own name, for
example ?model=gpt-realtime. Gemini Live models use the same OpenAI Realtime
protocol, so one client works for both providers. Any other model is refused
with unsupported_model, and the error lists the models you can use.
Setup. Add a provider key for OpenAI or Google to your workspace first, as for any other model. Authentication, session values and plan requirements are the same as for Streaming Transcription above.
Billing. Each reply from the model is its own Governed Call. Forgebench checks your allowlist, rate limit and budget when the reply starts, and settles the cost from the token usage the provider reports when the reply ends. Text and audio tokens are priced at their own rates, and cached input is priced at the cached rate. All the calls on one connection share one trace.
- If a budget runs out, the current reply is cancelled, you receive an
errorevent, and the connection closes with code 1008. - If a reply is cut off before the provider reports usage, you're charged for what was actually heard and spoken. Silence isn't charged.
- When OpenAI transcribes what the caller said, that cost is added to the next reply.
Limits. Each connection counts toward your key's streaming connection limit. A connection closes after two minutes with no audio or events in either direction by default.
Sarvam speech models
Sarvam's speech models work on the same routes as OpenAI's, so an OpenAI client
needs only a different model. Prices are in rupees, excluding GST, and are
shown in dollars at the daily exchange rate. Add your Sarvam key first. See
Model providers.
Speech to text (POST /v1/audio/transcriptions) with sarvam-saaras-v3 or
sarvam-saaras-v4:
- Billed per second of audio, rounded up to a whole second. A 3.5-second clip is billed as 4 seconds.
- Each request takes up to 30 seconds of audio. A longer clip is refused before anything is charged.
- Send
languageas a Sarvam locale such ashi-IN, orhi. If you leave it out, Sarvam detects the language.
Text to speech (POST /v1/audio/speech) with sarvam-bulbul-v3 or
sarvam-bulbul-v4-flash:
- Billed per input character, with at most 2,500 characters per request.
response_formatismp3,wav,flacorpcm.opusisn't available.speedis between 0.5 and 2.voiceis a Sarvam speaker. Bulbul v3 uses names such asshubh. Bulbul v4 Flash uses names such asshubh_enhi_ads.- Sarvam detects the language from the text.
A request Sarvam would refuse is returned as 422 before anything is reserved
or charged.
Voice model profiles
Admins can create a profile through POST /v1/routing/profiles with
kind: "transcription" or kind: "speech" and provider/model candidates.
least-used is the default voice strategy. Read
GET /v1/routing/strategies?kind=speech for available choices.
Inspect GET /v1/voice/profile-routing, then enable the workspace with
PUT /v1/voice/profile-routing/enabled and {"enabled": true}. The deployment
must also enable voice profile routing, or this returns 409. Set a default
with PUT /v1/voice/profile-defaults/{kind} and {"profile": "name"}, or bind
an agent with PUT /v1/agents/{id}/voice/profiles.
The agent binding wins over the workspace default, and the profile determines
the served model. Every candidate needs a usable workspace provider key and
must fit the caller's allowlist. Incompatible fields or unmapped voices skip
the candidate. Speech Voice Asset and marking checks run again for each
attempt. A broken agent binding fails with 409 agent_voice_profile_unavailable.
Calls sharing a conversation ID normally try the previously served route first, independently for transcription, LLM, and speech. This session pin is advisory and expires after 30 idle minutes by default. See Voice governance for voice mappings.

