CassetteHttpClient

org.llm4s.testkit.CassetteHttpClient
See theCassetteHttpClient companion object
@Experimental
final class CassetteHttpClient extends Llm4sHttpClient

An org.llm4s.http.Llm4sHttpClient that records a provider's HTTP exchanges to a cassette file and replays them (#459), for testing code that calls a real provider client without a network or an API key.

Pass it to the client as LlmClientOptions.default.withHttpClient(cassette). It reaches every provider that sends through Llm4sHttpClient (openai-compatible and its dialects, Gemini, Vertex AI, Ollama, Perplexity, watsonx); the openai, anthropic and bedrock chat clients send through their vendors' SDKs and ignore it.

'''The cassette''' is one JSON file: "llm4sCassette": 1 and the interactions in the order they happened, each a request (method, url, headers, body) and a response (status, headers, body, and masked: whether recording masked a value of the body; optional, and read as unknown when absent). A body is {"json": ...} (a JSON request body, keys sorted), {"text": "..."} or {"base64": "..."}, and absent when empty. A response body is kept as received, as text or base64, so a streamed (SSE) reply replays byte for byte.

'''What is masked before anything is written''' (to [REDACTED]):

  • every value llm4s holds as a Secret, wherever it appears in the URL, the headers or a body (a body that is not UTF-8 included, read byte for byte);
  • the value of every request header except a few that carry no credential (Accept, Accept-Encoding, Content-Type, User-Agent, anthropic-version, anthropic-beta, openai-beta, x-goog-api-client): a custom header may carry a gateway's token under any name;
  • the value of a response header whose name is a credential (Set-Cookie, ...), and the userinfo (user:password@) of the URL;
  • the value of a query parameter whose name is a credential (api_key, access_token, ...) or is key;
  • in a JSON request or response body, the value under every credential-named key at any depth (access_token, id_token, api_key, client_secret, password, ...), tool-call arguments and tool schemas included, and that value wherever else the same body repeats it, the model's text included. This catches a token a token exchange returns before llm4s holds it as a Secret. A string that itself holds JSON (a tool call's arguments sent as a string, a JSON-mode answer, a prompt that is a JSON object) is masked the same way, seven levels down at most (a JSON string deeper than that is masked whole); a repeat of a value masked inside such a string is masked only within that string. The rest of a JSON body, prompts and answers included, is written as it was;
  • in a request body that is text but not JSON (a form-encoded token request), what llm4s's log redaction masks: credential-named fields and values that look like vendor keys. A response that is not JSON (an SSE stream, plain text) only has registered secrets removed: a streamed reply's tool-call arguments are not masked by key;
  • in a Location or Content-Location response header, the URL's credential query parameters and userinfo.

A query parameter's name is checked percent-decoded (access%5Ftoken), and written as it was sent.

A secret in free text that matches none of these (a key pasted into a prompt) is written. Read a new cassette before committing it.

'''Matching.''' On replay a request matches a recorded one with the same method, URL and body, each masked as above; a JSON body is compared as JSON, and its prompts exactly, after that masking. A text body that is not JSON is compared after its log redaction, so two such bodies that differ only in what that masks match. Headers are not compared unless named in matchHeaders (anthropic-beta, ...), and credential headers never are, so a dummy key replays a recording made with a real one. Each recorded interaction plays once per client, the first unplayed match first. A request that matches none is a Left(CassetteMismatchError), naming the first JSON path at which its body differs from the recording, or the matched header that differs; in every mode but RecordNew it is never sent anywhere.

'''Sharing a file.''' Clients that record to one path in one JVM (Record, RecordIfMissing without the file, RecordNew) share its interactions and write lock, so a target client and a judge client recording to one cassette keep both their exchanges, and a later replay serves both. Open them all before either sends: opening one in Record starts the shared cassette over.

In Record mode a response body is read whole before it is returned, so a recording run does not stream in real time. A body over CassetteHttpClient.MaxBodyBytes, a multipart body, and an exchange that would make the cassette larger than CassetteHttpClient.MaxCassetteBytes are refused with a ValidationError. A failure of the live client is returned as it is and not recorded. The live client stays the caller's to close; close the cassette client too (Using.resource), which releases its hold on a shared cassette.

