ax

package
v0.10.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 5, 2026 License: MIT Imports: 2 Imported by: 0

Documentation

Overview

Package ax provides Agent Experience (AX) metadata for the ElevenLabs API.

This package is generated by ax-spec from x-ax-* OpenAPI extensions and API discovery. It provides:

  • Error code constants for machine-readable error handling
  • Retry policies indicating which operations are safe to retry
  • Capability mappings for operation introspection
  • Required field validation for request bodies

Error Handling Example:

import "github.com/plexusone/elevenlabs-go/ax"

resp, err := client.TextToSpeech().Generate(ctx, req)
if err != nil {
    apiErr := elevenlabs.ParseAPIError(err)
    if apiErr != nil && ax.IsErrorCode(apiErr, ax.ErrDocumentNotFound) {
        // Handle specific error
    }
}

Retry Policy Example:

if ax.IsRetryable("get_voices") {
    // Safe to implement automatic retry
}

The error codes were discovered by making actual API calls to the ElevenLabs API and extracting error codes from responses. This provides more accurate metadata than can be inferred from the OpenAPI specification alone.

Package ax provides Agent Experience (AX) helpers for ElevenLabs API integration.

This file contains helper functions specifically designed for OmniVoice integration, bridging between ElevenLabs AX error codes and the omnivoice-core resilience package.

Index

Constants

View Source
const (
	// ErrDocumentNotFound indicates the requested document was not found.
	ErrDocumentNotFound = "DOCUMENT_NOT_FOUND"

	// ErrInvalidUID indicates the provided UID is invalid.
	ErrInvalidUID = "INVALID_UID"

	// ErrMissingFeedback indicates feedback is required but was not provided.
	ErrMissingFeedback = "MISSING_FEEDBACK"

	// ErrNeedsAuthorization indicates the operation requires additional authorization.
	ErrNeedsAuthorization = "NEEDS_AUTHORIZATION"

	// ErrNotLoggedIn indicates the user is not authenticated.
	ErrNotLoggedIn = "NOT_LOGGED_IN"

	// ErrNoEditChanges indicates no changes were provided for an edit operation.
	ErrNoEditChanges = "NO_EDIT_CHANGES"

	// ErrUnprocessableEntity indicates a validation error in the request.
	ErrUnprocessableEntity = "UNPROCESSABLE_ENTITY"

	// ErrUserNotFound indicates the specified user was not found.
	ErrUserNotFound = "USER_NOT_FOUND"

	// ErrWorkspaceNotFound indicates the specified workspace was not found.
	ErrWorkspaceNotFound = "WORKSPACE_NOT_FOUND"
)

Error codes discovered from the ElevenLabs API via x-ax-error-code extensions. These codes appear in API error responses and can be used for machine-readable error handling instead of parsing error messages.

Variables

AllErrorCodes contains all known ElevenLabs API error codes.

View Source
var ErrorCodeMetadata = map[string]ErrorCodeInfo{
	ErrDocumentNotFound: {
		Code:        ErrDocumentNotFound,
		Description: "The requested document was not found",
		Retryable:   false,
		Category:    "not_found",
	},
	ErrInvalidUID: {
		Code:        ErrInvalidUID,
		Description: "The provided UID is invalid",
		Retryable:   false,
		Category:    "validation",
	},
	ErrMissingFeedback: {
		Code:        ErrMissingFeedback,
		Description: "Feedback is required but was not provided",
		Retryable:   false,
		Category:    "validation",
	},
	ErrNeedsAuthorization: {
		Code:        ErrNeedsAuthorization,
		Description: "The operation requires additional authorization",
		Retryable:   false,
		Category:    "auth",
	},
	ErrNotLoggedIn: {
		Code:        ErrNotLoggedIn,
		Description: "The user is not authenticated",
		Retryable:   false,
		Category:    "auth",
	},
	ErrNoEditChanges: {
		Code:        ErrNoEditChanges,
		Description: "No changes were provided for the edit operation",
		Retryable:   false,
		Category:    "validation",
	},
	ErrUnprocessableEntity: {
		Code:        ErrUnprocessableEntity,
		Description: "Request validation failed",
		Retryable:   false,
		Category:    "validation",
	},
	ErrUserNotFound: {
		Code:        ErrUserNotFound,
		Description: "The specified user was not found",
		Retryable:   false,
		Category:    "not_found",
	},
	ErrWorkspaceNotFound: {
		Code:        ErrWorkspaceNotFound,
		Description: "The specified workspace was not found",
		Retryable:   false,
		Category:    "not_found",
	},
}

