> ## Documentation Index
> Fetch the complete documentation index at: https://docs.fish.audio/llms.txt
> Use this file to discover all available pages before exploring further.

# Tracing & Performance Analysis

> Correlate Fish Audio inference spans with your own distributed traces

Fish Audio inference APIs accept the standard W3C Trace Context `traceparent`
header. Send this header when your application already has an active trace and
you want Fish Audio edge, inference, alignment, and upstream ASR spans to appear
under the same trace ID.

Supported inference surfaces:

* `POST /v1/tts`
* `POST /v1/tts/stream/with-timestamp`
* `POST /v1/asr`
* `wss://api.fish.audio/v1/tts/live`
* `wss://api.fish.audio/v1/asr/realtime`

If `traceparent` is omitted or invalid, Fish Audio starts a new trace for the
request. Tracing does not change authentication, rate limits, billing, request
priority, or generated output.

## Header Format

Use the W3C `traceparent` format:

```text theme={null}
traceparent: 00-<trace-id>-<parent-id>-<trace-flags>
```

Example:

```text theme={null}
traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01
```

In this example, `4bf92f3577b34da6a3ce929d0e0e4736` is the trace ID. Fish Audio
continues that trace ID when it calls the inference backend and related services.

> [!TIP]
>
> Prefer letting your tracing SDK inject `traceparent` instead of hand-building
> it. For each Fish Audio request, create a child span in your business service
> and inject that span context into the outgoing HTTP or WebSocket headers.

## Bind Business and Inference Traces

To bind your business-side trace to Fish Audio's inference-side trace:

1. Start or continue a trace in your application for the user workflow.
2. Create a child span around the Fish Audio request.
3. Inject that span context into the request headers.
4. Send the request with `traceparent`.
5. Use the same trace ID in your observability tool to inspect both your
   business spans and Fish Audio inference spans.

For multiple Fish Audio calls in one workflow, keep the same trace ID by using
the same parent trace, but let your tracing SDK create a fresh parent/span ID for
each outgoing request.

## REST Example

```bash theme={null}
TRACEPARENT="00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"

curl --request POST https://api.fish.audio/v1/tts \
  --header "Authorization: Bearer $FISH_API_KEY" \
  --header "Content-Type: application/json" \
  --header "model: s2-pro" \
  --header "traceparent: $TRACEPARENT" \
  --data '{
    "text": "Hello from a traced Fish Audio request.",
    "reference_id": "model-id",
    "format": "mp3"
  }' \
  --output out.mp3
```

## OpenTelemetry Examples

> [tab] Python
>
> ```python theme={null}
> import os
> import requests
> from opentelemetry import trace
> from opentelemetry.propagate import inject
>
> tracer = trace.get_tracer("my-service")
>
> with tracer.start_as_current_span("fish_audio.tts"):
>     headers = {
>         "Authorization": f"Bearer {os.environ['FISH_API_KEY']}",
>         "Content-Type": "application/json",
>         "model": "s2-pro",
>     }
>     inject(headers)
>
>     response = requests.post(
>         "https://api.fish.audio/v1/tts",
>         headers=headers,
>         json={
>             "text": "Hello from a traced request.",
>             "reference_id": "model-id",
>             "format": "mp3",
>         },
>         timeout=60,
>     )
>     response.raise_for_status()
> ```

> [tab] Node.js
>
> ```javascript theme={null}
> import { context, propagation, trace } from "@opentelemetry/api";
>
> const tracer = trace.getTracer("my-service");
> const span = tracer.startSpan("fish_audio.tts");
> const ctx = trace.setSpan(context.active(), span);
>
> try {
>   await context.with(ctx, async () => {
>     const headers = {
>       Authorization: `Bearer ${process.env.FISH_API_KEY}`,
>       "Content-Type": "application/json",
>       model: "s2-pro",
>     };
>     propagation.inject(ctx, headers);
>
>     const response = await fetch("https://api.fish.audio/v1/tts", {
>       method: "POST",
>       headers,
>       body: JSON.stringify({
>         text: "Hello from a traced request.",
>         reference_id: "model-id",
>         format: "mp3",
>       }),
>     });
>
>     if (!response.ok) {
>       throw new Error(`${response.status} ${await response.text()}`);
>     }
>   });
> } finally {
>   span.end();
> }
> ```

## SDK Examples

The official SDKs send `traceparent` in two ways: OpenTelemetry instruments the
HTTP library the SDK uses, or you pass the header yourself. These examples
assume that your application already configures an OpenTelemetry tracer
provider and exporter.

