### Describe VPCs using BytePlus Java SDK Source: https://github.com/byteplus-sdk/byteplus-java-sdk-v2/blob/main/README.md Example demonstrating how to use the VpcApi to describe VPCs by their IDs. Ensure you have configured credentials and the ApiClient. ```java import com.byteplus.ApiClient; import com.byteplus.ApiException; import com.byteplus.sign.Credentials; import com.byteplus.vpc.VpcApi; import com.byteplus.vpc.model.DescribeVpcsRequest; import com.byteplus.vpc.model.DescribeVpcsResponse; import java.util.ArrayList; import java.util.List; public class TestVpc { public static void main(String[] args) throws Exception { String ak = "your ak"; String sk = "your sk"; String region = "ap-southeast-1"; ApiClient apiClient = new ApiClient() .setCredentials(Credentials.getCredentials(ak, sk)) .setRegion(region); VpcApi vpcApi = new VpcApi(apiClient); DescribeVpcsRequest request = new DescribeVpcsRequest(); List list = new ArrayList<>(); list.add("vpc-13fpdgwk7rxfk3n6nu44wisg7"); request.setVpcIds(list); try { DescribeVpcsResponse response = vpcApi.describeVpcs(request); System.out.println(response); } catch (ApiException e) { System.out.println(e.getResponseBody()); } } } ``` -------------------------------- ### Manage ECS Resources with EcsApi Source: https://context7.com/byteplus-sdk/byteplus-java-sdk-v2/llms.txt This example demonstrates how to initialize the EcsApi client and perform common operations like creating a key pair, describing available resources, and listing instances. It includes error handling for network issues and server-side errors. ```java import com.byteplus.ApiClient; import com.byteplus.ApiException; import com.byteplus.sign.Credentials; import com.byteplus.ecs.EcsApi; import com.byteplus.ecs.model.*; import com.byteplus.model.Error; import org.apache.commons.lang.StringUtils; import java.net.*; public class EcsExample { public static void main(String[] args) { ApiClient client = new ApiClient() .setCredentials(Credentials.getEnvCredentials()) .setRegion("ap-southeast-1") .setAutoRetry(true) .setNumMaxRetries(3); EcsApi ecsApi = new EcsApi(client); // --- Create a Key Pair --- CreateKeyPairRequest kpReq = new CreateKeyPairRequest(); kpReq.setKeyPairName("my-ssh-key"); try { CreateKeyPairResponse kpResp = ecsApi.createKeyPair(kpReq); System.out.println("Key pair created: " + kpResp); } catch (ApiException e) { Throwable cause = e.getCause(); if (cause instanceof SocketTimeoutException || cause instanceof UnknownHostException) { System.err.println("Network/timeout error: " + cause.getMessage()); } else if (e.getResponseMetadata() != null && e.getResponseMetadata().getError() != null) { Error err = e.getResponseMetadata().getError(); System.err.printf("Server error [%s]: %s (requestId=%s)%n", err.getCode(), err.getMessage(), e.getResponseMetadata().getRequestId()); } else if (e.getCode() == 0 && !StringUtils.isEmpty(e.getMessage())) { System.err.println("Client error: " + e.getMessage()); } } // --- Describe available resources --- try { DescribeAvailableResourceRequest resReq = new DescribeAvailableResourceRequest(); DescribeAvailableResourceResponse resResp = ecsApi.describeAvailableResource(resReq); System.out.println("Available resources: " + resResp); } catch (ApiException e) { System.err.println("Describe resources failed: " + e.getResponseBody()); } // --- Describe Instances --- try { DescribeInstancesRequest instReq = new DescribeInstancesRequest(); instReq.setMaxResults(20); DescribeInstancesResponse instResp = ecsApi.describeInstances(instReq); System.out.println("Instances: " + instResp); } catch (ApiException e) { System.err.println("Describe instances failed: " + e.getResponseBody()); } } } ``` -------------------------------- ### Manage VPC Resources with VpcApi Source: https://context7.com/byteplus-sdk/byteplus-java-sdk-v2/llms.txt This example demonstrates creating a VPC, describing VPCs by ID, creating a subnet, creating a security group, and allocating an Elastic IP address using the VpcApi. Ensure you have set up your API client with credentials and region. ```java import com.byteplus.ApiClient; import com.byteplus.ApiException; import com.byteplus.sign.Credentials; import com.byteplus.vpc.VpcApi; import com.byteplus.vpc.model.*; import java.util.Arrays; public class VpcExample { public static void main(String[] args) { ApiClient client = new ApiClient() .setCredentials(Credentials.getEnvCredentials()) .setRegion("ap-southeast-1"); VpcApi vpcApi = new VpcApi(client); // --- Create a VPC --- try { CreateVpcRequest createReq = new CreateVpcRequest(); createReq.setVpcName("my-vpc"); createReq.setCidrBlock("10.0.0.0/16"); createReq.setDescription("Production VPC"); CreateVpcResponse createResp = vpcApi.createVpc(createReq); System.out.println("Created VPC: " + createResp); } catch (ApiException e) { System.err.println("Create VPC failed: " + e.getResponseBody()); } // --- Describe VPCs by ID --- try { DescribeVpcsRequest descReq = new DescribeVpcsRequest(); descReq.setVpcIds(Arrays.asList("vpc-13fpdgwk7rxfk3n6nu44wisg7")); DescribeVpcsResponse descResp = vpcApi.describeVpcs(descReq); System.out.println("VPCs: " + descResp); } catch (ApiException e) { System.err.println("Describe VPCs failed: " + e.getResponseBody()); } // --- Create a Subnet --- try { CreateSubnetRequest subnetReq = new CreateSubnetRequest(); subnetReq.setVpcId("vpc-13fpdgwk7rxfk3n6nu44wisg7"); subnetReq.setSubnetName("my-subnet"); subnetReq.setCidrBlock("10.0.1.0/24"); CreateSubnetResponse subnetResp = vpcApi.createSubnet(subnetReq); System.out.println("Subnet: " + subnetResp); } catch (ApiException e) { System.err.println("Create Subnet failed: " + e.getResponseBody()); } // --- Create a Security Group --- try { CreateSecurityGroupRequest sgReq = new CreateSecurityGroupRequest(); sgReq.setVpcId("vpc-13fpdgwk7rxfk3n6nu44wisg7"); sgReq.setSecurityGroupName("web-sg"); CreateSecurityGroupResponse sgResp = vpcApi.createSecurityGroup(sgReq); System.out.println("Security Group: " + sgResp); } catch (ApiException e) { System.err.println("Create Security Group failed: " + e.getResponseBody()); } // --- Allocate an Elastic IP --- try { AllocateEipAddressRequest eipReq = new AllocateEipAddressRequest(); AllocateEipAddressResponse eipResp = vpcApi.allocateEipAddress(eipReq); System.out.println("EIP: " + eipResp); } catch (ApiException e) { System.err.println("Allocate EIP failed: " + e.getResponseBody()); } } } ``` -------------------------------- ### Install BytePlus Java SDK v2 with Maven BOM Source: https://context7.com/byteplus-sdk/byteplus-java-sdk-v2/llms.txt Import the Maven Bill of Materials (BOM) to manage all module versions centrally. Then, declare only the service modules you need without specifying versions. ```xml com.byteplus byteplus-java-sdk-v2-bom 0.1.58 pom import com.byteplus byteplus-java-sdk-v2-vpc com.byteplus byteplus-java-sdk-v2-ecs com.byteplus byteplus-java-sdk-v2-ark-runtime javax.annotation javax.annotation-api 1.3.2 ``` -------------------------------- ### Get Credentials using `Credentials` Helper Source: https://context7.com/byteplus-sdk/byteplus-java-sdk-v2/llms.txt Use `Credentials.getCredentials` for hardcoded or STS tokens, and `Credentials.getEnvCredentials` to read from environment variables. The latter is recommended for production. ```java import com.byteplus.ApiClient; import com.byteplus.sign.Credentials; // Option 1: hardcoded (dev/testing only) Credentials staticCred = Credentials.getCredentials("YOUR_AK", "YOUR_SK"); // Option 2: STS temporary credentials Credentials stsCred = Credentials.getCredentials("STS_AK", "STS_SK", "STS_SESSION_TOKEN"); // Option 3: read from environment (recommended for production) // export BYTEPLUS_ACCESS_KEY=... // export BYTEPLUS_SECRET_KEY=... Credentials envCred = Credentials.getEnvCredentials(); ApiClient client = new ApiClient() .setCredentials(envCred) .setRegion("ap-southeast-1"); ``` -------------------------------- ### Handle API Errors in Java Source: https://github.com/byteplus-sdk/byteplus-java-sdk-v2/blob/main/docs/6-ErrorHandling.md This example demonstrates how to catch and differentiate between various API exceptions, including client errors, network/timeout errors, server errors, and other general exceptions. It checks the exception cause and response metadata to provide specific error messages. ```java import com.byteplus.ApiClient; import com.byteplus.ApiException; import com.byteplus.ecs.EcsApi; import com.byteplus.ecs.model.CreateKeyPairRequest; import com.byteplus.ecs.model.CreateKeyPairResponse; import com.byteplus.sign.Credentials; import java.net.SocketException; import java.net.SocketTimeoutException; import java.net.UnknownHostException; import java.net.UnknownServiceException; import com.byteplus.model.Error; import org.apache.commons.lang.StringUtils; public class SampleCode { public static void main(String[] args) { String region = "ap-singapore-1"; ApiClient apiClient = null; try { apiClient = new ApiClient() .setCredentials(Credentials.getEnvCredentials()) .setRegion(region) ; }catch (Exception e) { System.out.println("1. Client error: " + e.getMessage()); } EcsApi api = new EcsApi(apiClient); CreateKeyPairRequest createKeyPairRequest = new CreateKeyPairRequest(); createKeyPairRequest.setKeyPairName("ssh_key_pair"); try { CreateKeyPairResponse response = api.createKeyPair(createKeyPairRequest); System.out.println(response); } catch (ApiException e) { Throwable cause = e.getCause(); if(cause == null){ if (e.getCode() == 0 && !StringUtils.isEmpty(e.getMessage())) { System.out.println("1. Client error: " + e.getMessage()); } }else { if (cause instanceof SocketTimeoutException || cause instanceof UnknownHostException || cause instanceof UnknownServiceException || cause instanceof SocketException ) { System.out.println("2. Network/timeout error: " + cause.getMessage()); }else { System.out.println("4. Other error: " + cause.getMessage()); } } if (e.getResponseMetadata() != null && e.getResponseMetadata().getError()!= null) { Error error = e.getResponseMetadata().getError(); System.out.println("3. Server error: code: " + error.getCode() + ", message: " + error.getMessage() + ", requestId: " + e.getResponseMetadata().getRequestId()); } } catch (Exception e){ System.out.println("4. Other error: " + e.getMessage()); } } } ``` -------------------------------- ### OIDC Credential Provider Example Source: https://github.com/byteplus-sdk/byteplus-java-sdk-v2/blob/main/docs/1-Credentials.md Configure OidcCredentialProvider to obtain temporary credentials via OIDC token. Set optional parameters like duration, retry settings, and STS endpoint. ```java import com.byteplus.ApiClient; import com.byteplus.auth.CredentialProvider; import com.byteplus.auth.OidcCredentialProvider; public class SampleCode { public static void main(String[] args) { String region = "ap-singapore-1"; OidcCredentialProvider oidcProvider = new OidcCredentialProvider( "trn:iam::1234567890:role/oidc-role", // roleTrn null, // roleSessionName (optional) "/var/run/secrets/oidc/token", // oidcTokenFile null, // rolePolicy (optional) "sts.byteplusapi.com" // stsEndpoint (optional) ); // Optional setters oidcProvider.setDurationSeconds(3600); // Credential TTL in seconds, default: 3600 oidcProvider.setExpireBufferSeconds(60); // Expire buffer in seconds, default: 300 oidcProvider.setSchema("https"); // STS scheme, default: https oidcProvider.setMaxRetries(3); // Retry attempts, default: 3, 0 disables retry oidcProvider.setRetryIntervalMs(1000); // Retry interval in ms, default: 1000 CredentialProvider credentialProvider = new CredentialProvider(oidcProvider); ApiClient apiClient = new ApiClient() .setCredentialProvider(credentialProvider) .setRegion(region); } } ``` -------------------------------- ### Initialize BytePlus Java SDK with AK/SK Source: https://github.com/byteplus-sdk/byteplus-java-sdk-v2/blob/main/docs/1-Credentials.md Demonstrates initializing the BytePlus Java SDK with static Access Key (AK) and Secret Key (SK). For production, it's recommended to read credentials from environment variables. ```java import com.byteplus.ApiClient; import com.byteplus.sign.Credentials; public class SampleCode { public static void main(String[] args) { String ak = "Your AK"; String sk = "Your SK"; String region = "ap-singapore-1"; // 1. Using static AK/SK may leak credentials; do not use in production. Credentials akSkCredential = Credentials.getCredentials(ak, sk); // 2. Recommended in production: read from env vars: BYTEPLUS_ACCESS_KEY / BYTEPLUS_SECRET_KEY // Credentials akSkCredential = Credentials.getEnvCredentials(); ApiClient apiClient = new ApiClient() .setCredentials(akSkCredential) .setRegion(region); } } ``` -------------------------------- ### Configure Credentials via Environment Variables Source: https://github.com/byteplus-sdk/byteplus-java-sdk-v2/blob/main/README.md Set your BytePlus Access Key (AK), Secret Key (SK), and optionally Session Token as environment variables. ```bash export BYTEPLUS_ACCESS_KEY=your ak export BYTEPLUS_SECRET_KEY=your sk # If using token export BYTEPLUS_SESSION_TOKEN=token ``` -------------------------------- ### Initialize CLIConfigCredentialProvider Source: https://context7.com/byteplus-sdk/byteplus-java-sdk-v2/llms.txt Use `CLIConfigCredentialProvider` to load credentials from `~/.byteplus/config.json`, supporting multiple profiles and various credential modes. The config file path and profile name can be specified in the constructor. ```java import com.byteplus.ApiClient; import com.byteplus.auth.CLIConfigCredentialProvider; import com.byteplus.auth.CredentialProvider; import java.nio.file.Paths; // Use named profile "prod" from default config path CLIConfigCredentialProvider cliProvider = new CLIConfigCredentialProvider( "prod", // profile name Paths.get(System.getProperty("user.home"), ".byteplus", "config.json").toString() ); // Config file path priority: constructor arg > BYTEPLUS_CLI_CONFIG_FILE > ~/.byteplus/config.json // Profile priority: constructor arg > BYTEPLUS_PROFILE > "current" in config > "default" ApiClient client = new ApiClient() .setCredentialProvider(new CredentialProvider(cliProvider)) .setRegion("ap-southeast-1"); ``` -------------------------------- ### Configure Credentials in Code Source: https://github.com/byteplus-sdk/byteplus-java-sdk-v2/blob/main/README.md Instantiate Credentials object directly in your Java code using AK, SK, and optionally a session token. ```java Credentials credentials = Credentials.getCredentials(ak, sk); // If using token Credentials credentials = Credentials.getCredentials(ak, sk, token); ``` -------------------------------- ### Set Windows Environment Variables via Command Line Source: https://github.com/byteplus-sdk/byteplus-java-sdk-v2/blob/main/docs/1-Credentials.md Configure system-level environment variables for BytePlus access keys and session tokens on Windows using the `setx` command. Omit `/M` for user-level variables. ```batch setx BYTEPLUS_ACCESS_KEY yourAccessKeyID /M ``` ```batch setx BYTEPLUS_SECRET_KEY yourAccessKeySecret /M ``` ```batch setx BYTEPLUS_SESSION_TOKEN yourSessionToken /M ``` -------------------------------- ### Enable SDK Debug Logs with Logback Source: https://context7.com/byteplus-sdk/byteplus-java-sdk-v2/llms.txt Configure Logback's `logback.xml` to set the `com.byteplus.sdkcore` logger to DEBUG level. This will output full request/response details. Ensure `additivity` is set to `false` to prevent duplicate logs. ```xml %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n ``` -------------------------------- ### Generate Images with Java SDK Source: https://context7.com/byteplus-sdk/byteplus-java-sdk-v2/llms.txt Produces images from a text prompt using a deployed image generation model. Customize parameters like size, seed, and guidance scale. Replace 'YOUR_ARK_API_KEY' and 'YOUR_IMAGE_ENDPOINT_ID' with your credentials. The service client should be shut down after use. ```java import com.byteplus.ark.runtime.service.ArkService; import com.byteplus.ark.runtime.model.images.generation.*; import java.time.Duration; public class ImageGenExample { public static void main(String[] args) { ArkService service = new ArkService("YOUR_ARK_API_KEY", Duration.ofMinutes(5)); GenerateImagesRequest request = new GenerateImagesRequest(); request.setModel("YOUR_IMAGE_ENDPOINT_ID"); request.setPrompt("A serene mountain lake at sunrise, photorealistic, 4K"); request.setSize("1024x1024"); request.setResponseFormat("url"); // "url" or "b64_json" request.setSeed(42); request.setGuidanceScale(7.5); request.setWatermark(false); request.setOptimizePrompt(true); try { ImagesResponse response = service.generateImages(request); response.getData().forEach(img -> { System.out.println("Image URL: " + img.getUrl()); }); } catch (Exception e) { System.err.println("Image generation error: " + e.getMessage()); } finally { service.shutdownExecutor(); } } } ``` -------------------------------- ### Context-Aware Chat with ArkService Source: https://context7.com/byteplus-sdk/byteplus-java-sdk-v2/llms.txt Demonstrates how to use `createContext` to cache conversation history and `createContextChatCompletion` to leverage this cache for reduced latency and token costs in multi-turn conversations. ```APIDOC ## `ArkService.createContext` / `createContextChatCompletion` — Context-Aware Chat `createContext` pre-caches a conversation history prefix server-side, then `createContextChatCompletion` reuses that cached context with each subsequent user turn. This reduces latency and token cost for multi-turn conversations with long system prompts. ### Usage Example (Java) ```java import com.byteplus.ark.runtime.service.ArkService; import com.byteplus.ark.runtime.model.context.*; import com.byteplus.ark.runtime.model.context.chat.*; import com.byteplus.ark.runtime.model.completion.chat.*; import java.time.Duration; import java.util.*; public class ContextChatExample { public static void main(String[] args) { ArkService service = new ArkService("YOUR_ARK_API_KEY", Duration.ofMinutes(5)); String endpointId = "YOUR_ENDPOINT_ID"; // Step 1: create and cache context (system prompt + history) CreateContextRequest contextReq = new CreateContextRequest(); contextReq.setModel(endpointId); contextReq.setMessages(Arrays.asList( ChatMessage.builder() .role(ChatMessageRole.SYSTEM) .content("You are a senior Java developer who always responds with complete, runnable code examples.") .build() )); CreateContextResult contextResult = service.createContext(contextReq); String contextId = contextResult.getId(); System.out.println("Context cached: " + contextId); // Step 2: chat using the cached context ContextChatCompletionRequest chatReq = new ContextChatCompletionRequest(); chatReq.setContextId(contextId); chatReq.setMessages(Arrays.asList( ChatMessage.builder() .role(ChatMessageRole.USER) .content("Show me how to read a file line by line in Java.") .build() )); try { ChatCompletionResult result = service.createContextChatCompletion(chatReq); System.out.println(result.getChoices().get(0).getMessage().getContent()); } catch (Exception e) { System.err.println("Context chat error: " + e.getMessage()); } finally { service.shutdownExecutor(); } } } ``` ``` -------------------------------- ### Manage Files with ArkService in Java Source: https://context7.com/byteplus-sdk/byteplus-java-sdk-v2/llms.txt Upload files for batch inference or fine-tuning, retrieve their metadata, list all uploaded files, and delete them using the ArkService. Ensure the file path is correct and the purpose is set appropriately. ```java import com.byteplus.ark.runtime.service.ArkService; import com.byteplus.ark.runtime.model.files.*; import java.io.File; import java.time.Duration; public class FileManagementExample { public static void main(String[] args) { ArkService service = new ArkService("YOUR_ARK_API_KEY", Duration.ofMinutes(5)); // Upload a file UploadFileRequest uploadReq = new UploadFileRequest(); uploadReq.setFile(new File("/data/training_data.jsonl")); uploadReq.setPurpose("fine-tune"); FileMeta uploaded = service.uploadFile(uploadReq); System.out.println("Uploaded file ID: " + uploaded.getId()); // Retrieve file metadata FileMeta meta = service.retrieveFile(uploaded.getId()); System.out.printf("File: %s, size=%d bytes, status=%s%n", meta.getFilename(), meta.getBytes(), meta.getStatus()); // List all files ListFilesRequest listReq = new ListFilesRequest(); listReq.setPurpose("fine-tune"); ListFilesResponse files = service.listFiles(listReq); files.getData().forEach(f -> System.out.println(" " + f.getId() + " - " + f.getFilename())); // Delete a file DeleteFileResponse del = service.deleteFile(uploaded.getId()); System.out.println("Deleted: " + del.getId() + ", deleted=" + del.getDeleted()); service.shutdownExecutor(); } } ``` -------------------------------- ### Import BytePlus SDK BOM Source: https://github.com/byteplus-sdk/byteplus-java-sdk-v2/blob/main/README.md Import the Bill of Materials (BOM) to manage SDK versions when using Maven. ```xml com.byteplus byteplus-java-sdk-v2-bom 0.1.58 pom import ``` -------------------------------- ### Create VPC Source: https://context7.com/byteplus-sdk/byteplus-java-sdk-v2/llms.txt Creates a new Virtual Private Cloud (VPC) with a specified name, CIDR block, and description. ```APIDOC ## createVpc ### Description Creates a new VPC with the specified name, CIDR block, and description. ### Method POST ### Endpoint /vpc ### Parameters #### Request Body - **VpcName** (string) - Required - The name of the VPC. - **CidrBlock** (string) - Required - The CIDR block for the VPC. - **Description** (string) - Optional - A description for the VPC. ### Request Example ```json { "VpcName": "my-vpc", "CidrBlock": "10.0.0.0/16", "Description": "Production VPC" } ``` ### Response #### Success Response (200) - **VpcId** (string) - The ID of the created VPC. - **VpcName** (string) - The name of the created VPC. - **CidrBlock** (string) - The CIDR block of the created VPC. - **Description** (string) - The description of the created VPC. #### Response Example ```json { "VpcId": "vpc-xxxxxxxxxxxxxxxxx", "VpcName": "my-vpc", "CidrBlock": "10.0.0.0/16", "Description": "Production VPC" } ``` ``` -------------------------------- ### Initialize EnvironmentVariableCredentialProvider Source: https://context7.com/byteplus-sdk/byteplus-java-sdk-v2/llms.txt Use `EnvironmentVariableCredentialProvider` to read credentials from environment variables like `BYTEPLUS_ACCESS_KEY`, `BYTEPLUS_SECRET_KEY`, and `BYTEPLUS_SESSION_TOKEN`. This is suitable for containerized or CI/CD environments. ```java import com.byteplus.ApiClient; import com.byteplus.auth.CredentialProvider; import com.byteplus.auth.EnvironmentVariableCredentialProvider; // Shell: // export BYTEPLUS_ACCESS_KEY=your-ak // export BYTEPLUS_SECRET_KEY=your-sk // export BYTEPLUS_SESSION_TOKEN=your-token # optional ApiClient client = new ApiClient() .setCredentialProvider(new CredentialProvider(new EnvironmentVariableCredentialProvider())) .setRegion("ap-southeast-1"); ``` -------------------------------- ### UniversalApi.doCall - Low-Level Generic API Call Source: https://context7.com/byteplus-sdk/byteplus-java-sdk-v2/llms.txt Demonstrates how to use `UniversalApi.doCall` to make generic API requests when a specific service module is not available. The request and response bodies are weakly typed as `Map`. ```APIDOC ## `UniversalApi.doCall` — Low-Level Generic API Call `UniversalApi` provides a weakly-typed escape hatch for calling any BytePlus API without a dedicated service module. The request body and response are both `Map`. Use when a specific service module is not yet available. ### Method Signature `Map doCall(UniversalRequest req, Map params) throws ApiException` ### Parameters - `req` (UniversalRequest): An object containing details about the API request such as service name, version, action, HTTP method, and content type. - `params` (Map): A map of parameters for the API call. ### Request Example ```java import com.byteplus.ApiClient; import com.byteplus.ApiException; import com.byteplus.ContentType; import com.byteplus.HttpMethod; import com.byteplus.UniversalApi; import com.byteplus.UniversalRequest; import com.byteplus.sign.Credentials; import java.util.*; public class UniversalApiExample { public static void main(String[] args) { ApiClient client = new ApiClient() .setCredentials(Credentials.getEnvCredentials()) .setRegion("ap-southeast-1"); UniversalApi api = new UniversalApi(client); UniversalRequest req = new UniversalRequest(); req.setAction("DescribeVpcs"); req.setVersion("2020-04-01"); req.setServiceName("vpc"); req.setHttpMethod(HttpMethod.GET); req.setContentType(ContentType.JSON); Map params = new HashMap<>(); params.put("VpcIds.1", "vpc-13fpdgwk7rxfk3n6nu44wisg7"); try { Map response = api.doCall(req, params); System.out.println("Response: " + response); } catch (ApiException e) { System.err.println("API call failed: " + e.getResponseBody()); } } } ``` ``` -------------------------------- ### Enable Debug Logs in XML Configuration Source: https://github.com/byteplus-sdk/byteplus-java-sdk-v2/blob/main/docs/7-Debugging.md Configure your logging framework (e.g., Logback, Log4j) via XML to enable debug-level logs for the SDK core. This setting is useful for detailed troubleshooting. ```xml ``` -------------------------------- ### Configure HTTPS Scheme Source: https://github.com/byteplus-sdk/byteplus-java-sdk-v2/blob/main/docs/3-Transport.md Set to `false` to use HTTPS, which is the default. Set to `true` to disable SSL and use HTTP. ```java import com.byteplus.ApiClient; import com.byteplus.sign.Credentials; public class SampleCode { public static void main(String[] args) { String regionId = "ap-singapore-1"; ApiClient apiClient = new ApiClient() .setCredentials(Credentials.getEnvCredentials()) .setRegion(regionId) .setDisableSSL(false); } } ``` -------------------------------- ### Standard Endpoint Provider Configuration Source: https://context7.com/byteplus-sdk/byteplus-java-sdk-v2/llms.txt Uses `StandardEndpointProvider` for explicit IPv4/IPv6 rules, ignoring the bootstrap list. This configuration explicitly sets DualStack to false. ```java import com.byteplus.ApiClient; import com.byteplus.endpoint.StandardEndpointProvider; import com.byteplus.sign.Credentials; import java.util.HashSet; // Standard endpoint provider (explicit IPv4/IPv6 rules, ignores bootstrap list) ApiClient standard = new ApiClient() .setCredentials(Credentials.getEnvCredentials()) .setEndpointResolver(new StandardEndpointProvider()) .setRegion("ap-southeast-1") .setUseDualStack(false); // Endpoint format rules: // global + DualStack=false -> {Service}.byteplusapi.com // global + DualStack=true -> {Service}.byteplus-api.com // regional + DualStack=false -> {Service}.{region}.byteplusapi.com // regional + DualStack=true -> {Service}.{region}.byteplus-api.com ``` -------------------------------- ### Initialize SamlCredentialProvider Source: https://context7.com/byteplus-sdk/byteplus-java-sdk-v2/llms.txt Use `SamlCredentialProvider` to exchange a SAML Response for temporary credentials. Configure refresh intervals using `setDurationSeconds` and `setExpireBufferSeconds`. ```java import com.byteplus.ApiClient; import com.byteplus.auth.CredentialProvider; import com.byteplus.auth.SamlCredentialProvider; SamlCredentialProvider samlProvider = new SamlCredentialProvider( "trn:iam::123456789:role/saml-role", // roleTrn "trn:iam::123456789:saml-provider/MyIdp", // samlProviderTrn "BASE64_ENCODED_SAML_RESPONSE", // samlAssertion from IdP null, // rolePolicy (nullable) null // stsEndpoint (nullable = default) ); samlProvider.setDurationSeconds(3600); samlProvider.setExpireBufferSeconds(300); ApiClient client = new ApiClient() .setCredentialProvider(new CredentialProvider(samlProvider)) .setRegion("ap-southeast-1"); ``` -------------------------------- ### Set Environment Variables (Windows) Source: https://github.com/byteplus-sdk/byteplus-java-sdk-v2/blob/main/docs/EnvironmentVariables.md Set system-level environment variables from the command line. Omit the /M flag for user-level variables. Verify by opening a new command prompt. ```cmd setx BYTEPLUS_ACCESS_KEY your-ak /M setx BYTEPLUS_SECRET_KEY your-sk /M setx BYTEPLUS_SESSION_TOKEN your-session-token /M ``` -------------------------------- ### Configure HTTP(S) Proxy Source: https://github.com/byteplus-sdk/byteplus-java-sdk-v2/blob/main/docs/3-Transport.md Set the HTTP and HTTPS proxy URLs. The SDK prioritizes proxy settings configured in code over environment variables. ```java import com.byteplus.ApiClient; import com.byteplus.sign.Credentials; public class SampleCode { public static void main(String[] args) { String regionId = "ap-singapore-1"; ApiClient apiClient = new ApiClient() .setCredentials(Credentials.getEnvCredentials()) .setRegion(regionId) .setHttpProxy("http://your_http_proxy:proxy_port") .setHttpsProxy("http://your_https_proxy:proxy_port"); } } ``` -------------------------------- ### File Management with ArkService Source: https://context7.com/byteplus-sdk/byteplus-java-sdk-v2/llms.txt Provides methods for uploading files for batch inference or fine-tuning, retrieving file metadata, listing all uploaded files, and deleting files. ```APIDOC ## `ArkService.uploadFile` / `retrieveFile` / `listFiles` / `deleteFile` — File Management The file management methods upload files to the Ark platform for use in batch inference or fine-tuning, retrieve file metadata, list all uploaded files, and delete files. ### Usage Example (Java) ```java import com.byteplus.ark.runtime.service.ArkService; import com.byteplus.ark.runtime.model.files.*; import java.io.File; import java.time.Duration; public class FileManagementExample { public static void main(String[] args) { ArkService service = new ArkService("YOUR_ARK_API_KEY", Duration.ofMinutes(5)); // Upload a file UploadFileRequest uploadReq = new UploadFileRequest(); uploadReq.setFile(new File("/data/training_data.jsonl")); uploadReq.setPurpose("fine-tune"); FileMeta uploaded = service.uploadFile(uploadReq); System.out.println("Uploaded file ID: " + uploaded.getId()); // Retrieve file metadata FileMeta meta = service.retrieveFile(uploaded.getId()); System.out.printf("File: %s, size=%d bytes, status=%s%n", meta.getFilename(), meta.getBytes(), meta.getStatus()); // List all files ListFilesRequest listReq = new ListFilesRequest(); listReq.setPurpose("fine-tune"); ListFilesResponse files = service.listFiles(listReq); files.getData().forEach(f -> System.out.println(" " + f.getId() + " - " + f.getFilename())); // Delete a file DeleteFileResponse del = service.deleteFile(uploaded.getId()); System.out.println("Deleted: " + del.getId() + ", deleted=" + del.getDeleted()); service.shutdownExecutor(); } } ``` ``` -------------------------------- ### CLIConfigCredentialProvider Source: https://context7.com/byteplus-sdk/byteplus-java-sdk-v2/llms.txt Loads credentials from `~/.byteplus/config.json`, supporting multiple profiles and various credential modes by delegating to underlying providers. ```APIDOC ## `CLIConfigCredentialProvider` — Reuse BytePlus CLI Profile `CLIConfigCredentialProvider` loads credentials from `~/.byteplus/config.json`. It supports multiple profiles and all credential modes (`AK`, `StsToken`, `RamRoleArn`, `OIDC`, `EcsRole`, `SSO`), automatically delegating to the appropriate underlying provider. ```java import com.byteplus.ApiClient; import com.byteplus.auth.CLIConfigCredentialProvider; import com.byteplus.auth.CredentialProvider; import java.nio.file.Paths; // Use named profile "prod" from default config path CLIConfigCredentialProvider cliProvider = new CLIConfigCredentialProvider( "prod", // profile name Paths.get(System.getProperty("user.home"), ".byteplus", "config.json").toString() ); // Config file path priority: constructor arg > BYTEPLUS_CLI_CONFIG_FILE > ~/.byteplus/config.json // Profile priority: constructor arg > BYTEPLUS_PROFILE > "current" in config > "default" ApiClient client = new ApiClient() .setCredentialProvider(new CredentialProvider(cliProvider)) .setRegion("ap-southeast-1"); ``` ``` -------------------------------- ### OIDC Credential Provider from Environment Source: https://github.com/byteplus-sdk/byteplus-java-sdk-v2/blob/main/docs/1-Credentials.md Configure OIDC credentials using environment variables BYTEPLUS_OIDC_ROLE_TRN and BYTEPLUS_OIDC_TOKEN_FILE. This provider is suitable for OIDC-based authentication flows. ```java import com.byteplus.ApiClient; import com.byteplus.auth.CredentialProvider; import com.byteplus.auth.OidcCredentialProvider; public class SampleCode { public static void main(String[] args) throws Exception { // Required: // BYTEPLUS_OIDC_ROLE_TRN // BYTEPLUS_OIDC_TOKEN_FILE OidcCredentialProvider oidcProvider = OidcCredentialProvider.fromEnvironment(); CredentialProvider credentialProvider = new CredentialProvider(oidcProvider); ApiClient apiClient = new ApiClient() .setCredentialProvider(credentialProvider) .setRegion("ap-singapore-1"); } } ``` -------------------------------- ### Configure SSL Verification Source: https://github.com/byteplus-sdk/byteplus-java-sdk-v2/blob/main/docs/3-Transport.md Set `verifyingSsl` to `false` to skip SSL certificate verification. The default is `true`. ```java import com.byteplus.ApiClient; import com.byteplus.sign.Credentials; public class SampleCode { public static void main(String[] args) { String regionId = "ap-singapore-1"; ApiClient apiClient = new ApiClient() .setCredentials(Credentials.getEnvCredentials()) .setRegion(regionId) .setVerifyingSsl(false); } } ``` -------------------------------- ### Create and Use Context-Aware Chat Completion in Java Source: https://context7.com/byteplus-sdk/byteplus-java-sdk-v2/llms.txt Use `createContext` to cache conversation history server-side, then `createContextChatCompletion` to reuse it for reduced latency and token cost in multi-turn conversations. Ensure to replace placeholders with your actual API key and endpoint ID. ```java import com.byteplus.ark.runtime.service.ArkService; import com.byteplus.ark.runtime.model.context.*; import com.byteplus.ark.runtime.model.context.chat.*; import com.byteplus.ark.runtime.model.completion.chat.*; import java.time.Duration; import java.util.*; public class ContextChatExample { public static void main(String[] args) { ArkService service = new ArkService("YOUR_ARK_API_KEY", Duration.ofMinutes(5)); String endpointId = "YOUR_ENDPOINT_ID"; // Step 1: create and cache context (system prompt + history) CreateContextRequest contextReq = new CreateContextRequest(); contextReq.setModel(endpointId); contextReq.setMessages(Arrays.asList( ChatMessage.builder() .role(ChatMessageRole.SYSTEM) .content("You are a senior Java developer who always responds with complete, runnable code examples.") .build() )); CreateContextResult contextResult = service.createContext(contextReq); String contextId = contextResult.getId(); System.out.println("Context cached: " + contextId); // Step 2: chat using the cached context ContextChatCompletionRequest chatReq = new ContextChatCompletionRequest(); chatReq.setContextId(contextId); chatReq.setMessages(Arrays.asList( ChatMessage.builder() .role(ChatMessageRole.USER) .content("Show me how to read a file line by line in Java.") .build() )); try { ChatCompletionResult result = service.createContextChatCompletion(chatReq); System.out.println(result.getChoices().get(0).getMessage().getContent()); } catch (Exception e) { System.err.println("Context chat error: " + e.getMessage()); } finally { service.shutdownExecutor(); } } } ``` -------------------------------- ### OIDC Federation with Auto-Refresh using `OidcCredentialProvider` Source: https://context7.com/byteplus-sdk/byteplus-java-sdk-v2/llms.txt This provider exchanges an OIDC token file for temporary STS credentials via `AssumeRoleWithOIDC`, commonly used in Kubernetes environments. It supports explicit parameters or loading from environment variables. ```java import com.byteplus.ApiClient; import com.byteplus.auth.CredentialProvider; import com.byteplus.auth.OidcCredentialProvider; // Explicit parameters OidcCredentialProvider oidcProvider = new OidcCredentialProvider( "trn:iam::123456789:role/oidc-role", // roleTrn "my-session", // roleSessionName (nullable) "/var/run/secrets/oidc/token", // oidcTokenFile path null, // rolePolicy JSON (nullable) "sts.byteplusapi.com" // stsEndpoint (nullable = default) ); opeoidcProvider.setDurationSeconds(3600); opeoidcProvider.setExpireBufferSeconds(300); opeoidcProvider.setMaxRetries(3); opeoidcProvider.setRetryIntervalMs(1000); // Or load entirely from environment variables: // BYTEPLUS_OIDC_ROLE_TRN, BYTEPLUS_OIDC_TOKEN_FILE (required) // BYTEPLUS_OIDC_ROLE_SESSION_NAME, BYTEPLUS_OIDC_ROLE_POLICY, BYTEPLUS_OIDC_STS_ENDPOINT (optional) OidcCredentialProvider oidcFromEnv = OidcCredentialProvider.fromEnvironment(); ApiClient client = new ApiClient() .setCredentialProvider(new CredentialProvider(oidcFromEnv)) .setRegion("ap-southeast-1"); ``` -------------------------------- ### Wrap Static AK/SK with `StaticCredentialProvider` Source: https://context7.com/byteplus-sdk/byteplus-java-sdk-v2/llms.txt This provider wraps long-lived AK/SK (with optional STS token) into the `CredentialProvider` interface, allowing static credentials to be used interchangeably with dynamic providers. ```java import com.byteplus.ApiClient; import com.byteplus.auth.CredentialProvider; import com.byteplus.auth.StaticCredentialProvider; StaticCredentialProvider staticProvider = new StaticCredentialProvider( "YOUR_AK", "YOUR_SK", null // sessionToken; pass non-null for STS ); CredentialProvider credentialProvider = new CredentialProvider(staticProvider); ApiClient client = new ApiClient() .setCredentialProvider(credentialProvider) .setRegion("ap-southeast-1"); ``` -------------------------------- ### Set Linux Environment Variables Source: https://github.com/byteplus-sdk/byteplus-java-sdk-v2/blob/main/docs/1-Credentials.md Configure environment variables for BytePlus access keys and session tokens on Linux. Note that `export` commands are session-specific; for persistence, add them to your shell startup scripts. ```bash export BYTEPLUS_ACCESS_KEY=yourAccessKeyID ``` ```bash export BYTEPLUS_SECRET_KEY=yourSecretAccessKey ``` ```bash export BYTEPLUS_SESSION_TOKEN=yourSessionToken ``` -------------------------------- ### Low-Level Generic API Call with UniversalApi Source: https://context7.com/byteplus-sdk/byteplus-java-sdk-v2/llms.txt Use UniversalApi.doCall for API calls when a dedicated service module is not yet available. The request and response bodies are Map. ```java import com.byteplus.ApiClient; import com.byteplus.ApiException; import com.byteplus.ContentType; import com.byteplus.HttpMethod; import com.byteplus.UniversalApi; import com.byteplus.UniversalRequest; import com.byteplus.sign.Credentials; import java.util.*; public class UniversalApiExample { public static void main(String[] args) { ApiClient client = new ApiClient() .setCredentials(Credentials.getEnvCredentials()) .setRegion("ap-southeast-1"); UniversalApi api = new UniversalApi(client); UniversalRequest req = new UniversalRequest(); req.setAction("DescribeVpcs"); req.setVersion("2020-04-01"); req.setServiceName("vpc"); req.setHttpMethod(HttpMethod.GET); req.setContentType(ContentType.JSON); Map params = new HashMap<>(); params.put("VpcIds.1", "vpc-13fpdgwk7rxfk3n6nu44wisg7"); try { Map response = api.doCall(req, params); System.out.println("Response: " + response); } catch (ApiException e) { System.err.println("API call failed: " + e.getResponseBody()); } } } ``` -------------------------------- ### Configure Global Client Timeouts Source: https://github.com/byteplus-sdk/byteplus-java-sdk-v2/blob/main/docs/4-Timeout.md Set connect, read, and write timeouts for the ApiClient. Default values are 10 seconds. ```java import com.byteplus.ApiClient; import com.byteplus.sign.Credentials; public class SampleCode { public static void main(String[] args) { String regionId = "ap-singapore-1"; ApiClient apiClient = new ApiClient() .setCredentials(Credentials.getEnvCredentials()) .setRegion(regionId) .setConnectTimeout(10 * 1000) .setReadTimeout(15 * 1000) .setWriteTimeout(15 * 1000); } } ``` -------------------------------- ### Describe Instances Source: https://context7.com/byteplus-sdk/byteplus-java-sdk-v2/llms.txt Retrieves a list of ECS instances based on specified filters. ```APIDOC ## Describe Instances ### Description Retrieves a list of ECS instances based on specified filters. ### Method `describeInstances` ### Parameters #### Request Body - **instanceIds** (array of strings) - Optional - A list of instance IDs to filter by. - **regionId** (string) - Optional - The ID of the region to describe instances for. - **zoneId** (string) - Optional - The ID of the zone to describe instances for. - **instanceType** (string) - Optional - The instance type to filter by. - **status** (string) - Optional - The status of the instances to filter by (e.g., "Running", "Stopped"). - **tagFilters** (object) - Optional - Filters based on tags. - **key** (string) - The tag key. - **value** (string) - The tag value. - **maxResults** (integer) - Optional - The maximum number of instances to return. - **nextToken** (string) - Optional - The token for the next page of results. ### Request Example ```java DescribeInstancesRequest instReq = new DescribeInstancesRequest(); instReq.setMaxResults(20); DescribeInstancesResponse instResp = ecsApi.describeInstances(instReq); ``` ### Response #### Success Response (200) - **instances** (array) - A list of ECS instances. - **instanceId** (string) - The ID of the instance. - **instanceType** (string) - The type of the instance. - **status** (string) - The current status of the instance. - **creationTime** (string) - The time when the instance was created. - **tags** (array) - A list of tags associated with the instance. - **nextToken** (string) - The token for the next page of results, if any. #### Response Example ```json { "instances": [ { "instanceId": "i-xxxxxxxxxxxxxxxxx", "instanceType": "ecs.c1.medium", "status": "Running", "creationTime": "2023-10-27T09:00:00Z", "tags": [ { "key": "Name", "value": "MyInstance" } ] } ], "nextToken": "next-page-token" } ``` ```