ErrorCodeMetadata maps error codes to their metadata.

View Source
var OperationCapabilities = map[string][]Capability{

	"get_voices":          {CapRead},
	"get_voice_by_id":     {CapRead},
	"add_voice":           {CapWrite},
	"edit_voice":          {CapWrite},
	"delete_voice":        {CapWrite, CapDelete},
	"get_voice_settings":  {CapRead},
	"edit_voice_settings": {CapWrite},

	"text_to_speech_full":   {CapWrite},
	"text_to_speech_stream": {CapWrite},
	"text_to_dialogue":      {CapWrite},

	"speech_to_text": {CapWrite},

	"get_speech_history":            {CapRead},
	"get_speech_history_item_by_id": {CapRead},
	"delete_speech_history_item":    {CapWrite, CapDelete},
	"download_speech_history_items": {CapRead},

	"get_models": {CapRead},

	"get_user_info":              {CapRead},
	"get_user_subscription_info": {CapRead},

	"get_projects":      {CapRead},
	"get_project_by_id": {CapRead},
	"add_project":       {CapWrite},
	"delete_project":    {CapWrite, CapDelete},
	"edit_project":      {CapWrite},

	"create_dubbing":  {CapWrite},
	"delete_dubbing":  {CapWrite, CapDelete},
	"get_dubbed_file": {CapRead},
	"list_dubs":       {CapRead},

	"sound_generation": {CapWrite},

	"audio_isolation":        {CapWrite},
	"audio_isolation_stream": {CapWrite},

	"text_to_voice":         {CapWrite},
	"text_to_voice_design":  {CapWrite},
	"generate_random_voice": {CapWrite},

	"get_pronunciation_dictionaries_metadata": {CapRead},
	"get_pronunciation_dictionary_metadata":   {CapRead},
	"patch_pronunciation_dictionary":          {CapWrite},

	"get_agents_route":      {CapRead},
	"get_agent_route":       {CapRead},
	"create_agent_route":    {CapWrite},
	"delete_agent_route":    {CapWrite, CapDelete},
	"duplicate_agent_route": {CapWrite},

	"get_workspace_service_accounts": {CapRead, CapAdmin},
	"create_service_account_api_key": {CapWrite, CapAdmin},
	"delete_service_account_api_key": {CapWrite, CapDelete, CapAdmin},
	"invite_user":                    {CapWrite, CapAdmin},
	"remove_member":                  {CapWrite, CapDelete, CapAdmin},
}

OperationCapabilities maps operation IDs to their capabilities. Capabilities indicate what an operation can do:

  • read: retrieves data without modification
  • write: creates or modifies data
  • delete: removes data
  • admin: administrative operations requiring elevated permissions
