### Initialize TelnyxClient Merging Environment and Manual Settings Source: https://context7.com/team-telnyx/telnyx-java/llms.txt Create a TelnyxClient by starting with environment variable defaults and then overriding specific settings like max retries. ```java import com.telnyx.sdk.client.TelnyxClient; import com.telnyx.sdk.client.okhttp.TelnyxOkHttpClient; // Option 3 – merge env defaults with explicit overrides TelnyxClient client = TelnyxOkHttpClient.builder() .fromEnv() .maxRetries(5) .build(); ``` -------------------------------- ### Automatic and Manual Pagination Source: https://context7.com/team-telnyx/telnyx-java/llms.txt Examples demonstrate using `autoPager()` for automatic iteration through all pages and manual paging by repeatedly calling `nextPage()`. Useful for handling large datasets. ```java import com.telnyx.sdk.models.accessipaddress.*; // Auto-pagination (synchronous stream) AccessIpAddressListPage firstPage = client.accessIpAddress().list(); // Stream style firstPage.autoPager() .stream() .limit(100) .forEach(addr -> System.out.println(addr.ipAddress())); // Iterable style for (AccessIpAddressResponse addr : firstPage.autoPager()) { System.out.println(addr.ipAddress()); } // Manual page-by-page AccessIpAddressListPage page = client.accessIpAddress().list(); while (true) { for (AccessIpAddressResponse addr : page.items()) { System.out.println(addr.ipAddress()); } if (!page.hasNextPage()) break; page = page.nextPage(); } ``` -------------------------------- ### Creating JsonValue Objects Source: https://github.com/team-telnyx/telnyx-java/blob/master/README.md Provides examples of creating `JsonValue` objects for various data types, including primitives, arrays, objects, and complex nested structures. ```APIDOC ## Creating JsonValue Objects The most straightforward way to create a [`JsonValue`](telnyx-core/src/main/kotlin/com/telnyx/sdk/core/Values.kt) is using its `from(...)` method: ```java import com.telnyx.sdk.core.JsonValue; import java.util.List; import java.util.Map; // Create primitive JSON values JsonValue nullValue = JsonValue.from(null); JsonValue booleanValue = JsonValue.from(true); JsonValue numberValue = JsonValue.from(42); JsonValue stringValue = JsonValue.from("Hello World!"); // Create a JSON array value equivalent to `["Hello", "World"]` JsonValue arrayValue = JsonValue.from(List.of( "Hello", "World" )); // Create a JSON object value equivalent to `{ "a": 1, "b": 2 }` JsonValue objectValue = JsonValue.from(Map.of( "a", 1, "b", 2 )); // Create an arbitrarily nested JSON equivalent to: // { // "a": [1, 2], // "b": [3, 4] // } JsonValue complexValue = JsonValue.from(Map.of( "a", List.of( 1, 2 ), "b", List.of( 3, 4 ) )); ``` ``` -------------------------------- ### Manage IoT SIM Cards and Connectivity Source: https://context7.com/team-telnyx/telnyx-java/llms.txt Use `client.simCards()` to list, retrieve, and manage SIM cards. You can also get the public IP address and list wireless connectivity logs for a given SIM card. ```java import com.telnyx.sdk.models.simcards.*; // List all SIM cards SimCardListPage page = client.simCards().list(SimCardListParams.none()); page.autoPager().forEach(sim -> System.out.println(sim.iccid() + " — " + sim.status()) ); // Retrieve one SIM SimCardRetrieveResponse sim = client.simCards().retrieve("sim_id_abc123"); System.out.println("ICCID: " + sim.iccid()); System.out.println("Status: " + sim.status()); // Get public IP SimCardGetPublicIpResponse ip = client.simCards().getPublicIp("sim_id_abc123"); System.out.println("IP: " + ip.ip()); // List wireless connectivity logs SimCardListWirelessConnectivityLogsPage logs = client.simCards() .listWirelessConnectivityLogs("sim_id_abc123", SimCardListWirelessConnectivityLogsParams.none()); logs.autoPager().forEach(log -> System.out.println(log.createdAt() + " — " + log.type())); ``` -------------------------------- ### Retrieve and Delete Call Recordings Source: https://context7.com/team-telnyx/telnyx-java/llms.txt Use `client.recordings()` to get metadata, list recordings, or delete them. Ensure you have the correct recording ID. ```java import com.telnyx.sdk.models.recordings.*; import com.telnyx.sdk.core.http.HttpResponse; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; // Retrieve metadata RecordingRetrieveResponse rec = client.recordings().retrieve("recording_id_abc"); System.out.println("Duration: " + rec.durationMillis() + "ms"); // List recordings RecordingListPage page = client.recordings().list(RecordingListParams.none()); page.autoPager().forEach(r -> System.out.println(r.id())); // Delete client.recordings().delete("recording_id_abc"); ``` -------------------------------- ### Performing Call Control Actions Source: https://context7.com/team-telnyx/telnyx-java/llms.txt Execute various mid-call commands on a live call leg, such as speaking text, gathering DTMF input, starting recordings, transferring, or hanging up. Requires the call control ID. ```java import com.telnyx.sdk.models.calls.actions.*; String callControlId = "call_control_id_abc123"; // Speak text-to-speech to the caller ActionSpeakResponse speakResp = client.calls().actions().speak( callControlId, ActionSpeakParams.builder() .payload("Hello, please press 1 for sales or 2 for support.") .language("en-US") .voice(ActionSpeakParams.Voice.FEMALE) .build() ); // Gather DTMF digits after the TTS plays ActionGatherResponse gatherResp = client.calls().actions().gather( callControlId, ActionGatherParams.builder() .minimumDigits(1L) .maximumDigits(1L) .timeoutMillis(5000L) .build() ); // Start recording ActionStartRecordingResponse recResp = client.calls().actions().startRecording( callControlId, ActionStartRecordingParams.builder() .format(ActionStartRecordingParams.Format.MP3) .channels(ActionStartRecordingParams.Channels.SINGLE) .build() ); // Transfer the call ActionTransferResponse transferResp = client.calls().actions().transfer( callControlId, ActionTransferParams.builder() .to("+18005551234") .build() ); // Hang up client.calls().actions().hangup(callControlId); ``` -------------------------------- ### Get Raw HTTP Response with Headers and Status Code Source: https://github.com/team-telnyx/telnyx-java/blob/master/README.md Prefix API calls with `withRawResponse()` to access the status code, headers, and the raw response body. This is useful when you need more than just the deserialized object. ```java import com.telnyx.sdk.core.http.Headers; import com.telnyx.sdk.core.http.HttpResponseFor; import com.telnyx.sdk.models.numberorders.NumberOrderCreateParams; import com.telnyx.sdk.models.numberorders.NumberOrderCreateResponse; NumberOrderCreateParams params = NumberOrderCreateParams.builder() .addPhoneNumber(NumberOrderCreateParams.PhoneNumber.builder() .phoneNumber("+15558675309") .build()) .build(); HttpResponseFor numberOrder = client.numberOrders().withRawResponse().create(params); int statusCode = numberOrder.statusCode(); Headers headers = numberOrder.headers(); ``` -------------------------------- ### Client Initialization Source: https://context7.com/team-telnyx/telnyx-java/llms.txt Demonstrates how to initialize the TelnyxClient using environment variables or manual configuration, including options for proxy and timeouts. ```APIDOC ## Client Initialization — `TelnyxOkHttpClient` Create a `TelnyxClient` from environment variables (`TELNYX_API_KEY`, etc.) or manually via the builder. Reuse one instance for the lifetime of the application. ```java import com.telnyx.sdk.client.TelnyxClient; import com.telnyx.sdk.client.okhttp.TelnyxOkHttpClient; import java.net.InetSocketAddress; import java.net.Proxy; import java.time.Duration; // Option 1 – from environment variables / system properties TelnyxClient client = TelnyxOkHttpClient.fromEnv(); // Option 2 – manual construction with full options TelnyxClient client = TelnyxOkHttpClient.builder() .apiKey("YOUR_API_KEY") .baseUrl("https://api.telnyx.com/v2") // optional override .maxRetries(3) .timeout(Duration.ofSeconds(45)) .maxIdleConnections(10) .keepAliveDuration(Duration.ofMinutes(2)) .proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.example.com", 8080))) .responseValidation(true) .build(); // Option 3 – merge env defaults with explicit overrides TelnyxClient client = TelnyxOkHttpClient.builder() .fromEnv() .maxRetries(5) .build(); // Release resources when the application exits (optional) client.close(); ``` ``` -------------------------------- ### Configure Client with Hybrid Approach Source: https://github.com/team-telnyx/telnyx-java/blob/master/README.md Combine environment variable configuration with manual settings. System properties and environment variables are read first, then overridden by explicit builder methods. ```java import com.telnyx.sdk.client.TelnyxClient; import com.telnyx.sdk.client.okhttp.TelnyxOkHttpClient; TelnyxClient client = TelnyxOkHttpClient.builder() // Configures using the `telnyx.apiKey`, `telnyx.publicKey`, `telnyx.clientId`, `telnyx.clientSecret` and `telnyx.baseUrl` system properties // Or configures using the `TELNYX_API_KEY`, `TELNYX_PUBLIC_KEY`, `TELNYX_CLIENT_ID`, `TELNYX_CLIENT_SECRET` and `TELNYX_BASE_URL` environment variables .fromEnv() .apiKey("My API Key") .build(); ``` -------------------------------- ### Configure Client from Environment Variables Source: https://github.com/team-telnyx/telnyx-java/blob/master/README.md Configure the client using environment variables. Ensure the necessary variables like `TELNYX_API_KEY` are set. ```java import com.telnyx.sdk.client.TelnyxClient; import com.telnyx.sdk.client.okhttp.TelnyxOkHttpClient; // Configures using the `telnyx.apiKey`, `telnyx.publicKey`, `telnyx.clientId`, `telnyx.clientSecret` and `telnyx.baseUrl` system properties // Or configures using the `TELNYX_API_KEY`, `TELNYX_PUBLIC_KEY`, `TELNYX_CLIENT_ID`, `TELNYX_CLIENT_SECRET` and `TELNYX_BASE_URL` environment variables TelnyxClient client = TelnyxOkHttpClient.fromEnv(); ``` -------------------------------- ### Initialize TelnyxClient from Environment Variables Source: https://context7.com/team-telnyx/telnyx-java/llms.txt Create a TelnyxClient instance using default settings loaded from environment variables (e.g., TELNYX_API_KEY). ```java import com.telnyx.sdk.client.TelnyxClient; import com.telnyx.sdk.client.okhttp.TelnyxOkHttpClient; // Option 1 – from environment variables / system properties TelnyxClient client = TelnyxOkHttpClient.fromEnv(); ``` -------------------------------- ### Temporary Client Configuration with `withOptions()` Source: https://context7.com/team-telnyx/telnyx-java/llms.txt Demonstrates how to create a derived `TelnyxClient` instance with temporarily modified configuration options, such as a different base URL or retry count, without affecting the original client. ```APIDOC ## `withOptions()` — Temporary Client Configuration Reuse the same connection pool with a temporarily modified configuration. ```java import com.telnyx.sdk.client.TelnyxClient; // Creates a derived view; does NOT mutate the original client TelnyxClient staging = client.withOptions(o -> { o.baseUrl("https://api-staging.telnyx.com/v2"); o.maxRetries(0); }); // All calls through `staging` use the staging URL; `client` is unchanged ``` ``` -------------------------------- ### Temporary Client Configuration with `withOptions()` Source: https://context7.com/team-telnyx/telnyx-java/llms.txt Create a derived client with temporary configuration overrides without affecting the original client. Useful for testing or specific request modifications. ```java import com.telnyx.sdk.client.TelnyxClient; // Creates a derived view; does NOT mutate the original client TelnyxClient staging = client.withOptions(o -> { o.baseUrl("https://api-staging.telnyx.com/v2"); o.maxRetries(0); }); // All calls through `staging` use the staging URL; `client` is unchanged ``` -------------------------------- ### Create and Manage Conferences Source: https://context7.com/team-telnyx/telnyx-java/llms.txt Demonstrates creating a conference from a call leg, listing existing conferences, and updating participants (e.g., muting). ```java import com.telnyx.sdk.models.conferences.*; // Create a conference from an existing call leg ConferenceCreateResponse conf = client.conferences().create( ConferenceCreateParams.builder() .callControlId("call_control_id_abc123") .name("Sales Team Standup") .build() ); System.out.println("Conference ID: " + conf.id()); // List conferences (paginated) ConferenceListPage page = client.conferences().list(ConferenceListParams.none()); for (ConferenceRetrieveResponse c : page.autoPager()) { System.out.println(c.name() + " — " + c.status()); } // Update a participant (mute) client.conferences().updateParticipant( conf.id().get(), ConferenceUpdateParticipantParams.builder() .callControlId("call_control_id_abc123") .mute(true) .build() ); ``` -------------------------------- ### Enable Logging with Environment Variable Source: https://github.com/team-telnyx/telnyx-java/blob/master/README.md Configure SDK logging levels by setting the `TELNYX_LOG` environment variable. Use `info` for standard logging or `debug` for verbose output. ```sh export TELNYX_LOG=info ``` ```sh export TELNYX_LOG=debug ``` -------------------------------- ### Create Asynchronous Client Directly Source: https://github.com/team-telnyx/telnyx-java/blob/master/README.md Instantiate an asynchronous client directly using `TelnyxOkHttpClientAsync.fromEnv()`. This client's methods return `CompletableFuture`s. ```java import com.telnyx.sdk.client.TelnyxClientAsync; import com.telnyx.sdk.client.okhttp.TelnyxOkHttpClientAsync; import com.telnyx.sdk.models.calls.CallDialParams; import com.telnyx.sdk.models.calls.CallDialResponse; import java.util.concurrent.CompletableFuture; // Configures using the `telnyx.apiKey`, `telnyx.publicKey`, `telnyx.clientId`, `telnyx.clientSecret` and `telnyx.baseUrl` system properties // Or configures using the `TELNYX_API_KEY`, `TELNYX_PUBLIC_KEY`, `TELNYX_CLIENT_ID`, `TELNYX_CLIENT_SECRET` and `TELNYX_BASE_URL` environment variables TelnyxClientAsync client = TelnyxOkHttpClientAsync.fromEnv(); CallDialParams params = CallDialParams.builder() .connectionId("conn12345") .from("+15557654321") .to("+15551234567") .webhookUrl("https://your-webhook.url/events") .build(); CompletableFuture response = client.calls().dial(params); ``` -------------------------------- ### Initialize TelnyxClient with Manual Configuration Source: https://context7.com/team-telnyx/telnyx-java/llms.txt Manually construct a TelnyxClient with detailed configuration options including API key, base URL, retry settings, timeouts, connection pooling, and proxy. ```java import com.telnyx.sdk.client.TelnyxClient; import com.telnyx.sdk.client.okhttp.TelnyxOkHttpClient; import java.net.InetSocketAddress; import java.net.Proxy; import java.time.Duration; // Option 2 – manual construction with full options TelnyxClient client = TelnyxOkHttpClient.builder() .apiKey("YOUR_API_KEY") .baseUrl("https://api.telnyx.com/v2") // optional override .maxRetries(3) .timeout(Duration.ofSeconds(45)) .maxIdleConnections(10) .keepAliveDuration(Duration.ofMinutes(2)) .proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.example.com", 8080))) .responseValidation(true) .build(); ``` -------------------------------- ### Configure Client Manually with API Key Source: https://github.com/team-telnyx/telnyx-java/blob/master/README.md Manually configure the client by providing your API key directly. This is useful for hardcoded configurations or when environment variables are not preferred. ```java import com.telnyx.sdk.client.TelnyxClient; import com.telnyx.sdk.client.okhttp.TelnyxOkHttpClient; TelnyxClient client = TelnyxOkHttpClient.builder() .apiKey("My API Key") .build(); ``` -------------------------------- ### Initialize Telnyx Client and Dial a Call Source: https://github.com/team-telnyx/telnyx-java/blob/master/README.md Initializes the Telnyx client using environment variables or system properties and demonstrates how to dial a call. Ensure necessary Telnyx credentials are set. ```java import com.telnyx.sdk.client.TelnyxClient; import com.telnyx.sdk.client.okhttp.TelnyxOkHttpClient; import com.telnyx.sdk.models.calls.CallDialParams; import com.telnyx.sdk.models.calls.CallDialResponse; // Configures using the `telnyx.apiKey`, `telnyx.publicKey`, `telnyx.clientId`, `telnyx.clientSecret` and `telnyx.baseUrl` system properties // Or configures using the `TELNYX_API_KEY`, `TELNYX_PUBLIC_KEY`, `TELNYX_CLIENT_ID`, `TELNYX_CLIENT_SECRET` and `TELNYX_BASE_URL` environment variables TelnyxClient client = TelnyxOkHttpClient.fromEnv(); CallDialParams params = CallDialParams.builder() .connectionId("conn12345") .from("+15557654321") .to("+15551234567") .webhookUrl("https://your-webhook.url/events") .build(); CallDialResponse response = client.calls().dial(params); ``` -------------------------------- ### Modify Client Configuration Temporarily Source: https://github.com/team-telnyx/telnyx-java/blob/master/README.md Create a modified client configuration for temporary use without affecting the original client. This is done by calling `withOptions()` on an existing client or service. ```java import com.telnyx.sdk.client.TelnyxClient; TelnyxClient clientWithOptions = client.withOptions(optionsBuilder -> { optionsBuilder.baseUrl("https://example.com"); optionsBuilder.maxRetries(42); }); ``` -------------------------------- ### Switch to Asynchronous Execution Source: https://github.com/team-telnyx/telnyx-java/blob/master/README.md Call the `async()` method on an existing client to enable asynchronous operations. Configuration can be done via system properties or environment variables. ```java import com.telnyx.sdk.client.TelnyxClient; import com.telnyx.sdk.client.okhttp.TelnyxOkHttpClient; import com.telnyx.sdk.models.calls.CallDialParams; import com.telnyx.sdk.models.calls.CallDialResponse; import java.util.concurrent.CompletableFuture; // Configures using the `telnyx.apiKey`, `telnyx.publicKey`, `telnyx.clientId`, `telnyx.clientSecret` and `telnyx.baseUrl` system properties // Or configures using the `TELNYX_API_KEY`, `TELNYX_PUBLIC_KEY`, `TELNYX_CLIENT_ID`, `TELNYX_CLIENT_SECRET` and `TELNYX_BASE_URL` environment variables TelnyxClient client = TelnyxOkHttpClient.fromEnv(); CallDialParams params = CallDialParams.builder() .connectionId("conn12345") .from("+15557654321") .to("+15551234567") .webhookUrl("https://your-webhook.url/events") .build(); CompletableFuture response = client.async().calls().dial(params); ``` -------------------------------- ### Configure OkHttp Request/Response Logging Source: https://context7.com/team-telnyx/telnyx-java/llms.txt Enable logging for OkHttp requests and responses by setting the TELNYX_LOG environment variable to 'info' for basic details or 'debug' for full headers and bodies. ```bash # Info-level (request/response lines) export TELNYX_LOG=info # Debug-level (full headers and bodies) export TELNYX_LOG=debug ``` -------------------------------- ### Upload Audio File via Path Source: https://github.com/team-telnyx/telnyx-java/blob/master/README.md Transcribe an audio file by providing its `Path`. Ensure the file exists at the specified location. ```java import com.telnyx.sdk.models.ai.audio.AudioTranscribeParams; import com.telnyx.sdk.models.ai.audio.AudioTranscribeResponse; import java.nio.file.Paths; AudioTranscribeParams params = AudioTranscribeParams.builder() .model(AudioTranscribeParams.Model.DISTIL_WHISPER_DISTIL_LARGE_V2) .file(Paths.get("/path/to/file")) .build(); AudioTranscribeResponse response = client.ai().audio().transcribe(params); ``` -------------------------------- ### Call Control Actions with `client.calls().actions()` Source: https://context7.com/team-telnyx/telnyx-java/llms.txt Enables sending various mid-call commands to a live call leg, including answering, hanging up, text-to-speech playback, audio playback, DTMF gathering, call bridging, transferring, recording, forking, and transcription. ```APIDOC ## Call Control Actions — `client.calls().actions()` Send mid-call commands to a live call leg: answer, hangup, speak TTS, play audio, gather DTMF, bridge, transfer, record, fork, transcribe, and more. ```java import com.telnyx.sdk.models.calls.actions.*; String callControlId = "call_control_id_abc123"; // Speak text-to-speech to the caller ActionSpeakResponse speakResp = client.calls().actions().speak( callControlId, ActionSpeakParams.builder() .payload("Hello, please press 1 for sales or 2 for support.") .language("en-US") .voice(ActionSpeakParams.Voice.FEMALE) .build() ); // Gather DTMF digits after the TTS plays ActionGatherResponse gatherResp = client.calls().actions().gather( callControlId, ActionGatherParams.builder() .minimumDigits(1L) .maximumDigits(1L) .timeoutMillis(5000L) .build() ); // Start recording ActionStartRecordingResponse recResp = client.calls().actions().startRecording( callControlId, ActionStartRecordingParams.builder() .format(ActionStartRecordingParams.Format.MP3) .channels(ActionStartRecordingParams.Channels.SINGLE) .build() ); // Transfer the call ActionTransferResponse transferResp = client.calls().actions().transfer( callControlId, ActionTransferParams.builder() .to("+18005551234") .build() ); // Hang up client.calls().actions().hangup(callControlId); ``` ``` -------------------------------- ### Configure Proxy for Telnyx Client Source: https://github.com/team-telnyx/telnyx-java/blob/master/README.md Route all SDK requests through a specified proxy server by configuring the `proxy` method on the client builder. This is essential for network environments that require proxy usage. ```java import com.telnyx.sdk.client.TelnyxClient; import com.telnyx.sdk.client.okhttp.TelnyxOkHttpClient; import java.net.InetSocketAddress; import java.net.Proxy; TelnyxClient client = TelnyxOkHttpClient.builder() .fromEnv() .proxy(new Proxy( Proxy.Type.HTTP, new InetSocketAddress( "https://example.com", 8080 ) )) .build(); ``` -------------------------------- ### Create AI Chat Completions Source: https://context7.com/team-telnyx/telnyx-java/llms.txt Utilizes OpenAI-compatible models hosted by Telnyx for generating chat completions. Requires specifying the model, messages, and optional parameters like max tokens and temperature. ```java import com.telnyx.sdk.models.ai.chat.*; ChatCreateCompletionResponse completion = client.ai().chat().createCompletion( ChatCreateCompletionParams.builder() .model("openai/gpt-4") .addMessage(ChatCreateCompletionParams.Message.ofSystem( ChatCreateCompletionParams.Message.SystemMessage.builder() .content("You are a helpful customer support agent.") .build())) .addMessage(ChatCreateCompletionParams.Message.ofUser( ChatCreateCompletionParams.Message.UserMessage.builder() .content("What are your business hours?") .build())) .maxTokens(200L) .temperature(0.7) .build() ); completion.choices().forEach(choice -> System.out.println(choice.message().content()) ); ``` -------------------------------- ### Initialize Asynchronous TelnyxClient Source: https://context7.com/team-telnyx/telnyx-java/llms.txt Create an asynchronous TelnyxClient instance, which returns CompletableFuture for API calls. This client can share the connection pool with a synchronous client. ```java import com.telnyx.sdk.client.TelnyxClientAsync; import com.telnyx.sdk.client.okhttp.TelnyxOkHttpClientAsync; // Create a dedicated async client (shares connection pool with a sync client via client.async()) TelnyxClientAsync asyncClient = TelnyxOkHttpClientAsync.fromEnv(); ``` -------------------------------- ### Asynchronous Client Source: https://context7.com/team-telnyx/telnyx-java/llms.txt Shows how to create and use an asynchronous TelnyxClient for non-blocking API calls, returning `CompletableFuture` objects. ```APIDOC ## Asynchronous Client — `TelnyxOkHttpClientAsync` Switch to async execution either per-request or by creating a dedicated async client that returns `CompletableFuture`. ```java import com.telnyx.sdk.client.TelnyxClientAsync; import com.telnyx.sdk.client.okhttp.TelnyxOkHttpClientAsync; import com.telnyx.sdk.models.calls.CallDialParams; import com.telnyx.sdk.models.calls.CallDialResponse; import java.util.concurrent.CompletableFuture; // Create a dedicated async client (shares connection pool with a sync client via client.async()) TelnyxClientAsync asyncClient = TelnyxOkHttpClientAsync.fromEnv(); CallDialParams params = CallDialParams.builder() .connectionId("conn12345") .from("+15557654321") .to("+15551234567") .webhookUrl("https://your-app.example.com/webhooks") .build(); CompletableFuture future = asyncClient.calls().dial(params); future .thenAccept(response -> System.out.println("Call leg: " + response.callLegId())) .exceptionally(err -> { System.err.println("Error: " + err.getMessage()); return null; }); // Or derive from a sync client (shares pool): TelnyxClientAsync derived = syncClient.async(); ``` ``` -------------------------------- ### Create and Chat with AI Assistant Source: https://context7.com/team-telnyx/telnyx-java/llms.txt Create persistent AI assistant specifications and interact with them for voice or chat workflows. Requires specifying name, model, and instructions for creation, and user messages for chat. ```java import com.telnyx.sdk.models.ai.assistants.*; // Create an assistant Assistant assistant = client.ai().assistants().create( AssistantCreateParams.builder() .name("Support Bot") .model("openai/gpt-4") .instructions("You are a helpful support agent. Be concise.") .build() ); System.out.println("Assistant ID: " + assistant.id()); // Chat with the assistant AssistantChatResponse chat = client.ai().assistants().chat( assistant.id().get(), AssistantChatParams.builder() .addMessage(AssistantChatParams.Message.builder() .role("user") .content("How do I reset my password?") .build()) .build() ); System.out.println("Reply: " + chat.choices().get(0).message().content()); ``` -------------------------------- ### Manual Pagination with Synchronous Client Source: https://github.com/team-telnyx/telnyx-java/blob/master/README.md Manually paginate through results using `items()`, `hasNextPage()`, and `nextPage()` methods. This allows for explicit control over page fetching. ```java import com.telnyx.sdk.models.accessipaddress.AccessIpAddressListPage; import com.telnyx.sdk.models.accessipaddress.AccessIpAddressResponse; AccessIpAddressListPage page = client.accessIpAddress().list(); while (true) { for (AccessIpAddressResponse accessIpAddress : page.items()) { System.out.println(accessIpAddress); } if (!page.hasNextPage()) { break; } page = page.nextPage(); } ``` -------------------------------- ### Retrieve Available AI Models Source: https://context7.com/team-telnyx/telnyx-java/llms.txt Fetches a list of all available AI models, including open-source and OpenAI-compatible ones. Model IDs follow a '{source}/{model_name}' convention. ```java import com.telnyx.sdk.models.ai.AiRetrieveModelsResponse; AiRetrieveModelsResponse models = client.ai().retrieveModels(); models.data().forEach(m -> System.out.printf("%-40s owned_by=%s%n", m.id(), m.ownedBy().orElse("-")) ); // Example output: // openai/gpt-4 owned_by=openai // mistralai/Mistral-7B-Instruct-v0.1 owned_by=mistralai ``` -------------------------------- ### Configure Connection Pooling for Telnyx Client Source: https://github.com/team-telnyx/telnyx-java/blob/master/README.md Customize the underlying OkHttp connection pool settings by configuring `maxIdleConnections` and `keepAliveDuration`. Note that if `maxIdleConnections` is set, `keepAliveDuration` must also be set, and vice versa. ```java import com.telnyx.sdk.client.TelnyxClient; import com.telnyx.sdk.client.okhttp.TelnyxOkHttpClient; import java.time.Duration; TelnyxClient client = TelnyxOkHttpClient.builder() .fromEnv() // If `maxIdleConnections` is set, then `keepAliveDuration` must be set, and vice versa. .maxIdleConnections(10) .keepAliveDuration(Duration.ofMinutes(2)) .build(); ``` -------------------------------- ### AI Models List Source: https://context7.com/team-telnyx/telnyx-java/llms.txt Retrieve a list of all available AI models, including open-source and OpenAI models. ```APIDOC ## AI Models List — `client.ai().retrieveModels()` Retrieve all available open-source and OpenAI models. Model IDs follow `{source}/{model_name}` convention. ```java import com.telnyx.sdk.models.ai.AiRetrieveModelsResponse; AiRetrieveModelsResponse models = client.ai().retrieveModels(); models.data().forEach(m -> System.out.printf("%-40s owned_by=%s%n", m.id(), m.ownedBy().orElse("-")) ); // Example output: // openai/gpt-4 owned_by=openai // mistralai/Mistral-7B-Instruct-v0.1 owned_by=mistralai ``` ``` -------------------------------- ### Add Telnyx Java SDK to Gradle Source: https://context7.com/team-telnyx/telnyx-java/llms.txt Include the all-in-one Telnyx Java SDK artifact in your project's build.gradle.kts file. ```kotlin implementation("com.telnyx.sdk:telnyx:6.47.0") ``` -------------------------------- ### Setting Undocumented Parameters Source: https://github.com/team-telnyx/telnyx-java/blob/master/README.md Demonstrates how to add undocumented headers, query parameters, and body properties to API requests using the `putAdditionalHeader`, `putAdditionalQueryParam`, and `putAdditionalBodyProperty` methods. ```APIDOC ## Setting Undocumented Parameters To set undocumented parameters, call the `putAdditionalHeader`, `putAdditionalQueryParam`, or `putAdditionalBodyProperty` methods on any `Params` class: ```java import com.telnyx.sdk.core.JsonValue; import com.telnyx.sdk.models.calls.CallDialParams; CallDialParams params = CallDialParams.builder() .putAdditionalHeader("Secret-Header", "42") .putAdditionalQueryParam("secret_query_param", "42") .putAdditionalBodyProperty("secretProperty", JsonValue.from("42")) .build(); ``` These can be accessed on the built object later using the `_additionalHeaders()`, `_additionalQueryParams()`, and `_additionalBodyProperties()` methods. ``` -------------------------------- ### AI Assistants Source: https://context7.com/team-telnyx/telnyx-java/llms.txt Create, configure, and chat with persistent AI assistant specifications for voice or chat workflows using `client.ai().assistants()`. ```APIDOC ## AI Assistants — `client.ai().assistants()` Create, configure, and chat with persistent AI assistant specifications used for voice or chat workflows. ```java import com.telnyx.sdk.models.ai.assistants.*; // Create an assistant Assistant assistant = client.ai().assistants().create( AssistantCreateParams.builder() .name("Support Bot") .model("openai/gpt-4") .instructions("You are a helpful support agent. Be concise.") .build() ); System.out.println("Assistant ID: " + assistant.id()); // Chat with the assistant AssistantChatResponse chat = client.ai().assistants().chat( assistant.id().get(), AssistantChatParams.builder() .addMessage(AssistantChatParams.Message.builder() .role("user") .content("How do I reset my password?") .build()) .build() ); System.out.println("Reply: " + chat.choices().get(0).message().content()); ``` ``` -------------------------------- ### Dialing a Phone Number with `client.calls().dial()` Source: https://context7.com/team-telnyx/telnyx-java/llms.txt Initiate a call to a phone number or SIP URI from a Call Control App connection. This method fires various call-related webhooks and requires specific parameters like connection ID, caller ID, and destination. ```java import com.telnyx.sdk.models.calls.CallDialParams; import com.telnyx.sdk.models.calls.CallDialResponse; CallDialParams params = CallDialParams.builder() .connectionId("conn12345") // Call Control App ID .from("+15557654321") // caller ID (E.164) .to("+15551234567") // destination (E.164 or SIP) .webhookUrl("https://your-app.example.com/webhooks") .timeoutSecs(30L) .answeringMachineDetection(CallDialParams.AnsweringMachineDetectionEnum.PREMIUM) .record(CallDialParams.Record.RECORD_FROM_ANSWER) .build(); try { CallDialResponse response = client.calls().dial(params); System.out.println("Call leg ID: " + response.callLegId()); System.out.println("Call control ID: " + response.callControlId()); } catch (com.telnyx.sdk.errors.UnauthorizedException e) { System.err.println("Invalid API key"); } catch (com.telnyx.sdk.errors.TelnyxServiceException e) { System.err.printf("API error %d: %s%n", e.statusCode(), e.getMessage()); } ``` -------------------------------- ### Upload Audio File via Byte Array Source: https://github.com/team-telnyx/telnyx-java/blob/master/README.md Transcribe an audio file by providing its content as a `byte[]` array. The filename will not be included in the request. ```java import com.telnyx.sdk.models.ai.audio.AudioTranscribeParams; import com.telnyx.sdk.models.ai.audio.AudioTranscribeResponse; AudioTranscribeParams params = AudioTranscribeParams.builder() .model(AudioTranscribeParams.Model.DISTIL_WHISPER_DISTIL_LARGE_V2) .file("content".getBytes()) .build(); AudioTranscribeResponse response = client.ai().audio().transcribe(params); ``` -------------------------------- ### Pagination Source: https://context7.com/team-telnyx/telnyx-java/llms.txt Iterate all pages automatically using `autoPager()`, or step through pages manually. ```APIDOC ## Pagination — `autoPager()` and Manual Paging ### Description Iterate all pages automatically using `autoPager()`, or step through pages manually. ### Auto-Pagination (Synchronous Stream) ```java AccessIpAddressListPage firstPage = client.accessIpAddress().list(); // Stream style firstPage.autoPager() .stream() .limit(100) .forEach(addr -> System.out.println(addr.ipAddress())); // Iterable style for (AccessIpAddressResponse addr : firstPage.autoPager()) { System.out.println(addr.ipAddress()); } ``` ### Manual Paging ```java AccessIpAddressListPage page = client.accessIpAddress().list(); while (true) { for (AccessIpAddressResponse addr : page.items()) { System.out.println(addr.ipAddress()); } if (!page.hasNextPage()) break; page = page.nextPage(); } ``` ``` -------------------------------- ### Raw HTTP Responses with `withRawResponse()` Source: https://context7.com/team-telnyx/telnyx-java/llms.txt Shows how to use `withRawResponse()` to access raw HTTP status codes and response headers in addition to the deserialized response body, useful for detailed inspection and debugging. ```APIDOC ## Raw HTTP Responses — `withRawResponse()` Access HTTP status codes and response headers alongside deserialized bodies. ```java import com.telnyx.sdk.core.http.Headers; import com.telnyx.sdk.core.http.HttpResponseFor; import com.telnyx.sdk.models.numberorders.NumberOrderCreateParams; import com.telnyx.sdk.models.numberorders.NumberOrderCreateResponse; HttpResponseFor raw = client .numberOrders() .withRawResponse() .create( NumberOrderCreateParams.builder() .addPhoneNumber(NumberOrderCreateParams.PhoneNumber.builder() .phoneNumber("+15558675309") .build()) .build() ); int status = raw.statusCode(); // e.g. 200 Headers headers = raw.headers(); // all response headers NumberOrderCreateResponse body = raw.parse(); System.out.printf("Status %d — Order %s%n", status, body.id()); ``` ``` -------------------------------- ### Create Primitive and Complex JsonValue Objects in Java Source: https://github.com/team-telnyx/telnyx-java/blob/master/README.md Demonstrates creating various `JsonValue` objects, including null, boolean, number, string, arrays, objects, and arbitrarily nested structures using the `JsonValue.from(...)` method. ```java import com.telnyx.sdk.core.JsonValue; import java.util.List; import java.util.Map; // Create primitive JSON values JsonValue nullValue = JsonValue.from(null); JsonValue booleanValue = JsonValue.from(true); JsonValue numberValue = JsonValue.from(42); JsonValue stringValue = JsonValue.from("Hello World!"); // Create a JSON array value equivalent to `["Hello", "World"]` JsonValue arrayValue = JsonValue.from(List.of( "Hello", "World" )); // Create a JSON object value equivalent to `{ "a": 1, "b": 2 }` JsonValue objectValue = JsonValue.from(Map.of( "a", 1, "b", 2 )); // Create an arbitrarily nested JSON equivalent to: // { // "a": [1, 2], // "b": [3, 4] // } JsonValue complexValue = JsonValue.from(Map.of( "a", List.of( 1, 2 ), "b", List.of( 3, 4 ) )); ``` -------------------------------- ### Auto-pagination with Synchronous Client Source: https://github.com/team-telnyx/telnyx-java/blob/master/README.md Use `autoPager()` to iterate through all results across pages with the synchronous client. It returns an `Iterable`. ```java import com.telnyx.sdk.models.accessipaddress.AccessIpAddressListPage; import com.telnyx.sdk.models.accessipaddress.AccessIpAddressResponse; AccessIpAddressListPage page = client.accessIpAddress().list(); // Process as an Iterable for (AccessIpAddressResponse accessIpAddress : page.autoPager()) { System.out.println(accessIpAddress); } // Process as a Stream page.autoPager() .stream() .limit(50) .forEach(accessIpAddress -> System.out.println(accessIpAddress)); ``` -------------------------------- ### Per-Request Options Source: https://context7.com/team-telnyx/telnyx-java/llms.txt Illustrates how to override client-wide settings like timeout and response validation for individual API requests using `RequestOptions`. ```APIDOC ## Per-Request Options — `RequestOptions` Override timeout or response validation for a specific call without changing the global client. ```java import com.telnyx.sdk.core.RequestOptions; import com.telnyx.sdk.models.numberorders.NumberOrderCreateParams; import com.telnyx.sdk.models.numberorders.NumberOrderCreateResponse; import java.time.Duration; RequestOptions opts = RequestOptions.builder() .timeout(Duration.ofSeconds(10)) .responseValidation(true) .build(); NumberOrderCreateResponse order = client.numberOrders().create( NumberOrderCreateParams.builder() .addPhoneNumber(NumberOrderCreateParams.PhoneNumber.builder() .phoneNumber("+15558675309") .build()) .build(), opts ); System.out.println("Order ID: " + order.id()); ``` ``` -------------------------------- ### AI Summary Source: https://context7.com/team-telnyx/telnyx-java/llms.txt Summarize PDF, HTML, text, JSON, CSV, or audio/video files up to 100 MB using the `client.ai().summarize()` method. ```APIDOC ## AI Summary — `client.ai().summarize()` Summarize a PDF, HTML, text, JSON, CSV, or audio/video file (up to 100 MB). ```java import com.telnyx.sdk.models.ai.AiSummarizeParams; import com.telnyx.sdk.models.ai.AiSummarizeResponse; import java.nio.file.Paths; AiSummarizeResponse summary = client.ai().summarize( AiSummarizeParams.builder() .file(Paths.get("/documents/quarterly-report.pdf")) .build() ); System.out.println("Summary: " + summary.summary()); ``` ``` -------------------------------- ### Configure HTTPS Security Settings for Telnyx Client Source: https://github.com/team-telnyx/telnyx-java/blob/master/README.md Configure how HTTPS connections are secured by providing custom `sslSocketFactory`, `trustManager`, and `hostnameVerifier`. It is recommended to use system defaults unless specific security requirements necessitate custom configurations. ```java import com.telnyx.sdk.client.TelnyxClient; import com.telnyx.sdk.client.okhttp.TelnyxOkHttpClient; TelnyxClient client = TelnyxOkHttpClient.builder() .fromEnv() // If `sslSocketFactory` is set, then `trustManager` must be set, and vice versa. .sslSocketFactory(yourSSLSocketFactory) .trustManager(yourTrustManager) .hostnameVerifier(yourHostnameVerifier) .build(); ``` -------------------------------- ### Add Telnyx Java SDK to Maven Source: https://context7.com/team-telnyx/telnyx-java/llms.txt Add the all-in-one Telnyx Java SDK artifact to your project's pom.xml file. ```xml com.telnyx.sdk telnyx 6.47.0 ``` -------------------------------- ### Upload Audio File with Filename using MultipartField Source: https://github.com/team-telnyx/telnyx-java/blob/master/README.md Upload an audio file using `MultipartField` to specify both the `InputStream` value and a custom filename. This is useful when the filename is not inferable from the source. ```java import com.telnyx.sdk.core.MultipartField; import com.telnyx.sdk.models.ai.audio.AudioTranscribeParams; import com.telnyx.sdk.models.ai.audio.AudioTranscribeResponse; import java.io.InputStream; import java.net.URL; AudioTranscribeParams params = AudioTranscribeParams.builder() .model(AudioTranscribeParams.Model.DISTIL_WHISPER_DISTIL_LARGE_V2) .file(MultipartField.builder() .value(new URL("https://example.com//path/to/file").openStream()) .filename("/path/to/file") .build()) .build(); AudioTranscribeResponse response = client.ai().audio().transcribe(params); ``` -------------------------------- ### Summarize Document with AI Source: https://context7.com/team-telnyx/telnyx-java/llms.txt Summarize a PDF, HTML, text, JSON, CSV, or audio/video file up to 100 MB. Requires specifying the file path. ```java import com.telnyx.sdk.models.ai.AiSummarizeParams; import com.telnyx.sdk.models.ai.AiSummarizeResponse; import java.nio.file.Paths; AiSummarizeResponse summary = client.ai().summarize( AiSummarizeParams.builder() .file(Paths.get("/documents/quarterly-report.pdf")) .build() ); System.out.println("Summary: " + summary.summary()); ``` -------------------------------- ### Send and Manage Messages Source: https://context7.com/team-telnyx/telnyx-java/llms.txt Shows how to send SMS/MMS messages, including those with media, retrieve message status, schedule messages for future delivery, and cancel scheduled messages. ```java import com.telnyx.sdk.models.messages.*; // Generic send (SMS/MMS) MessageSendResponse sent = client.messages().send( MessageSendParams.builder() .from("+15552345678") .to("+15559876543") .text("Hello from Telnyx!") .build() ); System.out.println("Message ID: " + sent.id()); // Long-code send with media MessageSendLongCodeResponse mms = client.messages().sendLongCode( MessageSendLongCodeParams.builder() .from("+15552345678") .to("+15559876543") .text("Check out this image!") .addMediaUrl("https://example.com/photo.jpg") .build() ); // Retrieve message (available up to 10 days) MessageRetrieveResponse msg = client.messages().retrieve(sent.id().get()); System.out.println("Status: " + msg.to().get(0).status()); // Schedule a message for later delivery MessageScheduleResponse scheduled = client.messages().schedule( MessageScheduleParams.builder() .from("+15552345678") .to("+15559876543") .text("Reminder: your appointment is tomorrow.") .sendAt("2025-12-01T09:00:00Z") .build() ); // Cancel a scheduled message client.messages().cancelScheduled(scheduled.id().get()); ``` -------------------------------- ### AI Chat Completions Source: https://context7.com/team-telnyx/telnyx-java/llms.txt Generate chat completions using OpenAI-compatible models hosted by Telnyx. ```APIDOC ## AI Chat Completions — `client.ai().chat().createCompletion()` OpenAI-compatible chat completions using Telnyx-hosted open-source or OpenAI models. ```java import com.telnyx.sdk.models.ai.chat.*; ChatCreateCompletionResponse completion = client.ai().chat().createCompletion( ChatCreateCompletionParams.builder() .model("openai/gpt-4") .addMessage(ChatCreateCompletionParams.Message.ofSystem( ChatCreateCompletionParams.Message.SystemMessage.builder() .content("You are a helpful customer support agent.") .build())) .addMessage(ChatCreateCompletionParams.Message.ofUser( ChatCreateCompletionParams.Message.UserMessage.builder() .content("What are your business hours?") .build())) .maxTokens(200L) .temperature(0.7) .build() ); completion.choices().forEach(choice -> System.out.println(choice.message().content()) ); ``` ``` -------------------------------- ### Error Handling Source: https://context7.com/team-telnyx/telnyx-java/llms.txt The SDK throws typed unchecked exceptions for every HTTP error class. ```APIDOC ## Error Handling ### Description The SDK throws typed unchecked exceptions for every HTTP error class. ### Exception Types - `BadRequestException` (400) - `UnauthorizedException` (401) - `PermissionDeniedException` (403) - `NotFoundException` (404) - `RateLimitException` (429) - `InternalServerException` (5xx) - `TelnyxIoException` (Network errors) - `TelnyxInvalidDataException` (Unexpected response shape) ### Example Usage ```java try { client.calls().dial(params); } catch (BadRequestException e) { System.err.println("400 Bad Request: " + e.getMessage()); } catch (UnauthorizedException e) { System.err.println("401 Unauthorized – check your API key"); } catch (PermissionDeniedException e) { System.err.println("403 Forbidden"); } catch (NotFoundException e) { System.err.println("404 Not Found: " + e.getMessage()); } catch (RateLimitException e) { System.err.println("429 Rate Limited – back off and retry"); } catch (InternalServerException e) { System.err.println("5xx Server Error: " + e.statusCode()); } catch (TelnyxIoException e) { System.err.println("Network error: " + e.getMessage()); } catch (TelnyxInvalidDataException e) { System.err.println("Unexpected response shape: " + e.getMessage()); } ``` ```