'''Known limitations.'''

  • Replay returns what was written, masked: a value under a credential-named key (a tool-call argument named token, say a pagination token) replays as [REDACTED], so a flow that sends that value back cannot replay.
  • A response that is not JSON (a form-encoded OAuth token response) and JSON nested deeper than llm4s's structural redaction reads are only scrubbed of registered secrets.
  • What is masked, and so what matches, depends on which secrets the JVM has registered (Redaction.scrubKnown): a request recorded in a JVM that held a secret may not match one replayed in a JVM that did not.
  • Embedding clients that take a supplied HTTP client (voyage, jina, cohere, openai embeddings) record and replay too; the openai, anthropic and bedrock chat clients ignore options.httpClient.

Attributes

Companion
object
Source
CassetteHttpClient.scala
Graph
Supertypes
class Object
trait Matchable
class Any

Members list

Value members

Concrete methods

override def close(): Unit

Releases this client's hold on its cassette: once every client recording to a path is closed, the next client on it reads the file afresh. It never closes the live client, which stays the caller's. Closing twice does nothing; a closed client answers every request with a Left.

Releases this client's hold on its cassette: once every client recording to a path is closed, the next client on it reads the file afresh. It never closes the live client, which stays the caller's. Closing twice does nothing; a closed client answers every request with a Left.

Attributes

Definition Classes
Source
CassetteHttpClient.scala
override def send(request: HttpRequest): Result[StreamingHttpResponse]

Sends request and returns the response with its body still open.

Sends request and returns the response with its body still open.

An implementation:

The caller closes the body, on a non-2xx status too. A failure while reading it surfaces as an IOException from the stream itself, not through the returned Result.

Attributes

Definition Classes
Source
CassetteHttpClient.scala

The recorded interactions no request has played yet, as METHOD url, in the cassette's order. Empty when every recording was used; in Record mode, every interaction recorded so far. A cassette shared by several clients (one path) lists what this client has not played, the others' recordings included.

The recorded interactions no request has played yet, as METHOD url, in the cassette's order. Empty when every recording was used; in Record mode, every interaction recorded so far. A cassette shared by several clients (one path) lists what this client has not played, the others' recordings included.

Attributes

Source
CassetteHttpClient.scala

Inherited methods

final def delete(url: String, headers: Map[String, String], timeout: FiniteDuration): Result[HttpResponse]

Sends a DELETE to url, with no body.

Sends a DELETE to url, with no body.

The response body is read as text, as sendText does. A non-2xx status is a Right; HttpResponse.ensureSuccess turns it into an error. Transport failures are the Lefts described on the trait.

Value parameters

headers

request headers

timeout

both of the request's timeouts, 10 seconds by default (HttpRequest.DefaultTimeout)

url

absolute http or https URL

Attributes

Inherited from:
Llm4sHttpClient
Source
Llm4sHttpClient.scala
final def get(url: String, headers: Map[String, String], params: Map[String, String], timeout: FiniteDuration): Result[HttpResponse]

Sends a GET to url, with params URL-encoded and appended as its query: after a & when url already has a query, else after a ?.

Sends a GET to url, with params URL-encoded and appended as its query: after a & when url already has a query, else after a ?.

The response body is read as text, as sendText does. A non-2xx status is a Right; HttpResponse.ensureSuccess turns it into an error. Transport failures are the Lefts described on the trait.

Value parameters

headers

request headers

params

query parameters; empty sends url unchanged

timeout

both of the request's timeouts, 10 seconds by default (HttpRequest.DefaultTimeout)

url

absolute http or https URL

Attributes

Inherited from:
Llm4sHttpClient
Source
Llm4sHttpClient.scala
final def post(url: String, headers: Map[String, String], body: String, timeout: FiniteDuration): Result[HttpResponse]

Sends a POST with body as text, encoded as UTF-8.

Sends a POST with body as text, encoded as UTF-8.

The response body is read as text, as sendText does. A non-2xx status is a Right; HttpResponse.ensureSuccess turns it into an error. Transport failures are the Lefts described on the trait.

Value parameters

body

the request body

headers

request headers

timeout

both of the request's timeouts, 10 seconds by default (HttpRequest.DefaultTimeout)

url

absolute http or https URL

Attributes

Inherited from:
Llm4sHttpClient
Source
Llm4sHttpClient.scala
final def postBytes(url: String, headers: Map[String, String], data: Array[Byte], timeout: FiniteDuration): Result[HttpResponse]

Sends a POST with data as the body, byte for byte.

Sends a POST with data as the body, byte for byte.

The response body is read as text, as sendText does. A non-2xx status is a Right; HttpResponse.ensureSuccess turns it into an error. Transport failures are the Lefts described on the trait.

Value parameters

data

the request body

headers

request headers

timeout

both of the request's timeouts, 10 seconds by default (HttpRequest.DefaultTimeout)

url

absolute http or https URL

Attributes

Inherited from:
Llm4sHttpClient
Source
Llm4sHttpClient.scala
final def postMultipart(url: String, headers: Map[String, String], parts: Seq[MultipartPart], timeout: FiniteDuration): Result[HttpResponse]

Sends a POST with parts as a multipart/form-data body. A MultipartPart.TextField is sent as a form field, and a MultipartPart.FilePart as a file with its filename and content type, its content read from its file or taken from its bytes. A file that cannot be read, or a part content type holding a line break, is a Left(ValidationError), and nothing is sent.

Sends a POST with parts as a multipart/form-data body. A MultipartPart.TextField is sent as a form field, and a MultipartPart.FilePart as a file with its filename and content type, its content read from its file or taken from its bytes. A file that cannot be read, or a part content type holding a line break, is a Left(ValidationError), and nothing is sent.

The response body is read as text, as sendText does. A non-2xx status is a Right; HttpResponse.ensureSuccess turns it into an error. Transport failures are the Lefts described on the trait.

Value parameters

headers

request headers

parts

the form fields and files, in order

timeout

both of the request's timeouts, 10 seconds by default (HttpRequest.DefaultTimeout)

url

absolute http or https URL

Attributes

Inherited from:
Llm4sHttpClient
Source
Llm4sHttpClient.scala
final def postRaw(url: String, headers: Map[String, String], body: String, timeout: FiniteDuration): Result[HttpRawResponse]

POST with a string body and return the response as raw bytes, bypassing charset decoding.

POST with a string body and return the response as raw bytes, bypassing charset decoding.

Use this when the response body is binary (e.g. image data) where decoding to a String and back would corrupt bytes that are not valid in the chosen charset.

Attributes

Inherited from:
Llm4sHttpClient
Source
Llm4sHttpClient.scala
final def postStream(url: String, headers: Map[String, String], body: String, timeout: FiniteDuration): Result[StreamingHttpResponse]

POST with a string body and return the response as a streaming InputStream.

POST with a string body and return the response as a streaming InputStream.

Use this for server-sent events or JSON-lines endpoints where the body must be consumed incrementally. The caller is responsible for closing the InputStream, including on a non-2xx status. A failure while reading the stream surfaces as an IOException from the stream itself, not through the returned Result.

The default timeout is 10 minutes, because a model may pause that long between events: it bounds the wait for the response head and each wait for the next bytes, never the length of the stream.

Attributes

Inherited from:
Llm4sHttpClient
Source
Llm4sHttpClient.scala
final def put(url: String, headers: Map[String, String], body: String, timeout: FiniteDuration): Result[HttpResponse]

Sends a PUT with body as text, encoded as UTF-8.

Sends a PUT with body as text, encoded as UTF-8.

The response body is read as text, as sendText does. A non-2xx status is a Right; HttpResponse.ensureSuccess turns it into an error. Transport failures are the Lefts described on the trait.

Value parameters

body

the request body

headers

request headers

timeout

both of the request's timeouts, 10 seconds by default (HttpRequest.DefaultTimeout)

url

absolute http or https URL

Attributes

Inherited from:
Llm4sHttpClient
Source
Llm4sHttpClient.scala
final def sendRaw(request: HttpRequest): Result[HttpRawResponse]

send, then the whole body as bytes; a failure while reading it is a Left. The body is closed.

send, then the whole body as bytes; a failure while reading it is a Left. The body is closed.

Attributes

Inherited from:
Llm4sHttpClient
Source
Llm4sHttpClient.scala
final def sendText(request: HttpRequest): Result[HttpResponse]

send, then the whole body as text in the charset its Content-Type names, UTF-8 when it names none; a failure while reading it is a Left. The body is closed.

send, then the whole body as text in the charset its Content-Type names, UTF-8 when it names none; a failure while reading it is a Left. The body is closed.

Attributes

Inherited from:
Llm4sHttpClient
Source
Llm4sHttpClient.scala

Concrete fields

Attributes

Source
CassetteHttpClient.scala
val path: Path

Attributes

Source
CassetteHttpClient.scala