View Source
var RequiredFields = map[string][]string{
	"add_chapter":                              {"name"},
	"add_from_rules":                           {"rules", "name"},
	"add_language":                             {"language"},
	"add_mcp_server_tool_approval_route":       {"tool_name", "tool_description"},
	"add_mcp_tool_config_override_route":       {"tool_name"},
	"add_member":                               {"email"},
	"add_rules":                                {"rules"},
	"add_sharing_voice":                        {"new_name"},
	"add_tool_route":                           {"tool_config"},
	"compose_plan":                             {"prompt"},
	"create_agent_response_test_route":         {"chat_history", "success_condition", "success_examples", "failure_examples", "name"},
	"create_agent_route":                       {"conversation_config"},
	"create_batch_call":                        {"call_name", "agent_id", "recipients"},
	"create_clip":                              {"start_time", "end_time"},
	"create_mcp_server_route":                  {"config"},
	"create_podcast":                           {"model_id", "mode", "source"},
	"create_pvc_voice":                         {"name", "language"},
	"create_secret_route":                      {"type", "name", "value"},
	"create_service_account_api_key":           {"name", "permissions"},
	"create_text_document_route":               {"text"},
	"create_url_document_route":                {"url"},
	"create_voice":                             {"voice_name", "voice_description", "generated_voice_id"},
	"create_voice_old":                         {"voice_name", "voice_description", "generated_voice_id"},
	"create_workspace_webhook_route":           {"settings"},
	"download_speech_history_items":            {"history_item_ids"},
	"dub":                                      {"segments", "languages"},
	"edit_project":                             {"name", "default_title_voice_id", "default_paragraph_voice_id"},
	"edit_service_account_api_key":             {"is_enabled", "name", "permissions"},
	"edit_workspace_webhook_route":             {"is_disabled", "name"},
	"generate_random_voice":                    {"gender", "accent", "age", "accent_strength", "text"},
	"get_agent_response_tests_summaries_route": {"test_ids"},
	"get_or_create_rag_indexes":                {"items"},
	"get_public_llm_expected_cost_calculation": {"prompt_length", "number_of_pages", "rag_enabled"},
	"handle_sip_trunk_outbound_call":           {"agent_id", "agent_phone_number_id", "to_number"},
	"handle_twilio_outbound_call":              {"agent_id", "agent_phone_number_id", "to_number"},
	"import_whatsapp_account":                  {"business_account_id", "phone_number_id", "token_code"},
	"invite_user":                              {"email"},
	"invite_users_bulk":                        {"emails"},
	"migrate_segments":                         {"segment_ids", "speaker_id"},
	"rag_index_status":                         {"model"},
	"register_twilio_call":                     {"agent_id", "from_number", "to_number"},
	"remove_member":                            {"email"},
	"remove_rules":                             {"rule_strings"},
	"render":                                   {"render_type"},
	"resubmit_tests_route":                     {"test_run_ids", "agent_id"},
	"run_agent_test_suite_route":               {"tests"},
	"run_conversation_simulation_route":        {"simulation_specification"},
	"run_conversation_simulation_route_stream": {"simulation_specification"},
	"share_resource_endpoint":                  {"role", "resource_type"},
	"sound_generation":                         {"text"},
	"text_to_dialogue":                         {"inputs"},
	"text_to_dialogue_full_with_timestamps":    {"inputs"},
	"text_to_dialogue_stream":                  {"inputs"},
	"text_to_dialogue_stream_with_timestamps":  {"inputs"},
	"text_to_speech_full":                      {"text"},
	"text_to_speech_full_with_timestamps":      {"text"},
	"text_to_speech_stream":                    {"text"},
	"text_to_speech_stream_with_timestamps":    {"text"},
	"text_to_voice":                            {"voice_description"},
	"text_to_voice_design":                     {"voice_description"},
	"text_to_voice_remix":                      {"voice_description"},
	"transcribe":                               {"segments"},
	"translate":                                {"segments", "languages"},
	"unshare_resource_endpoint":                {"resource_type"},
	"update_agent_response_test_route":         {"chat_history", "success_condition", "success_examples", "failure_examples", "name"},
	"update_document_route":                    {"name"},
	"update_mcp_server_approval_policy_route":  {"approval_policy"},
	"update_pronunciation_dictionaries":        {"pronunciation_dictionary_locators"},
	"update_secret_route":                      {"type", "name", "value"},
	"update_tool_route":                        {"tool_config"},
	"update_workspace_member":                  {"email"},
	"whatsapp_outbound_call":                   {"whatsapp_phone_number_id", "whatsapp_user_id", "whatsapp_call_permission_request_template_name", "whatsapp_call_permission_request_template_language_code", "agent_id"},
}

