### ConnectionOptions Builder Example Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/configuration.md Example of building ConnectionOptions and initializing a Generation client. ```java ConnectionOptions options = ConnectionOptions.builder() .connectTimeout(Duration.ofSeconds(30)) .readTimeout(Duration.ofSeconds(120)) .writeTimeout(Duration.ofSeconds(30)) .proxyHost("proxy.example.com") .proxyPort(8080) .build(); Generation generation = new Generation( Protocol.HTTP.getValue(), "https://api.example.com", options ); ``` -------------------------------- ### Environment Variable Example Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/configuration.md Example of setting the DASHSCOPE_API_KEY environment variable. ```bash export DASHSCOPE_API_KEY="sk-xxxxxxxxxxxxxxxx" ``` -------------------------------- ### Network Configuration Environment Variables Example Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/configuration.md Examples of setting network-related environment variables. ```bash export DASHSCOPE_PROXY_HOST="proxy.company.com" export DASHSCOPE_PROXY_PORT="8080" export DASHSCOPE_READ_TIMEOUT="60" export DASHSCOPE_CONNECTION_TIMEOUT="30" ``` -------------------------------- ### Proxy Authentication Example Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/configuration.md Provides a Java code example for setting up proxy authentication using OkHttp's Authenticator with basic credentials. ```java import okhttp3.Authenticator; import okhttp3.Credentials; import okhttp3.Request; import okhttp3.Response; import java.io.IOException; Authenticator proxyAuth = new Authenticator() { @Override public Request authenticate(Route route, Response response) throws IOException { String credential = Credentials.basic("username", "password"); return response.request().newBuilder() .header("Proxy-Authorization", credential) .build(); } }; ConnectionOptions options = ConnectionOptions.builder() .proxyHost("proxy.company.com") .proxyPort(8080) .proxyAuthenticator(proxyAuth) .build(); ``` -------------------------------- ### QwenTtsRealtime Constructor Example Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/api-reference/audiotts.md Example of how to configure and create a QwenTtsRealtime instance. ```java QwenTtsRealtimeConfig config = QwenTtsRealtimeConfig.builder() .apiKey("your-api-key") .model("qwen-tts-realtime") .voice("longyuxi") .build(); QwenTtsRealtime realtimeTts = new QwenTtsRealtime(config); ``` -------------------------------- ### GenerationParam Builder Example Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/configuration.md Example of building GenerationParam for text generation requests. ```java GenerationParam param = GenerationParam.builder() .model("qwen-turbo") // Required .prompt("Your prompt") // Required (or messages) .apiKey("your-api-key") // Optional if env var set .temperature(0.7f) // Default varies by model .topP(0.9) // Nucleus sampling .topK(25) // Top-k sampling .maxTokens(1024) // Max output length .seed(42) // For reproducibility .enableSearch(true) // Enable web search .resultFormat("text") // "text" or "message" .incrementalOutput(false) // Streaming mode .repetitionPenalty(1.1f) // Avoid repetition .build(); ``` -------------------------------- ### Protocol Options Configuration Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/configuration.md Examples of configuring the Generation client with HTTP or WebSocket protocols. ```java // HTTP protocol (recommended for most cases) Generation generation = new Generation(Protocol.HTTP.getValue()); // WebSocket protocol (for persistent connections) Generation generation = new Generation(Protocol.WEBSOCKET.getValue()); ``` -------------------------------- ### Base URL Configuration Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/configuration.md Examples of configuring the Generation client with default or custom endpoints. ```java // Use default DashScope endpoint Generation generation = new Generation(); // Use custom endpoint Generation generation = new Generation( Protocol.HTTP.getValue(), "https://custom-api.example.com" ); ``` -------------------------------- ### Simple Text Generation Example Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/README.md Basic usage example for text generation. ```java import com.alibaba.dashscope.aigc.generation.Generation; import com.alibaba.dashscope.aigc.generation.GenerationParam; Generation generation = new Generation(); GenerationParam param = GenerationParam.builder() .model("qwen-turbo") .prompt("What is machine learning?") .build(); GenerationResult result = generation.call(param); System.out.println(result.getOutput().getText()); ``` -------------------------------- ### Simple Chat Completion Example Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/README.md Basic usage example for chat completion. ```java import com.alibaba.dashscope.aigc.completion.ChatCompletions; import com.alibaba.dashscope.aigc.completion.ChatCompletionParam; import com.alibaba.dashscope.common.Message; ChatCompletions client = new ChatCompletions(); ChatCompletionParam param = ChatCompletionParam.builder() .model("qwen-turbo") .messages(List.of( Message.builder().role("user").content("Hello!").build() )) .build(); ChatCompletion result = client.call(param); System.out.println(result.getChoices().get(0).getMessage().getContent()); ``` -------------------------------- ### streamCall Example Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/api-reference/audiotts.md Example of setting up parameters and calling the streamCall method. ```java QwenTtsRealtimeParam param = QwenTtsRealtimeParam.builder() .text("Hello world!") .sampleRate(QwenTtsRealtimeAudioFormat.SAMPLE_RATE_16K) .build(); realtimeTts.streamCall(param); ``` -------------------------------- ### Call Method Example Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/api-reference/generation.md Performs a blocking synchronous call to get the complete model response. ```java public GenerationResult call(HalfDuplexServiceParam param) throws ApiException, NoApiKeyException, InputRequiredException ``` ```java import com.alibaba.dashscope.aigc.generation.Generation; import com.alibaba.dashscope.aigc.generation.GenerationParam; import com.alibaba.dashscope.aigc.generation.GenerationResult; Generation generation = new Generation(); GenerationParam param = GenerationParam.builder() .model("qwen-turbo") .prompt("Translate 'hello' to French") .apiKey("your-api-key") .build(); try { GenerationResult result = generation.call(param); System.out.println("Output: " + result.getOutput().getText()); System.out.println("Request ID: " + result.getRequestId()); } catch (Exception e) { e.printStackTrace(); } ``` -------------------------------- ### Java Usage with Environment Variable Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/configuration.md Example of how the SDK automatically reads the DASHSCOPE_API_KEY environment variable. ```java GenerationParam param = GenerationParam.builder() .model("qwen-turbo") .prompt("Hello") .build(); // API key read from env ``` -------------------------------- ### TextReRank() Constructor Example Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/api-reference/textrerank.md Creates a TextReRank client with default HTTP protocol and settings. ```java TextReRank reranker = new TextReRank(); ``` -------------------------------- ### Example with Custom Timeouts Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/configuration.md Demonstrates how to set custom connection, write, and read timeouts using ConnectionOptions and then initializing a Generation object. ```java ConnectionOptions options = ConnectionOptions.builder() .connectTimeout(Duration.ofSeconds(30)) .writeTimeout(Duration.ofSeconds(30)) .readTimeout(Duration.ofSeconds(180)) .build(); Generation generation = new Generation( Protocol.HTTP.getValue(), null, options ); ``` -------------------------------- ### shutdown Example Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/api-reference/audiotts.md Example of how to shut down the real-time TTS session. ```java realtimeTts.shutdown(); ``` -------------------------------- ### Environment Setup Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/QUICK_REFERENCE.md Sets environment variables for API key and optional connection timeouts/proxy settings. ```bash # Required export DASHSCOPE_API_KEY="sk-..." # Optional (with defaults shown) export DASHSCOPE_CONNECTION_TIMEOUT="120" # seconds export DASHSCOPE_READ_TIMEOUT="300" # seconds export DASHSCOPE_WRITE_TIMEOUT="60" # seconds export DASHSCOPE_PROXY_HOST="" # e.g., proxy.company.com export DASHSCOPE_PROXY_PORT="443" # if using proxy ``` -------------------------------- ### ImageGeneration() Constructor Example Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/api-reference/imagegeneration.md Creates an ImageGeneration client with default HTTP protocol and settings. ```java ImageGeneration imageGen = new ImageGeneration(); ``` -------------------------------- ### ChatCompletionParam Configuration Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/configuration.md Example of configuring ChatCompletionParam for OpenAI-compatible chat completions. ```java ChatCompletionParam param = ChatCompletionParam.builder() .model("qwen-turbo") // Required .messages(List.of( Message.builder() .role("user") .content("What is AI?") .build() )) .temperature(0.7f) .topP(1) .maxTokens(1024) .frequencyPenalty(0f) .presencePenalty(0f) .seed(null) .responseFormat("json") .stream(false) .tools(List.of()) .apiKey("key") .build(); ``` -------------------------------- ### UploadFileException Example Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/errors.md Demonstrates how to catch and handle UploadFileException during file upload operations. ```java try { ImageGenerationResult result = imageGen.call(param); } catch (UploadFileException e) { System.err.println("File upload failed: " + e.getMessage()); } ``` -------------------------------- ### TextReRank(String protocol) Constructor Example Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/api-reference/textrerank.md Creates a TextReRank client with specified protocol. ```java TextReRank reranker = new TextReRank(Protocol.HTTP.getValue()); ``` -------------------------------- ### Handling ApiException Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/errors.md Example of how to catch and handle ApiException in Java. ```java try { GenerationResult result = generation.call(param); } catch (ApiException e) { Status status = e.getStatus(); int httpCode = status.getStatusCode(); String code = status.getCode(); String message = status.getMessage(); String requestId = status.getRequestId(); } ``` -------------------------------- ### Simple Text Embedding Example Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/README.md Basic usage example for text embedding. ```java import com.alibaba.dashscope.embeddings.TextEmbedding; import com.alibaba.dashscope.embeddings.TextEmbeddingParam; TextEmbedding embedding = new TextEmbedding(); TextEmbeddingParam param = TextEmbeddingParam.builder() .model("text-embedding-v3") .texts(Arrays.asList("text to embed")) .build(); TextEmbeddingResult result = embedding.call(param); List vector = result.getOutput().getEmbeddings().get(0).getEmbedding(); ``` -------------------------------- ### Image Generation Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/QUICK_REFERENCE.md Example of generating images using the DashScope Java SDK. ```java ImageGeneration imgGen = new ImageGeneration(); ImageGenerationResult result = imgGen.call( ImageGenerationParam.builder() .model("wan2.6-t2i") .message(ImageGenerationMessage.builder() .role("user") .content("A beautiful landscape") .build()) .size("1024*1024") .n(1) .apiKey("key") .build() ); String imageUrl = result.getOutput().getResults().get(0).getUrl(); ``` -------------------------------- ### call(ChatCompletionParam param) Method Example Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/api-reference/chatcompletions.md Performs a synchronous call to get the complete chat completion. ```java import com.alibaba.dashscope.aigc.completion.ChatCompletions; import com.alibaba.dashscope.aigc.completion.ChatCompletion; import com.alibaba.dashscope.aigc.completion.ChatCompletionParam; import com.alibaba.dashscope.common.Message; import com.alibaba.dashscope.common.Role; import java.util.Arrays; ChatCompletions client = new ChatCompletions(); ChatCompletionParam param = ChatCompletionParam.builder() .model("qwen-turbo") .messages(Arrays.asList( Message.builder() .role(Role.USER.getValue()) .content("What is machine learning?") .build() )) .temperature(0.7f) .apiKey("your-api-key") .build(); try { ChatCompletion result = client.call(param); String response = result.getChoices().get(0).getMessage().getContent(); System.out.println("Response: " + response); } catch (Exception e) { e.printStackTrace(); } ``` -------------------------------- ### Function Calling Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/README.md Example of setting up tools for function calling. ```java List tools = List.of( // Define tools... ); GenerationParam param = GenerationParam.builder() .model("qwen-turbo") .messages(messages) .tools(tools) .build(); ``` -------------------------------- ### Text vs Message Format - Text Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/configuration.md Example of configuring the response format to 'text', which returns the generated text directly. ```json "result_format": "text" // Returns: output.text = "generated text" ``` -------------------------------- ### Request ID Tracking Example Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/configuration.md Demonstrates how to retrieve and print the unique requestId from a GenerationResult for debugging and tracking purposes. ```java GenerationResult result = generation.call(param); String requestId = result.getRequestId(); System.out.println("Request ID: " + requestId); ``` -------------------------------- ### ImageGeneration(String protocol) Constructor Example Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/api-reference/imagegeneration.md Creates an ImageGeneration client with specified protocol. ```java ImageGeneration imageGen = new ImageGeneration(Protocol.HTTP.getValue()); ``` -------------------------------- ### TextEmbedding() Constructor Example Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/api-reference/textembedding.md Creates a TextEmbedding client with default HTTP protocol and settings. ```java TextEmbedding embedding = new TextEmbedding(); ``` -------------------------------- ### ImageGenerationParam Configuration Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/configuration.md Example of configuring ImageGenerationParam for image generation requests. ```java ImageGenerationParam param = ImageGenerationParam.builder() .model("wan2.6-t2i") // Required .message(ImageGenerationMessage.builder() // Required .role("user") .content("A scenic mountain landscape") .build()) .size("1024*1024") // Image dimensions .n(1) // Number of images .seed(42) // Reproducibility .negativePrompt("ugly, blurry") // Negative prompt .promptExtend(false) // Extend prompt .watermark(true) // Add watermark .apiKey("key") .build(); ``` -------------------------------- ### Handling InputRequiredException Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/errors.md Example of how to catch and handle InputRequiredException in Java. ```java try { GenerationResult result = generation.call(param); } catch (InputRequiredException e) { String errorMsg = e.getMessage(); System.err.println("Missing required parameter: " + errorMsg); } ``` -------------------------------- ### TextReRank(String protocol, String baseUrl, ConnectionOptions connectionOptions) Constructor Example Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/api-reference/textrerank.md Creates a TextReRank client with advanced connection configuration. ```java TextReRank reranker = new TextReRank( Protocol.HTTP.getValue(), "https://api.example.com", connectionOptions ); ``` -------------------------------- ### Text vs Message Format - Message Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/configuration.md Example of configuring the response format to 'message', which returns a structured message object. ```json "result_format": "message" // Returns: output.choices[].message.content = "text" ``` -------------------------------- ### TextEmbeddingParam Configuration Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/configuration.md Example of configuring TextEmbeddingParam for text embedding requests. ```java TextEmbeddingParam param = TextEmbeddingParam.builder() .model("text-embedding-v3") // Required .texts(Arrays.asList( "Text to embed", "Another text" )) .textType(TextEmbeddingParam.TextType.DOCUMENT) // QUERY or DOCUMENT .dimension(1024) // Output dimension (v3+) .outputType(TextEmbeddingParam.OutputType.DENSE) // DENSE, SPARSE, or combined .apiKey("key") .build(); ``` -------------------------------- ### Common Missing Parameters for TextEmbedding Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/errors.md Example of TextEmbeddingParam with required parameters for TextEmbedding. ```java TextEmbeddingParam param = TextEmbeddingParam.builder() .model("text-embedding-v3") // Required .texts(Arrays.asList( "text1", "text2" // Required, non-empty )) .apiKey("key") // Required .build(); ``` -------------------------------- ### ChatCompletions() Constructor Example Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/api-reference/chatcompletions.md Creates a ChatCompletions client with default settings using the HTTP protocol. ```java ChatCompletions chatCompletions = new ChatCompletions(); ``` -------------------------------- ### Handling NoApiKeyException Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/errors.md Example of how to catch and handle NoApiKeyException in Java. ```java try { GenerationResult result = generation.call(param); } catch (NoApiKeyException e) { System.err.println("API key not configured"); System.err.println("Set DASHSCOPE_API_KEY environment variable"); System.err.println("Or provide apiKey in request parameters"); } ``` -------------------------------- ### Common Missing Parameters for Generation Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/errors.md Example of GenerationParam with required parameters for Generation. ```java GenerationParam param = GenerationParam.builder() .model("qwen-turbo") // Required .prompt("Your prompt here") // Required .messages(messages) // Or messages, not both .apiKey("key") // Required .build(); ``` -------------------------------- ### TextReRank(String protocol, String baseUrl) Constructor Example Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/api-reference/textrerank.md Creates a TextReRank client with custom protocol and base URL. ```java TextReRank reranker = new TextReRank( Protocol.HTTP.getValue(), "https://api.example.com" ); ``` -------------------------------- ### Set Seed for Reproducibility Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/configuration.md Example of setting a seed value to ensure reproducible results in model generations. ```java .seed(42) // Same seed = same results ``` -------------------------------- ### Common Missing Parameters for ChatCompletion Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/errors.md Example of ChatCompletionParam with required parameters for ChatCompletion. ```java ChatCompletionParam param = ChatCompletionParam.builder() .model("qwen-turbo") // Required .messages(messages) // Required, non-empty .apiKey("key") // Required .build(); ``` -------------------------------- ### Text Embedding Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/QUICK_REFERENCE.md Example of generating text embeddings using the DashScope Java SDK. ```java TextEmbedding embedding = new TextEmbedding(); TextEmbeddingResult result = embedding.call( TextEmbeddingParam.builder() .model("text-embedding-v3") .texts(Arrays.asList("text 1", "text 2")) .dimension(1024) .apiKey("key") .build() ); List vector = result.getOutput().getEmbeddings().get(0).getEmbedding(); ``` -------------------------------- ### ImageGeneration(String protocol, String baseUrl, ConnectionOptions connectionOptions) Constructor Example Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/api-reference/imagegeneration.md Creates an ImageGeneration client with advanced connection configuration. ```java ImageGeneration imageGen = new ImageGeneration( Protocol.HTTP.getValue(), "https://api.example.com", connectionOptions ); ``` -------------------------------- ### Text Reranking Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/QUICK_REFERENCE.md Example of performing text reranking using the DashScope Java SDK. ```java TextReRank reranker = new TextReRank(); TextReRankResult result = reranker.call( TextReRankParam.builder() .model("gte-rerank-v2") .query("What is AI?") .documents(Arrays.asList( "AI is...", "Machine learning...", "The weather is..." )) .topN(2) .apiKey("key") .build() ); result.getOutput().getResults().forEach(r -> System.out.println("Score: " + r.getRelevanceScore()) ); ``` -------------------------------- ### Audio TTS - HTTP-based Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/QUICK_REFERENCE.md Example of using HTTP-based Audio TTS (Text-to-Speech) with the DashScope Java SDK. ```java HttpSpeechSynthesizer synthesizer = new HttpSpeechSynthesizer(); HttpSpeechSynthesisResult result = synthesizer.call( HttpSpeechSynthesisParam.builder() .model("cosyvoice-v3-flash") .text("Hello world!") .voice("longxiao") .sampleRate(48000) .apiKey("key") .build() ); String audioUrl = result.getOutput().getAudio().getUrl(); ``` -------------------------------- ### Non-stream only conversation example Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/README.md This Java code demonstrates how to initiate a non-streaming conversation using the Qwen model. ```java import com.alibaba.dashscope.aigc.conversation.Conversation; import com.alibaba.dashscope.aigc.conversation.ConversationResult; import com.alibaba.dashscope.aigc.conversation.qwen.QWenConversationParam; public class Main { public static void main(String[] args) { Conversation conversation = new Conversation(); //QWEN model, if using other model, you can replace the QWenConversationParam here. QWenConversationParam param = QWenConversationParam.builder() .model(QWenConversationParam.QWEN_TURBO) .prompt("hello") .apiKey("testKey") .build(); ConversationResult result = conversation.call(param); } } ``` -------------------------------- ### Asynchronous call() Method Example Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/api-reference/textembedding.md Performs an asynchronous call with callback-based result handling. ```java embedding.call(param, new ResultCallback() { @Override public void onEvent(TextEmbeddingResult result) { int count = result.getOutput().getEmbeddings().size(); System.out.println("Generated " + count + " embeddings"); } @Override public void onComplete() { System.out.println("Embedding complete"); } @Override public void onError(Exception e) { System.err.println("Error: " + e.getMessage()); } }); ``` -------------------------------- ### call(TextReRankParam param) Method Example Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/api-reference/textrerank.md Performs a synchronous call to rerank documents. ```java import com.alibaba.dashscope.rerank.TextReRank; import com.alibaba.dashscope.rerank.TextReRankParam; import com.alibaba.dashscope.rerank.TextReRankResult; import java.util.Arrays; TextReRank reranker = new TextReRank(); TextReRankParam param = TextReRankParam.builder() .model("gte-rerank-v2") .query("What is machine learning?") .documents(Arrays.asList( "ML is a subset of AI focused on learning from data", "The weather is sunny today", "Machine learning enables computers to improve through experience" )) .topN(2) .returnDocuments(true) .apiKey("your-api-key") .build(); try { TextReRankResult result = reranker.call(param); result.getOutput().getResults().forEach(item -> { System.out.println("Score: " + item.getRelevanceScore() + " Index: " + item.getIndex()); }); } catch (Exception e) { e.printStackTrace(); } ``` -------------------------------- ### TextEmbedding(String baseUrl) Constructor Example Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/api-reference/textembedding.md Creates a TextEmbedding client with a custom base URL. ```java TextEmbedding embedding = new TextEmbedding("https://api.example.com"); ``` -------------------------------- ### Enabling Web Search Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/README.md Example of enabling web search for a generation request. ```java GenerationParam param = GenerationParam.builder() .model("qwen-turbo") .prompt("Latest AI developments") .enableSearch(true) // Enable web search .build(); ``` -------------------------------- ### InvalidateParameter Exception Example Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/errors.md Shows how to catch and handle InvalidateParameter exceptions when request parameters are invalid. ```java try { GenerationParam param = GenerationParam.builder() .model("invalid-model-name") // Invalid model .prompt("test") .apiKey("key") .build(); generation.call(param); } catch (InvalidateParameter e) { System.err.println("Invalid parameter: " + e.getMessage()); } ``` -------------------------------- ### Synchronous call() Method Example Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/api-reference/textembedding.md Performs a synchronous call to generate text embeddings. ```java import com.alibaba.dashscope.embeddings.TextEmbedding; import com.alibaba.dashscope.embeddings.TextEmbeddingParam; import com.alibaba.dashscope.embeddings.TextEmbeddingResult; import java.util.Arrays; TextEmbedding embedding = new TextEmbedding(); TextEmbeddingParam param = TextEmbeddingParam.builder() .model("text-embedding-v3") .texts(Arrays.asList( "The quick brown fox jumps over the lazy dog", "Machine learning is a subset of artificial intelligence" )) .textType(TextEmbeddingParam.TextType.DOCUMENT) .dimension(1024) .apiKey("your-api-key") .build(); try { TextEmbeddingResult result = embedding.call(param); result.getOutput().getEmbeddings().forEach(emb -> { System.out.println("Embedding dimension: " + emb.getEmbedding().size()); }); } catch (Exception e) { e.printStackTrace(); } ``` -------------------------------- ### Adjusting Sampling Parameters Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/README.md Example of adjusting temperature, topP, and topK for response randomness. ```java param = param.toBuilder() .temperature(0.7f) // 0=deterministic, 2=random .topP(0.9) // nucleus sampling .topK(25) // top-k sampling .build(); ``` -------------------------------- ### call(ImageGenerationParam param) Method Example Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/api-reference/imagegeneration.md Performs a synchronous call to generate images using the ImageGeneration API. ```java import com.alibaba.dashscope.aigc.imagegeneration.ImageGeneration; import com.alibaba.dashscope.aigc.imagegeneration.ImageGenerationParam; import com.alibaba.dashscope.aigc.imagegeneration.ImageGenerationResult; import com.alibaba.dashscope.aigc.imagegeneration.ImageGenerationMessage; ImageGeneration imageGen = new ImageGeneration(); ImageGenerationMessage message = ImageGenerationMessage.builder() .role("user") .content("Generate a scenic mountain landscape with a lake at sunset") .build(); ImageGenerationParam param = ImageGenerationParam.builder() .model("wan2.6-t2i") .message(message) .seed(42) .size("1024*1024") .n(1) .apiKey("your-api-key") .build(); try { ImageGenerationResult result = imageGen.call(param); String imageUrl = result.getOutput().getResults().get(0).getUrl(); System.out.println("Generated image: " + imageUrl); } catch (Exception e) { e.printStackTrace(); } ``` -------------------------------- ### Text Generation (Primary) - Sync Call Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/QUICK_REFERENCE.md Synchronous call example for text generation using the DashScope Java SDK. ```java Generation gen = new Generation(); GenerationResult result = gen.call( GenerationParam.builder() .model("qwen-turbo") .prompt("Your prompt here") .apiKey("key") .build() ); System.out.println(result.getOutput().getText()); ``` -------------------------------- ### Chat Completions (OpenAI Compatible) - Sync Call Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/QUICK_REFERENCE.md Synchronous call example for chat completions, compatible with OpenAI API, using the DashScope Java SDK. ```java ChatCompletions client = new ChatCompletions(); ChatCompletion result = client.call( ChatCompletionParam.builder() .model("qwen-turbo") .messages(List.of( Message.builder().role("user").content("Hello").build() )) .apiKey("key") .build() ); String response = result.getChoices().get(0).getMessage().getContent(); ``` -------------------------------- ### Streaming with Flowable (Reactive) Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/README.md Example of using the SDK for streaming responses with RxJava's Flowable. ```java Flowable stream = generation.streamCall(param); stream.blockingForEach(result -> System.out.print(result.getOutput().getText()) ); ``` -------------------------------- ### ImageGeneration(String protocol, String baseUrl) Constructor Example Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/api-reference/imagegeneration.md Creates an ImageGeneration client with custom protocol and base URL. ```java ImageGeneration imageGen = new ImageGeneration( Protocol.HTTP.getValue(), "https://api.example.com" ); ``` -------------------------------- ### Handling Rate Limiting Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/README.md Example of catching ApiException and implementing backoff for rate limiting. ```java try { return generation.call(param); } catch (ApiException e) { if (e.getStatus().getStatusCode() == 429) { // Rate limited - implement backoff Thread.sleep(5000); return generation.call(param); } } ``` -------------------------------- ### Streaming with Callback-based API Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/README.md Example of using the SDK for streaming responses with a callback interface. ```java generation.streamCall(param, new ResultCallback() { public void onEvent(GenerationResult result) { } public void onComplete() { } public void onError(Exception e) { } }); ``` -------------------------------- ### ErrorType Usage Example Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/errors.md Illustrates how to use the ErrorType enum to check specific error codes within an ApiException. ```java try { generation.call(param); } catch (ApiException e) { Status status = e.getStatus(); String code = status.getCode(); if (code.equals(ErrorType.API_KEY_ERROR.getValue())) { // Handle auth error } else if (code.equals(ErrorType.NETWORK_ERROR.getValue())) { // Handle network error } } ``` -------------------------------- ### Conversation Call with Callback (Stream and Non-Stream) Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/README.md Example of making a conversation call that supports both stream and non-stream modes, accepting results via a callback. ```java import com.alibaba.dashscope.common.ResultCallback; import com.alibaba.dashscope.aigc.conversation.Conversation; import com.alibaba.dashscope.aigc.conversation.ConversationResult; import com.alibaba.dashscope.aigc.conversation.qwen.QWenConversationParam; import com.alibaba.dashscope.aigc.conversation.qwen.QWenConversationResult; import com.alibaba.dashscope.exception.ApiException; public class Main { public static void main(String[] args) { Conversation conversation = new Conversation(); //QWEN model, if using other model, you can replace the QWenConversationParam here. QWenConversationParam param = QWenConversationParam.builder() .model(QWenConversationParam.QWEN_TURBO) //there are other arguments supported. .prompt("hello") .apiKey("testKey") .build(); class ReactCallback extends ResultCallback { @Override public void onEvent(ConversationResult message) { QWenConversationResult result = (QWenConversationResult) message; // TODO deal with result } public void onComplete() { // TODO all messages received } public void onError(Exception e) { ApiException apiException = (ApiException) e; // TODO deal with exception } } conversation.call(param, new ReactCallback()); } } ``` -------------------------------- ### ChatCompletions(String baseUrl, ConnectionOptions connectionOptions) Constructor Example Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/api-reference/chatcompletions.md Creates a ChatCompletions client with custom base URL and connection options. ```java ConnectionOptions options = ConnectionOptions.builder() .readTimeout(30000) .build(); ChatCompletions client = new ChatCompletions( "https://api.example.com", options ); ``` -------------------------------- ### Conversation Stream Call with React IO Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/README.md Example of making a streaming conversation call using `streamCall` and processing results with RxJava's Flowable. ```java import com.alibaba.dashscope.aigc.conversation.Conversation; import com.alibaba.dashscope.aigc.conversation.ConversationResult; import com.alibaba.dashscope.aigc.conversation.qwen.QWenConversationParam; import com.alibaba.dashscope.common.StreamingMode; import com.alibaba.dashscope.utils.JsonUtils; import io.reactivex.Flowable; public class Main { public static void main(String[] args) { Conversation conversation = new Conversation(); //QWEN model, if using other model, you can replace the QWenConversationParam here. QWenConversationParam param = QWenConversationParam.builder().model(QWenConversationParam.QWEN_TURBO).prompt("hello") .mode(StreamingMode.OUT) .apiKey("testKey") .build(); Flowable flowable = conversation.streamCall(param); try { flowable.blockingForEach(msg -> System.out.println(JsonUtils.toJson(msg))); } catch (Throwable e) { // TODO deal with error here } } } ``` -------------------------------- ### Custom Connection Options Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/QUICK_REFERENCE.md Shows how to configure custom connection timeouts, proxy settings, and other options. ```java ConnectionOptions opts = ConnectionOptions.builder() .connectTimeout(Duration.ofSeconds(30)) .readTimeout(Duration.ofSeconds(120)) .proxyHost("proxy.company.com") .proxyPort(8080) .build(); Generation gen = new Generation(Protocol.HTTP.getValue(), null, opts); ``` -------------------------------- ### Setting Up HTTP Proxy via Environment Variables Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/configuration.md Configures HTTP proxy settings using environment variables for host and port. ```bash export DASHSCOPE_PROXY_HOST="proxy.company.com" export DASHSCOPE_PROXY_PORT="8080" ``` -------------------------------- ### Set API Key via Environment Variable Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/configuration.md Demonstrates how to set the DashScope API key using an environment variable for enhanced security. ```bash export DASHSCOPE_API_KEY="your-key" ``` -------------------------------- ### Function Calling Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/QUICK_REFERENCE.md Demonstrates how to define tools and use them for function calling with the generation API. ```java List tools = List.of( // Define tool schemas... ); GenerationParam param = GenerationParam.builder() .model("qwen-turbo") .messages(messages) .tools(tools) .apiKey("key") .build(); GenerationResult result = generation.call(param); if (result.getOutput().getChoices().get(0).getMessage().getToolCalls() != null) { // Handle tool calls } ``` -------------------------------- ### Setting Up HTTP Proxy via ConnectionOptions Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/configuration.md Configures HTTP proxy settings directly within the ConnectionOptions builder. ```java ConnectionOptions options = ConnectionOptions.builder() .proxyHost("proxy.company.com") .proxyPort(8080) .build(); Generation generation = new Generation( Protocol.HTTP.getValue(), null, options ); ``` -------------------------------- ### Enable Logging Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/QUICK_REFERENCE.md Enables DEBUG level logging for the SDK using SLF4J. ```java // SLF4J is used; configure your logging provider System.setProperty("slf4j.simpleLogger.defaultLogLevel", "DEBUG"); ``` -------------------------------- ### Error Handling Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/QUICK_REFERENCE.md Demonstrates how to catch and handle various exceptions that may occur during API calls. ```java try { GenerationResult result = generation.call(param); } catch (NoApiKeyException e) { System.err.println("API key required"); } catch (InputRequiredException e) { System.err.println("Missing parameter: " + e.getMessage()); } catch (ApiException e) { int code = e.getStatus().getStatusCode(); if (code == 429) System.err.println("Rate limited"); else if (code == 500) System.err.println("Server error"); } ``` -------------------------------- ### Constructor with Protocol Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/api-reference/generation.md Creates a Generation client with specified protocol. ```java public Generation(String protocol) ``` ```java import com.alibaba.dashscope.protocol.Protocol; Generation generation = new Generation(Protocol.HTTP.getValue()); ``` -------------------------------- ### Conversation Client Initialization Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/README.md Initialize a Conversation client using the default HTTP protocol. ```java // Use http as the network protocol. Conversation conversation = new Conversation(); ``` -------------------------------- ### Constructor with Advanced Connection Options Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/api-reference/generation.md Creates a Generation client with advanced connection configuration. ```java public Generation(String protocol, String baseUrl, ConnectionOptions connectionOptions) ``` ```java ConnectionOptions options = ConnectionOptions.builder() .readTimeout(30000) .connectionTimeout(10000) .build(); Generation generation = new Generation( Protocol.HTTP.getValue(), "https://api.example.com", options ); ``` -------------------------------- ### Comprehensive Error Handling Pattern Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/errors.md Demonstrates how to handle various exceptions thrown by the generation call, including configuration, validation, and general API errors. ```java public class ApiErrorHandler { public void handleGenerationCall(GenerationParam param) { try { GenerationResult result = generation.call(param); System.out.println("Success: " + result.getOutput().getText()); } catch (NoApiKeyException e) { System.err.println("Configuration error: API key not found"); System.err.println("Set DASHSCOPE_API_KEY or provide apiKey parameter"); } catch (InputRequiredException e) { System.err.println("Validation error: " + e.getMessage()); System.err.println("Check required parameters: model, prompt, apiKey"); } catch (ApiException e) { Status status = e.getStatus(); int httpCode = status.getStatusCode(); String code = status.getCode(); switch (httpCode) { case 401: case 403: System.err.println("Auth error: Invalid API key"); break; case 429: System.err.println("Rate limited: " + status.getMessage()); System.err.println("Wait before retrying"); break; case 500: case 502: case 503: System.err.println("Server error: " + status.getMessage()); System.err.println("Request ID: " + status.getRequestId()); break; default: System.err.println("API error: " + status.getMessage()); } } } } ``` -------------------------------- ### Constructor with Protocol and Base URL Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/api-reference/generation.md Creates a Generation client with custom protocol and base URL. ```java public Generation(String protocol, String baseUrl) ``` ```java Generation generation = new Generation( Protocol.HTTP.getValue(), "https://api.example.com" ); ``` -------------------------------- ### Conversation Client Initialization with Protocol Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/README.md Initialize a Conversation client specifying the network protocol (HTTP or WebSocket). ```java import com.alibaba.dashscope.common.Protocol; Conversation conversation = new Conversation(Protocol.HTTP.getValue()); Conversation conversation = new Conversation(Protocol.WEBSOCKET.getValue()); ``` -------------------------------- ### Multi-turn Conversation Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/QUICK_REFERENCE.md Illustrates how to manage and send messages for a multi-turn conversational interaction. ```java List messages = new ArrayList<>(); messages.add(Message.builder().role("user").content("Hi").build()); messages.add(Message.builder().role("assistant").content("Hello!").build()); messages.add(Message.builder().role("user").content("Who are you?").build()); GenerationParam param = GenerationParam.builder() .model("qwen-turbo") .messages(messages) .apiKey("key") .build(); GenerationResult result = generation.call(param); ``` -------------------------------- ### Get Request ID from Error Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/QUICK_REFERENCE.md Retrieves the request ID from an ApiException for debugging purposes. ```java try { generation.call(param); } catch (ApiException e) { String requestId = e.getStatus().getRequestId(); System.out.println("Request ID: " + requestId); } ``` -------------------------------- ### QwenTtsRealtime Constructor Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/api-reference/audiotts.md Creates an instance of QwenTtsRealtime for real-time streaming TTS. ```java public QwenTtsRealtime(QwenTtsRealtimeConfig config) ``` -------------------------------- ### Chat Completions (OpenAI Compatible) - Streaming Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/QUICK_REFERENCE.md Streaming chat completions using the DashScope Java SDK. ```java Flowable stream = client.streamCall(param); stream.blockingForEach(chunk -> { String delta = chunk.getChoices().get(0).getDelta().getContent(); System.out.print(delta); }); ``` -------------------------------- ### call(ChatCompletionParam param, ResultCallback callback) Method Example Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/api-reference/chatcompletions.md Performs a non-blocking call with callback-based result handling. ```java import com.alibaba.dashscope.common.ResultCallback; client.call(param, new ResultCallback() { @Override public void onEvent(ChatCompletion result) { String message = result.getChoices().get(0).getMessage().getContent(); System.out.println("Received: " + message); } @Override public void onComplete() { System.out.println("Request completed"); } @Override public void onError(Exception e) { System.err.println("Error: " + e.getMessage()); } }); ``` -------------------------------- ### call(ConversationParam param) Method Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/api-reference/conversation.md Performs a synchronous call to get the complete result without streaming. ```java public ConversationResult call(ConversationParam param) throws ApiException, NoApiKeyException, InputRequiredException ``` ```java import com.alibaba.dashscope.aigc.conversation.Conversation; import com.alibaba.dashscope.aigc.conversation.ConversationResult; import com.alibaba.dashscope.aigc.conversation.qwen.QWenConversationParam; Conversation conversation = new Conversation(); QWenConversationParam param = QWenConversationParam.builder() .model(QWenConversationParam.QWEN_TURBO) .prompt("Hello, how are you?") .apiKey("your-api-key") .build(); try { ConversationResult result = conversation.call(param); System.out.println(result.getOutput().getText()); } catch (Exception e) { e.printStackTrace(); } ``` -------------------------------- ### Default Constructor Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/api-reference/generation.md Creates a Generation client with default HTTP protocol and standard service options. ```java public Generation() ``` ```java Generation generation = new Generation(); ``` -------------------------------- ### Environment Variable Configuration Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/README.md Setting API key and read timeout using environment variables. ```bash export DASHSCOPE_API_KEY="key" export DASHSCOPE_READ_TIMEOUT="120" ``` -------------------------------- ### Text Generation (Primary) - Streaming (Callback) Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/QUICK_REFERENCE.md Streaming text generation using a callback in the DashScope Java SDK. ```java gen.streamCall(param, new ResultCallback() { public void onEvent(GenerationResult r) { /* handle */ } public void onComplete() { /* done */ } public void onError(Exception e) { /* error */ } }); ``` -------------------------------- ### HttpSpeechSynthesizer Constructor Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/api-reference/audiotts.md Creates a new HttpSpeechSynthesizer instance with default settings. ```java public HttpSpeechSynthesizer(){ } ``` ```java HttpSpeechSynthesizer synthesizer = new HttpSpeechSynthesizer(); ``` -------------------------------- ### API Classes and Imports Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/QUICK_REFERENCE.md Imports for various API classes in the DashScope Java SDK, including Text Generation, Chat Completion, Text Embedding, Image Generation, Text Reranking, and common types. ```java // Text Generation import com.alibaba.dashscope.aigc.generation.Generation; import com.alibaba.dashscope.aigc.generation.GenerationParam; import com.alibaba.dashscope.aigc.generation.GenerationResult; // Chat Completion import com.alibaba.dashscope.aigc.completion.ChatCompletions; import com.alibaba.dashscope.aigc.completion.ChatCompletionParam; import com.alibaba.dashscope.aigc.completion.ChatCompletion; // Text Embedding import com.alibaba.dashscope.embeddings.TextEmbedding; import com.alibaba.dashscope.embeddings.TextEmbeddingParam; import com.alibaba.dashscope.embeddings.TextEmbeddingResult; // Image Generation import com.alibaba.dashscope.aigc.imagegeneration.ImageGeneration; import com.alibaba.dashscope.aigc.imagegeneration.ImageGenerationParam; import com.alibaba.dashscope.aigc.imagegeneration.ImageGenerationResult; // Text Reranking import com.alibaba.dashscope.rerank.TextReRank; import com.alibaba.dashscope.rerank.TextReRankParam; import com.alibaba.dashscope.rerank.TextReRankResult; // Common Types import com.alibaba.dashscope.common.Message; import com.alibaba.dashscope.common.Role; import com.alibaba.dashscope.common.ResultCallback; import com.alibaba.dashscope.exception.ApiException; import com.alibaba.dashscope.exception.NoApiKeyException; import com.alibaba.dashscope.exception.InputRequiredException; ``` -------------------------------- ### ConnectionOptions Class Definition Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/configuration.md Definition of the ConnectionOptions class for advanced network and connection configuration. ```java public final class ConnectionOptions { Duration connectTimeout; Duration writeTimeout; Duration readTimeout; String proxyHost; Integer proxyPort; Authenticator proxyAuthenticator; boolean useDefaultClient; } ``` -------------------------------- ### Check Response Structure Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/QUICK_REFERENCE.md Prints details from the GenerationResult, including request ID, token usage, and output text. ```java GenerationResult result = generation.call(param); System.out.println("Request ID: " + result.getRequestId()); System.out.println("Input tokens: " + result.getUsage().getInputTokens()); System.out.println("Output tokens: " + result.getUsage().getOutputTokens()); System.out.println("Text: " + result.getOutput().getText()); ``` -------------------------------- ### Conversation() Constructor Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/api-reference/conversation.md Creates a Conversation client with default HTTP protocol and default API service options. ```java public Conversation() ``` ```java Conversation conversation = new Conversation(); ``` -------------------------------- ### Maven Dependency Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/README.md Add Maven dependency to your project. ```xml com.alibaba dashscope-sdk-java 2.22.18 ``` -------------------------------- ### Version Information Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/README.md SDK version and target Java version. ```text - SDK Version: 2.22.18 - Java Target: 1.8+ - Key Dependencies: - RxJava 2 (for streaming) - OkHttp 4.12 (for HTTP) - Gson 2.8.9 (for JSON) - Lombok 1.18.26 (for code generation) ``` -------------------------------- ### Text Generation (Primary) - Streaming (Flowable) Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/QUICK_REFERENCE.md Streaming text generation using Flowable in the DashScope Java SDK. ```java Flowable stream = gen.streamCall(param); stream.blockingForEach(result -> System.out.print(result.getOutput().getText()) ); ``` -------------------------------- ### Check API Key Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/QUICK_REFERENCE.md Command to check if the DASHSCOPE_API_KEY environment variable is set. ```bash echo $DASHSCOPE_API_KEY ``` -------------------------------- ### Conversation(String protocol) Constructor Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/api-reference/conversation.md Creates a Conversation client with specified protocol. ```java public Conversation(String protocol) ``` ```java import com.alibaba.dashscope.common.Protocol; Conversation conversation = new Conversation(Protocol.HTTP.getValue()); ``` -------------------------------- ### Conversation(String protocol, String baseUrl, ConnectionOptions connectionOptions) Constructor Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/api-reference/conversation.md Creates a Conversation client with protocol, base URL, and connection options. ```java public Conversation(String protocol, String baseUrl, ConnectionOptions connectionOptions) ``` ```java ConnectionOptions options = ConnectionOptions.builder() .readTimeout(30000) .build(); Conversation conversation = new Conversation( Protocol.HTTP.getValue(), "https://api.example.com", options ); ``` -------------------------------- ### Connection Options Configuration Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/README.md Setting read timeout using ConnectionOptions builder. ```java ConnectionOptions opts = ConnectionOptions.builder() .readTimeout(Duration.ofSeconds(120)) .build(); ``` -------------------------------- ### Conversation(String protocol, String baseUrl) Constructor Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/api-reference/conversation.md Creates a Conversation client with specified protocol and base URL. ```java public Conversation(String protocol, String baseUrl) ``` ```java Conversation conversation = new Conversation( Protocol.HTTP.getValue(), "https://custom-api.example.com" ); ``` -------------------------------- ### Retry with Backoff Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/QUICK_REFERENCE.md Implements a retry mechanism with exponential backoff for handling API errors like rate limiting. ```java int maxRetries = 3; long baseDelay = 1000; for (int i = 0; i < maxRetries; i++) { try { return generation.call(param); } catch (ApiException e) { if (e.getStatus().getStatusCode() == 429 && i < maxRetries - 1) { Thread.sleep(baseDelay * (1 << i)); } else { throw e; } } } ``` -------------------------------- ### Request Parameters Configuration Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/README.md Setting API key directly in GenerationParam. ```java GenerationParam param = GenerationParam.builder() .apiKey("explicit-key") .build(); ``` -------------------------------- ### Set API Key Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/README.md Set API key via environment variable for authentication. ```bash export DASHSCOPE_API_KEY="your-api-key" ``` -------------------------------- ### Streaming Error Handling with Callbacks Source: https://github.com/dashscope/dashscope-sdk-java/blob/main/_autodocs/errors.md Illustrates error handling for streaming operations using a ResultCallback interface. ```java generation.streamCall(param, new ResultCallback() { @Override public void onEvent(GenerationResult result) { System.out.print(result.getOutput().getText()); } @Override public void onComplete() { System.out.println("Stream complete"); } @Override public void onError(Exception e) { if (e instanceof ApiException) { ApiException apiError = (ApiException) e; System.err.println("Error: " + apiError.getStatus().getCode()); } else { System.err.println("Error: " + e.getMessage()); } } }); ```