> [tab] Python
>
> **OpenTelemetry auto-instrumentation.** The SDK sends every request through
> `httpx`, including the WebSocket upgrades of `tts.stream_websocket` and
> `asr.stream_websocket`.
> Install `opentelemetry-instrumentation-httpx` and instrument `httpx` once
> at startup. Each Fish Audio request then gets its own child span and
> `traceparent`.
>
> ```python theme={null}
> from fishaudio import FishAudio
> from opentelemetry import trace
> from opentelemetry.instrumentation.httpx import HTTPXClientInstrumentor
>
> HTTPXClientInstrumentor().instrument()
>
> tracer = trace.get_tracer("my-service")
> client = FishAudio()
>
> with tracer.start_as_current_span("fish_audio.tts"):
>     audio = client.tts.convert(text="Hello from a traced request.")
> ```
>
> **By hand.** Inject the current span context into `additional_headers`:
>
> ```python theme={null}
> from fishaudio import FishAudio
> from fishaudio.core import RequestOptions
> from opentelemetry import trace
> from opentelemetry.propagate import inject
>
> tracer = trace.get_tracer("my-service")
> client = FishAudio()
>
> with tracer.start_as_current_span("fish_audio.tts"):
>     headers = {}
>     inject(headers)
>     audio = client.tts.convert(
>         text="Hello from a traced request.",
>         request_options=RequestOptions(additional_headers=headers),
>     )
> ```
>
> `tts.stream_websocket` and `asr.stream_websocket` do not take
> `request_options`. To add the header there without auto-instrumentation, pass your own `httpx` client with a
> request hook. A client you pass in does not get the SDK's `base_url` or
> `timeout`, so set both on it.
>
> ```python theme={null}
> import httpx
> from fishaudio import FishAudio
> from opentelemetry import trace
> from opentelemetry.propagate import inject
>
> tracer = trace.get_tracer("my-service")
> http_client = httpx.Client(
>     base_url="https://api.fish.audio",
>     timeout=240.0,
>     event_hooks={"request": [lambda request: inject(request.headers)]},
> )
> client = FishAudio(httpx_client=http_client)
>
> with tracer.start_as_current_span("fish_audio.tts_stream"):
>     audio = b"".join(
>         client.tts.stream_websocket(iter(["Hello from ", "a traced stream."]))
>     )
> ```

> [tab] TypeScript
>
> **OpenTelemetry auto-instrumentation.** The SDK makes HTTP requests with
> the global `fetch`, which `@opentelemetry/instrumentation-undici` covers.
> `textToSpeech.convertRealtime` opens its WebSocket through `node:http`,
> which `@opentelemetry/instrumentation-http` covers.
> `@opentelemetry/auto-instrumentations-node` includes both. Start
> OpenTelemetry before your application loads, for example with
> `node --import ./instrumentation.js app.js`:
>
> ```typescript instrumentation.ts theme={null}
> import { NodeSDK } from "@opentelemetry/sdk-node";
> import { getNodeAutoInstrumentations } from "@opentelemetry/auto-instrumentations-node";
>
> const sdk = new NodeSDK({
>   // Configure traceExporter or the OTEL_* environment variables here.
>   instrumentations: [getNodeAutoInstrumentations()],
> });
> sdk.start();
> ```
>
> ```typescript app.ts theme={null}
> import { trace } from "@opentelemetry/api";
> import { FishAudioClient } from "fish-audio";
>
> const tracer = trace.getTracer("my-service");
> const client = new FishAudioClient({ apiKey: process.env.FISH_API_KEY });
>
> await tracer.startActiveSpan("fish_audio.tts", async span => {
>   try {
>     const stream = await client.textToSpeech.convert({
>       text: "Hello from a traced request.",
>     });
>     for await (const chunk of stream) {
>       // write or play the audio chunk
>     }
>   } finally {
>     span.end();
>   }
> });
> ```
>
> **By hand.** A client header can be a function. The SDK calls it for every
> HTTP request and when `speechToText.convertRealtime` connects, so each
> request carries the span that is active at that moment:
>
> ```typescript theme={null}
> import { context, propagation, trace } from "@opentelemetry/api";
> import { FishAudioClient } from "fish-audio";
>
> const tracer = trace.getTracer("my-service");
> const client = new FishAudioClient({
>   apiKey: process.env.FISH_API_KEY,
>   headers: {
>     traceparent: () => {
>       const carrier: Record<string, string> = {};
>       propagation.inject(context.active(), carrier);
>       return carrier.traceparent;
>     },
>   },
> });
>
> await tracer.startActiveSpan("fish_audio.tts", async span => {
>   try {
>     const stream = await client.textToSpeech.convert({
>       text: "Hello from a traced request.",
>     });
>     for await (const chunk of stream) {
>       // write or play the audio chunk
>     }
>   } finally {
>     span.end();
>   }
> });
> ```
>
> You can also pass `{ headers: { traceparent } }` as the request options
> argument of a single call.

> [tab] Go
>
> **OpenTelemetry instrumentation.** Requests use the `context.Context` you
> pass in. To trace them, give the client an `http.Client` whose transport is
> wrapped with `otelhttp`, and register the W3C propagator. Go's global
> propagator does nothing until you set one.
>
> ```go theme={null}
> package main
>
> import (
> 	"context"
> 	"log"
> 	"net/http"
>
> 	fishaudio "github.com/fishaudio/fish-audio-go"
> 	"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
> 	"go.opentelemetry.io/otel"
> 	"go.opentelemetry.io/otel/propagation"
> )
>
> func main() {
> 	otel.SetTextMapPropagator(propagation.TraceContext{})
>
> 	client := fishaudio.NewClient(
> 		fishaudio.WithHTTPClient(&http.Client{
> 			Transport: otelhttp.NewTransport(http.DefaultTransport),
> 		}),
> 	)
>
> 	ctx, span := otel.Tracer("my-service").Start(context.Background(), "fish_audio.tts")
> 	defer span.End()
>
> 	audio, err := client.TTS.Convert(ctx, &fishaudio.ConvertParams{
> 		Text: "Hello from a traced request.",
> 	})
> 	if err != nil {
> 		log.Fatal(err)
> 	}
> 	log.Printf("received %d bytes", len(audio))
> }
> ```
>
> **By hand.** The Go SDK methods do not take per-request headers. Without
> `otelhttp`, add the header in your own `http.RoundTripper`. Register the
> W3C propagator first, as in the example above:
>
> ```go theme={null}
> type traceparentTransport struct{ base http.RoundTripper }
>
> func (t traceparentTransport) RoundTrip(req *http.Request) (*http.Response, error) {
> 	req = req.Clone(req.Context())
> 	otel.GetTextMapPropagator().Inject(req.Context(), propagation.HeaderCarrier(req.Header))
> 	return t.base.RoundTrip(req)
> }
>
> client := fishaudio.NewClient(
> 	fishaudio.WithHTTPClient(&http.Client{
> 		Transport: traceparentTransport{base: http.DefaultTransport},
> 	}),
> )
> ```

> [!WARNING]
>
> Some SDK calls cannot carry `traceparent` yet:
>
> * **TypeScript** `textToSpeech.convertRealtime` (`/v1/tts/live`) does not send
>   headers you set on the client. It carries `traceparent` only when
>   `@opentelemetry/instrumentation-http` is active.
> * **Go** `TTS.StreamWebSocket` (`/v1/tts/live`) cannot send `traceparent`.
> * **Go** `TTS.Convert`, `TTS.Stream` and `ASR.Transcribe` do not take
>   per-request headers. Use a custom transport as shown above.
>
> For these calls, use the raw [WebSocket example](#websocket-tracing) or the
> [REST example](#rest-example).

## WebSocket Tracing

Pass `traceparent` on the WebSocket upgrade request:

```javascript theme={null}
import WebSocket from "ws";

const ws = new WebSocket("wss://api.fish.audio/v1/tts/live", {
  headers: {
    Authorization: `Bearer ${process.env.FISH_API_KEY}`,
    model: "s2-pro",
    traceparent: "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01",
  },
});
```

> [!NOTE]
>
> Browser WebSocket APIs do not allow custom headers. For browser clients,
> inject `traceparent` from a trusted server-side proxy or use REST endpoints
> where your frontend can send the header through `fetch`.

## Trace ID in Responses

Inference responses include an `x-fish-trace-id` header with the trace ID Fish
Audio used for the request. This applies to the inference endpoints listed
above, including the WebSocket upgrade response. When you send a valid
`traceparent`, the value is your trace ID. When you omit `traceparent` or send
an invalid one, it is the new trace ID Fish Audio started. Include it when you
contact support about a request.

```bash theme={null}
curl --request POST https://api.fish.audio/v1/tts \
  --header "Authorization: Bearer $FISH_API_KEY" \
  --header "Content-Type: application/json" \
  --header "traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01" \
  --data '{ "text": "Hello from a traced request.", "format": "mp3" }' \
  --dump-header - \
  --output out.mp3
```

```text theme={null}
x-fish-trace-id: 4bf92f3577b34da6a3ce929d0e0e4736
```

## Speech-to-Text Request IDs

`transcribe-1-pro` responses from `POST /v1/asr` include a `request_id` field
in the JSON body, on success and on its own error responses, and the same value
in the `x-request-id` response header. Platform errors, such as authentication,
credit, and concurrency errors, and errors from the network edge do not carry
it. Include it when you contact support about a transcription request. See
[Speech to Text](https://docs.fish.audio/api-reference/endpoint/openapi-v1/speech-to-text.md#read-the-response).

## Enterprise Performance Analysis

> [!NOTE]
>
> Fish Audio supports trace-based performance analysis for enterprise customers
> with a signed enterprise agreement. When this support is enabled, share the
> W3C trace ID with Fish Audio support so we can correlate your business span
> with Fish Audio edge routing, backend inference, reference-audio encoding,
> TTFT, response-time, alignment, and upstream ASR spans.

Only share the trace ID or `traceparent` value needed for investigation. Do not
place API keys, user identifiers, transcripts, audio URLs, or other sensitive
data in trace IDs or span names.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.