RequiredFields maps operation IDs to their required input fields. This is extracted from the OpenAPI specification's requestBody schema required fields, allowing pre-flight validation before making API calls.

View Source
var RetryPolicy = map[string]bool{}/* 212 elements not displayed */

RetryPolicy maps operation IDs to their retry safety. true = safe to retry automatically (idempotent reads) false = not safe to retry without user confirmation (may cause duplicates)

This information is derived from:

  • HTTP method (GET/HEAD/OPTIONS are generally safe)
  • Operation semantics (create operations are not safe)
  • x-ax-retryable extensions when present

Functions

func AllCategories

func AllCategories() []string

AllCategories returns all error categories used by ElevenLabs AX errors.

func CategoryForCode

func CategoryForCode(code string) resilience.ErrorCategory

CategoryForCode returns the resilience.ErrorCategory for an AX error code. Returns CategoryUnknown if the code is not recognized.

Example:

if code, ok := ax.ContainsErrorCode(err); ok {
    category := ax.CategoryForCode(code)
    if category == resilience.CategoryAuth {
        // Handle auth error
    }
}

func ClassifyHTTPStatus

func ClassifyHTTPStatus(status int, message string) resilience.ErrorInfo

ClassifyHTTPStatus returns a resilience.ErrorInfo for an HTTP status code. This is useful when no AX error code is available in the response.

func CodesByCategory

func CodesByCategory(category string) []string

CodesByCategory returns all AX error codes for a given category.

Example:

authCodes := ax.CodesByCategory("auth")
// Returns: ["NEEDS_AUTHORIZATION", "NOT_LOGGED_IN"]

func ContainsErrorCode

func ContainsErrorCode(err error) (string, bool)

ContainsErrorCode extracts the AX error code from an error, if present. Returns the matching code and true if found, empty string and false otherwise.

func GetNonRetryableOperations

func GetNonRetryableOperations() []string

GetNonRetryableOperations returns all operation IDs that are NOT safe to retry.

func GetOperationsByCapability

func GetOperationsByCapability(cap Capability) []string

GetOperationsByCapability returns all operations that have a specific capability.

func GetRequiredFields

func GetRequiredFields(operationID string) []string

GetRequiredFields returns the required fields for an operation. Returns nil if the operation has no required fields or is not found.

func GetRetryableOperations

func GetRetryableOperations() []string

GetRetryableOperations returns all operation IDs that are safe to retry.

func HasCapability

func HasCapability(operationID string, cap Capability) bool

HasCapability checks if an operation has a specific capability.

func HasRequiredFields

func HasRequiredFields(operationID string) bool

HasRequiredFields returns true if the operation has required fields.

func IsAuthError

func IsAuthError(code string) bool

IsAuthError returns true if the error code indicates an authentication/authorization issue.

func IsErrorCode

func IsErrorCode(err error, code string) bool

IsErrorCode checks if an error contains the specified AX error code. It works with any error type by checking if the error string contains the code. For more precise matching, use IsErrorCodeExact with an APIErrorer.

func IsNotFoundError

func IsNotFoundError(code string) bool

IsNotFoundError returns true if the error code indicates a resource was not found.

func IsReadOnly

func IsReadOnly(operationID string) bool

IsReadOnly returns true if an operation only has read capability.

func IsRetryable

func IsRetryable(operationID string) bool

IsRetryable returns whether an operation is safe to retry automatically. Operations not in the map default to false (not retryable).

func IsRetryableCode

func IsRetryableCode(code string) bool

