Error Handling

When BAML raises an exception, it will be an instance of a subclass of BamlError. This allows you to catch all BAML-specific exceptions with a single except block.

Example

1from baml_client import b
2from baml_py.errors import BamlError, BamlInvalidArgumentError, BamlClientError, BamlClientHttpError, BamlValidationError
3
4try:
5 b.CallFunctionThatRaisesError()
6except BamlError as e:
7 print(e)
8
9
10try:
11 b.CallFunctionThatRaisesError()
12except BamlValidationError as e:
13 # The original prompt sent to the LLM
14 print(e.prompt)
15 # The LLM response string
16 print(e.raw_output)
17 # A human-readable error message
18 print(e.message)

BamlError

Base class for all BAML exceptions.

message
string

A human-readable error message.

BamlInvalidArgumentError

Subclass of BamlError.

Raised when one or multiple arguments to a function are invalid.

BamlClientError

Subclass of BamlError.

Raised when a client fails to return a valid response.

In the case of aggregate clients like fallback or those with retry_policy, only the last client’s error is raised.

BamlClientHttpError

Subclass of BamlClientError.

Raised when the HTTP request made by a client fails with a non-200 status code.

status_code
int

The status code of the response.

Common status codes are:

  • 1: Other
  • 2: Other
  • 400: Bad Request
  • 401: Unauthorized
  • 403: Forbidden
  • 404: Not Found
  • 429: Too Many Requests
  • 500: Internal Server Error

BamlValidationError

Subclass of BamlError.

Raised when BAML fails to parse a string from the LLM into the specified object.

raw_output
string

The raw text from the LLM that failed to parse into the expected return type of a function.

message
string

The parsing-related error message.

prompt
string

The original prompt that was sent to the LLM, formatted as a plain string. Images sent as base64-encoded strings are not serialized into this field.