IsRetryableCode returns true if the AX error code represents a retryable error. Returns false for unknown codes.

Example:

if code, ok := ax.ContainsErrorCode(err); ok {
    if ax.IsRetryableCode(code) {
        // Safe to retry
    }
}

func IsValidationError

func IsValidationError(code string) bool

IsValidationError returns true if the error code indicates a validation failure.

func MissingFields

func MissingFields(operationID string, presentFields map[string]bool) []string

MissingFields checks which required fields are missing from a request. The provided map should contain the field names that are present. Returns a slice of missing field names.

func RequiresAdmin

func RequiresAdmin(operationID string) bool

RequiresAdmin returns true if an operation requires admin capability.

func SuggestionForCode

func SuggestionForCode(code string) string

SuggestionForCode returns a helpful suggestion for resolving an AX error code. Returns a generic suggestion for unknown codes.

Example:

if code, ok := ax.ContainsErrorCode(err); ok {
    suggestion := ax.SuggestionForCode(code)
    log.Printf("Error: %s. Suggestion: %s", code, suggestion)
}

func ToErrorInfo

func ToErrorInfo(code string) resilience.ErrorInfo

ToErrorInfo converts an AX error code to a resilience.ErrorInfo. This is useful for wrapping ElevenLabs errors as ProviderErrors.

Example:

if code, ok := ax.ContainsErrorCode(err); ok {
    info := ax.ToErrorInfo(code)
    return resilience.NewProviderError("elevenlabs", "Synthesize", err, info)
}

func ValidateFields

func ValidateFields(operationID string, presentFields map[string]bool) string

ValidateFields returns an error message if required fields are missing. Returns empty string if all required fields are present.

Types

type APIErrorer

type APIErrorer interface {
	error
	APIDetail() string
	APIMessage() string
}

APIErrorer is an interface for errors that provide API error details. The elevenlabs.APIError type implements this interface.

type Capability

type Capability string

Capability represents an operation capability for agent introspection.

const (
	CapRead   Capability = "read"
	CapWrite  Capability = "write"
	CapDelete Capability = "delete"
	CapAdmin  Capability = "admin"
)

Standard capabilities derived from operation semantics.

func GetCapabilities

func GetCapabilities(operationID string) []Capability

GetCapabilities returns the capabilities for an operation. Returns nil if the operation is not found.

type ErrorCodeInfo

type ErrorCodeInfo struct {
	Code        string
	Description string
	Retryable   bool
	Category    string
}

ErrorCodeInfo provides metadata about an error code.

func GetErrorInfo

func GetErrorInfo(code string) *ErrorCodeInfo

GetErrorInfo returns metadata about an error code. Returns nil if the code is not recognized.

type Operation

type Operation string

Operation represents an ElevenLabs API operation.

const (
	OpTextToSpeech     Operation = "text-to-speech"
	OpSpeechToText     Operation = "speech-to-text"
	OpVoiceClone       Operation = "voice-clone"
	OpVoiceDesign      Operation = "voice-design"
	OpSoundGeneration  Operation = "sound-generation"
	OpAudioIsolation   Operation = "audio-isolation"
	OpDubbing          Operation = "dubbing"
	OpProjects         Operation = "projects"
	OpPronunciation    Operation = "pronunciation"
	OpConversationalAI Operation = "conversational-ai"
)

Known ElevenLabs API operations.

type RequiredField

type RequiredField struct {
	Name        string
	Description string
	Example     string
}

RequiredField represents a required field for an operation.

func OperationRequiredFields

func OperationRequiredFields(op Operation) []RequiredField

OperationRequiredFields returns the required fields for an ElevenLabs API operation. This enables pre-flight validation before making API calls.

Example:

fields := ax.OperationRequiredFields(ax.OpTextToSpeech)
for _, f := range fields {
    if isEmpty(request[f.Name]) {
        return fmt.Errorf("missing required field: %s", f.Name)
    }
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL