diff --git a/.dev_tools/google-java-format-1.16.0-all-deps.jar b/.dev_tools/google-java-format-1.16.0-all-deps.jar new file mode 100644 index 00000000..167f461e Binary files /dev/null and b/.dev_tools/google-java-format-1.16.0-all-deps.jar differ diff --git a/.dev_tools/google-java-format-1.7-all-deps.jar b/.dev_tools/google-java-format-1.7-all-deps.jar deleted file mode 100644 index e2d40de4..00000000 Binary files a/.dev_tools/google-java-format-1.7-all-deps.jar and /dev/null differ diff --git a/.dev_tools/run_ci.sh b/.dev_tools/run_ci.sh index a2338057..d247f3c2 100644 --- a/.dev_tools/run_ci.sh +++ b/.dev_tools/run_ci.sh @@ -1,5 +1,18 @@ #!/bin/bash +# Guard the 3.0 root-package layout: the com.alibaba.dashscope.v3 intermediate packages and +# the root common leaf were eliminated by the package finalization. A stale pre-migration copy +# re-added under them slips through a merge with zero conflict signal (the merge base usually +# lacks the path) and breaks the build against classes that no longer exist, so fail fast here +# before the format loop and mvn package spend minutes on it. +STALE_LAYOUT_FILES=$(find src -type f -name "*.java" 2>/dev/null | grep -E "^src/(main|test)/java/com/alibaba/dashscope/(v3|common)/" || true) +if [ -n "$STALE_LAYOUT_FILES" ]; then + echo "Found files under eliminated packages (com.alibaba.dashscope.v3 / root common):" + echo "$STALE_LAYOUT_FILES" + echo "The 3.0 layout owns the root packages; drop the stale copy or move the code there." + exit 1 +fi + # get all java files FILES_TO_CHECK=$(find . -type f -name "*.java" | grep "./*/src/.*java") @@ -8,7 +21,7 @@ HAS_CHANGES=false for FILE in $FILES_TO_CHECK; do echo "Checking file: $FILE" - java -jar .dev_tools/google-java-format-1.7-all-deps.jar $FILE | diff $FILE - + java -jar .dev_tools/google-java-format-1.16.0-all-deps.jar $FILE | diff $FILE - if [ $? -ne 0 ]; then echo "File $FILE has changes after formatting." HAS_CHANGES=true diff --git a/.github/workflows/build-and-test.yml b/.github/workflows/build-and-test.yml index e45bec81..2e3838b8 100644 --- a/.github/workflows/build-and-test.yml +++ b/.github/workflows/build-and-test.yml @@ -30,6 +30,9 @@ on: workflow_dispatch: # Allow manual trigger env: + # JDK 8 toolchain end to end: javac 8 lacks the --release flag and its JVM rejects + # --add-opens, so the pom defaults to source/target 8 and the jdk9-plus profile covers + # newer JDKs (release 8 API checking + junit-pioneer test opens). JAVA_VERSION: '8' JAVA_DISTRIBUTION: 'temurin' @@ -41,36 +44,82 @@ jobs: runs-on: ubuntu-22.04 steps: - name: Checkout code - uses: actions/checkout@v4 + uses: actions/checkout@v5 + + # The com.alibaba.dashscope.v3 intermediate packages and the root common leaf were + # eliminated by the 3.0 package finalization. A stale pre-migration copy re-added under + # them slips through a merge with zero conflict signal (the merge base usually lacks + # the path) and breaks the build against classes that no longer exist, so fail fast + # before Maven spends minutes drowning the cause in compiler errors. + - name: Guard eliminated packages + run: | + stale=$(find src -type f -name "*.java" 2>/dev/null \ + | grep -E "^src/(main|test)/java/com/alibaba/dashscope/(v3|common)/" || true) + if [ -n "$stale" ]; then + echo "::error::Found files under eliminated packages (com.alibaba.dashscope.v3 / root common): the 3.0 layout owns the root packages; drop the stale copy or move the code there." + echo "$stale" + exit 1 + fi - name: Set up JDK ${{ env.JAVA_VERSION }} - uses: actions/setup-java@v4 + uses: actions/setup-java@v5 with: java-version: ${{ env.JAVA_VERSION }} distribution: ${{ env.JAVA_DISTRIBUTION }} cache: 'maven' + # Both the 3.0 tokenization.QwenTokenizer and legacy_2x QwenTokenizer fall back to a + # single-attempt ModelScope download when the verified cache is missing; pre-seed it here + # with retries so tests never depend on a flaky runtime fetch. + - name: Pre-download Qwen tokenizer vocab + run: | + vocab_dir="$HOME/.cache/dashscope/tokenizers" + vocab="$vocab_dir/qwen.tiktoken" + sha256="b2b1b8dfb5cc5f024bafc373121c6aba3f66f9a5a0269e243470a1de16a33186" + url="https://www.modelscope.cn/models/Qwen/Qwen-7B-Chat/resolve/master/qwen.tiktoken" + mkdir -p "$vocab_dir" + for attempt in 1 2 3; do + if curl -fsSL --connect-timeout 30 --max-time 300 --retry 3 --retry-delay 5 \ + -o "$vocab" "$url" && [ "$(sha256sum "$vocab" | cut -d' ' -f1)" = "$sha256" ]; then + echo "Vocab cached at $vocab" + exit 0 + fi + echo "Vocab download attempt $attempt failed, retrying..." + sleep 10 + done + echo "::error::Failed to download qwen.tiktoken from ModelScope after 3 attempts" + exit 1 + - name: Run tests run: mvn clean test env: DASHSCOPE_API_KEY: ${{ secrets.DASHSCOPE_API_KEY }} + # examples/ is a standalone Maven project, so install this checkout's SDK first. + - name: Install current SDK for examples + run: mvn install -DskipTests -Dgpg.skip=true + + - name: Run examples dry-run tests + run: mvn -f examples/pom.xml clean test + - name: Upload test results if: always() uses: actions/upload-artifact@v4 with: name: test-results - path: target/surefire-reports/ + path: | + target/surefire-reports/ + examples/target/surefire-reports/ build: runs-on: ubuntu-22.04 needs: [test] steps: - name: Checkout code - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: Set up JDK ${{ env.JAVA_VERSION }} - uses: actions/setup-java@v4 + uses: actions/setup-java@v5 with: java-version: ${{ env.JAVA_VERSION }} distribution: ${{ env.JAVA_DISTRIBUTION }} diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml new file mode 100644 index 00000000..7f1f0ef3 --- /dev/null +++ b/.github/workflows/docs.yml @@ -0,0 +1,100 @@ +name: 📚 Docs + +on: + push: + branches: [main, master] + paths: + - 'docs/**' + - 'examples/**' + - 'mkdocs.yml' + - 'requirements-doc.txt' + - 'src/main/java/**' + - 'pom.xml' + - '.github/workflows/docs.yml' + pull_request: + branches: [main, master] + paths: + - 'docs/**' + - 'examples/**' + - 'mkdocs.yml' + - 'requirements-doc.txt' + - 'src/main/java/**' + - 'pom.xml' + - '.github/workflows/docs.yml' + workflow_dispatch: + release: + types: [published] + +permissions: + contents: read + +concurrency: + group: docs-${{ github.ref }} + cancel-in-progress: false + +jobs: + build: + # On release events the dispatcher below re-runs this workflow on the default + # branch; a tag-ref build could not deploy to Pages anyway. + if: github.event_name != 'release' + runs-on: ubuntu-22.04 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-java@v4 + with: + java-version: '17' + distribution: temurin + cache: maven + - uses: actions/setup-python@v5 + with: + python-version: '3.11' + - name: Install docs dependencies + run: pip install -r requirements-doc.txt + - name: Generate Javadoc (delombok, JDK 17) + run: mvn -Pdocs -DskipTests -Dgpg.skip=true generate-sources javadoc:javadoc + - name: Bridge Javadoc stylesheet toward Material + run: cat docs/javadoc/material-bridge.css >> target/apidocs/stylesheet.css + - name: Build site (strict) + run: python -m mkdocs build --strict + env: + # Lifts the anonymous GitHub API rate limit for the recent-releases + # table ({{ release_notes }}); the data itself is public. + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + - name: Attach Javadoc under /api/ + run: | + mkdir -p site/api + cp -R target/apidocs/. site/api/ + - uses: actions/upload-pages-artifact@v3 + if: github.event_name != 'pull_request' && (github.ref == 'refs/heads/main' || github.ref == 'refs/heads/master') + with: + path: site + + deploy: + if: github.event_name != 'pull_request' && github.event_name != 'release' && (github.ref == 'refs/heads/main' || github.ref == 'refs/heads/master') + needs: build + runs-on: ubuntu-22.04 + permissions: + pages: write + id-token: write + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + concurrency: + group: github-pages + cancel-in-progress: false + steps: + - id: deployment + uses: actions/deploy-pages@v4 + + # A published release should refresh the site from the default branch (the release + # event itself carries a tag ref, which the deploy job would skip). + dispatch-on-release: + if: github.event_name == 'release' + runs-on: ubuntu-22.04 + permissions: + actions: write + contents: read + steps: + - run: gh workflow run docs.yml --ref main -R "$GITHUB_REPOSITORY" + env: + GH_TOKEN: ${{ github.token }} \ No newline at end of file diff --git a/.github/workflows/linter.yml b/.github/workflows/linter.yml index 9b830460..527a006d 100644 --- a/.github/workflows/linter.yml +++ b/.github/workflows/linter.yml @@ -29,16 +29,16 @@ jobs: linter: runs-on: ubuntu-22.04 steps: - - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - - name: Set up JDK 8 - uses: actions/setup-java@v4 + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + - name: Set up JDK 17 + uses: actions/setup-java@v5 with: - java-version: '8' + java-version: '17' distribution: 'temurin' - name: Check code formatting run: | # Check if any files need formatting - if ! java -jar .dev_tools/google-java-format-1.7-all-deps.jar \ + if ! java -jar .dev_tools/google-java-format-1.16.0-all-deps.jar \ --dry-run --set-exit-if-changed \ $(find . -type f -name "*.java" | grep "./*/src/.*java"); then echo "❌ Code formatting issues found!" diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 00000000..ff15818f --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,70 @@ +name: Release + +on: + push: + tags: ['v*'] + +jobs: + publish: + runs-on: ubuntu-latest + environment: maven-central + permissions: + contents: write + steps: + - uses: actions/checkout@v5 + with: + fetch-depth: 0 + + - name: Tag commit must be on main + run: | + git fetch origin main + git merge-base --is-ancestor "$GITHUB_SHA" origin/main + + - uses: actions/setup-java@v5 + with: + distribution: temurin + java-version: 8 + server-id: central + server-username: CENTRAL_USERNAME + server-password: CENTRAL_PASSWORD + gpg-private-key: ${{ secrets.GPG_PRIVATE_KEY }} + gpg-passphrase: MAVEN_GPG_PASSPHRASE + + - name: Version must match tag + run: | + V=$(mvn -q help:evaluate -Dexpression=project.version -DforceStdout) + test "v$V" = "$GITHUB_REF_NAME" + + - name: Pre-download Qwen tokenizer vocab + run: | + vocab_dir="$HOME/.cache/dashscope/tokenizers" + vocab="$vocab_dir/qwen.tiktoken" + sha256="b2b1b8dfb5cc5f024bafc373121c6aba3f66f9a5a0269e243470a1de16a33186" + url="https://www.modelscope.cn/models/Qwen/Qwen-7B-Chat/resolve/master/qwen.tiktoken" + mkdir -p "$vocab_dir" + for attempt in 1 2 3; do + if curl -fsSL --connect-timeout 30 --max-time 300 --retry 3 --retry-delay 5 \ + -o "$vocab" "$url" && [ "$(sha256sum "$vocab" | cut -d' ' -f1)" = "$sha256" ]; then + echo "Vocab cached at $vocab" + exit 0 + fi + echo "Vocab download attempt $attempt failed, retrying..." + sleep 10 + done + echo "::error::Failed to download qwen.tiktoken from ModelScope after 3 attempts" + exit 1 + + - name: Unit tests + run: mvn -B test + + - name: Deploy to Maven Central + run: mvn -B deploy -DskipTests -DautoPublish=${{ vars.AUTO_PUBLISH || 'false' }} + env: + CENTRAL_USERNAME: ${{ secrets.CENTRAL_USERNAME }} + CENTRAL_PASSWORD: ${{ secrets.CENTRAL_PASSWORD }} + MAVEN_GPG_PASSPHRASE: ${{ secrets.GPG_PASSPHRASE }} + + - name: Create GitHub Release + run: gh release create "$GITHUB_REF_NAME" --generate-notes --title "$GITHUB_REF_NAME" + env: + GH_TOKEN: ${{ github.token }} \ No newline at end of file diff --git a/.gitignore b/.gitignore index 70184495..cfcd99f1 100644 --- a/.gitignore +++ b/.gitignore @@ -169,5 +169,13 @@ cython_debug/ #.idea/ /dashscope-sdk-java.iml /.idea -.acli/ +/md/ settings.xml + +# Qwen tokenizer vocab: fetched from ModelScope at runtime, never commit the +# 2.4MB file (a local copy may be placed here for offline development/tests). +src/main/resources/qwen.tiktoken + +# MkDocs docs site: build output and the locally-copied Javadoc bundle +site/ +docs/api/ diff --git a/DOCS_TEMPLATE.md b/DOCS_TEMPLATE.md new file mode 100644 index 00000000..b41d9e2a --- /dev/null +++ b/DOCS_TEMPLATE.md @@ -0,0 +1,32 @@ +# DashScope SDK documentation template + +Use this template for both the Python and Java sites. Keep the shared navigation, +reader tasks, and section order consistent. Write code, commands, behavior and +prerequisites for the actual SDK. A missing API is a documented difference, not +a reason to invent an equivalent. Keep existing public paths when relabeling +or moving pages in the menu. Every new reader-facing page ships in English and +Simplified Chinese with links to the same-language guides and reference. + +| Menu | Shared page structure | +| --- | --- | +| Home | Explain what the SDK does; show version and minimum runtime; link Quickstart, Examples and API key; show capability highlights and a short usage flow. | +| Features | Use the same capability → SDK entry point → guide table: chat, multimodal, embeddings/rerank, media generation, audio/meetings, files/models/fine-tuning, AgentStudio, tokenization, apps/decision. Follow with sync/async, streaming, protocols, configuration, errors, local development, SDK-specific capabilities, and legacy compatibility. | +| Learn | Quickstart (prerequisites, install, configure, first request, streaming, async, errors, next steps) → Migration → Guides. Start Guides with Capability recipes (short calls by task and links to runnable source), then Chat and Streaming, Async Client, Multimodal, Embeddings and Rerank, Images and Videos, Audio, Files and Fine-tuning, AgentStudio, Tokenization, Local Mock Debugging, Errors and Diagnosis, Configuration. Put extra guides after the common group. | +| Reference | API Overview → Client & Configuration, Chat, Audio, Protocols and transport, Client Resources, AgentStudio, Types, Errors, Devkit, Legacy API. Describe the actual wire protocols and transports for each SDK. Put SDK-only APIs after shared categories. Link to generated signatures instead of duplicating them by hand. | +| Resources | Examples → Developer Guide → Help & Issues. The examples hub starts with offline and live run paths, then maps tasks to source and guides, then explains engineering, agent and scenario patterns. The developer guide covers setup, checks, and docs preview. | +| About | Project and links → License → Compatibility and versioning → Getting help. Add SDK-specific implementation details where useful. | +| Release Notes | Identify the version of the source used to build the docs, link published releases, show recent releases, then stable major-version highlights and legacy policy. Never label historical highlights with a floating version. | + +## Topic guide template + +1. **Choose the API:** state the task and how to select the right resource. +2. **Run a minimal workflow:** show a small code example or direct runnable + command; list inputs, credentials and any cloud or hardware requirements. +3. **Explain the result and boundaries:** show what to read, how to handle + failures or task IDs, and note sync-only or other SDK-specific behavior. +4. **Keep exploring:** link to the maintained example source and generated API + reference. Embed existing source with checked snippets when useful. + +Before merging: build both locales in strict mode; verify new example paths +and run offline smoke examples if their instructions changed. Change this +template and its peer copy together when the shared structure changes. diff --git a/README.md b/README.md index bee11a6a..f862dd52 100644 --- a/README.md +++ b/README.md @@ -1,20 +1,322 @@ -# dashscope-sdk-java +# DashScope Java SDK -This is the java sdk for the DashScope models. +[![Maven Central](https://img.shields.io/maven-central/v/com.alibaba/dashscope-sdk-java.svg)](https://central.sonatype.com/artifact/com.alibaba/dashscope-sdk-java) +[![Build and Test](https://github.com/dashscope/dashscope-sdk-java/actions/workflows/build-and-test.yml/badge.svg)](https://github.com/dashscope/dashscope-sdk-java/actions/workflows/build-and-test.yml) +[![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](LICENSE) -## Usage +English | [中文](README_zh.md) -To use the sdk in your java systems, please add the maven dependency in your pom.xml: +Documentation site: — bilingual guides, +2.x migration notes and generated API docs. + +The Java SDK for [DashScope](https://dashscope.aliyuncs.com) models (Alibaba Cloud Model Studio). +This repository is on the **3.0 generation**: a single `DashScopeClient` entry point with a typed +resource tree, blocking SSE streaming, and an async mirror returning `CompletableFuture` / +RxJava `Flowable`. **Java 8+** is required at runtime. + +> Upgrading from 2.x? The old APIs moved to `com.alibaba.dashscope.legacy_2x.*` and are deprecated +> for removal in 4.0 — see [Migrating from 2.x](#migrating-from-2x). Legacy documentation is kept +> in the [appendix](#legacy-2x-api-deprecated) at the end of this file. + +## Installation ```xml com.alibaba dashscope-sdk-java - {dashscope-sdk-java-version} + 3.0.0 ``` -## QuickStart +## Quick Start + +Set your API key first: `export DASHSCOPE_API_KEY=sk-...` (get one from the +[Model Studio console](https://bailian.console.aliyun.com/)). + +### Synchronous + +```java +import com.alibaba.dashscope.DashScopeClient; +import com.alibaba.dashscope.types.completions.ChatCompletion; +import com.alibaba.dashscope.types.completions.ChatCompletionCreateParams; +import com.alibaba.dashscope.types.messages.Message; +import java.util.Collections; + +try (DashScopeClient client = DashScopeClient.builder().build()) { + ChatCompletion result = client.chat().completions().create( + ChatCompletionCreateParams.builder() + .model("qwen-plus") + .messages(Collections.singletonList(Message.user("Hello, how are you?"))) + .build()); + System.out.println(result.outputText()); + System.out.println("request_id: " + result.getRequestId()); +} +``` + +### Streaming (SSE) + +`createStreaming` returns a single-use `ResponseStream` — a blocking, typed iterator. Always +close it with try-with-resources so the underlying connection is released. Each chunk's `delta()` +carries the content increment. + +```java +import com.alibaba.dashscope.DashScopeClient; +import com.alibaba.dashscope.types.common.ResponseStream; +import com.alibaba.dashscope.types.completions.ChatCompletionChunk; +import com.alibaba.dashscope.types.completions.ChatCompletionCreateParams; +import com.alibaba.dashscope.types.completions.Delta; +import com.alibaba.dashscope.types.messages.Message; +import java.util.Collections; + +try (DashScopeClient client = DashScopeClient.builder().build()) { + try (ResponseStream stream = client.chat().completions().createStreaming( + ChatCompletionCreateParams.builder() + .model("qwen-plus") + .messages(Collections.singletonList(Message.user("Hello, how are you?"))) + .build())) { + for (ChatCompletionChunk chunk : stream) { + Delta delta = chunk.delta(); + if (delta != null && delta.getContent() != null) { + System.out.print(delta.getContent()); + } + } + } +} +``` + +### Asynchronous + +`DashScopeAsyncClient` mirrors the same resource tree: unary calls return `CompletableFuture`, +streaming returns RxJava `Flowable`. The client owns a daemon executor; try-with-resources shuts +it down. + +```java +import com.alibaba.dashscope.DashScopeAsyncClient; +import com.alibaba.dashscope.types.completions.ChatCompletion; +import com.alibaba.dashscope.types.completions.ChatCompletionCreateParams; +import com.alibaba.dashscope.types.messages.Message; +import java.util.Collections; +import java.util.concurrent.CompletableFuture; + +try (DashScopeAsyncClient client = DashScopeAsyncClient.builder().build()) { + CompletableFuture future = client.chat().completions().create( + ChatCompletionCreateParams.builder() + .model("qwen-plus") + .messages(Collections.singletonList(Message.user("Hello, how are you?"))) + .build()); + future.thenAccept(result -> System.out.println(result.outputText())).join(); + + // Streaming: client.chat().completions().createStreaming(params) returns + // Flowable; consume with blockingForEach or subscribe. +} +``` + +## Configuration + +Every setting in the table below resolves through a config chain: **builder > JVM system +property > environment variable > `~/.dashscope/config.toml` > default** (`wsBaseUrl` has no +config-file key; `raiseOnError`, `httpClient` and `executor` are builder-only). The API key +additionally falls back to the 1.x key file (`DASHSCOPE_API_KEY_FILE_PATH` or +`~/.dashscope/api_key`), so `DashScopeClient.builder().build()` works with just +`DASHSCOPE_API_KEY` exported. + +The config file is a flat `key = value` TOML subset; duration values are in **seconds**: + +```toml +# ~/.dashscope/config.toml +api_key = "sk-..." +base_url = "https://dashscope.aliyuncs.com" +workspace = "llm-xxxx" +region = "cn-beijing" +timeout = 300 # seconds +max_retries = 2 +ws_ping_interval = 0 # seconds, 0 = off +``` + +Client-level options (`DashScopeClient.builder()` / `DashScopeAsyncClient.builder()`): + +| Builder method | Environment variable | Default | Description | +|---|---|---|---| +| `apiKey(...)` | `DASHSCOPE_API_KEY` | — | API key (config chain above) | +| `baseUrl(...)` | `DASHSCOPE_BASE_URL` / `DASHSCOPE_HTTP_BASE_URL` | region endpoint | HTTP base URL | +| `wsBaseUrl(...)` | `DASHSCOPE_WEBSOCKET_BASE_URL` | region endpoint | WebSocket base URL | +| `workspace(...)` | `DASHSCOPE_WORKSPACE` | — | Workspace id (required by some APIs, e.g. decision) | +| `region(...)` | `DASHSCOPE_REGION` | `cn-beijing` | MaaS gateway region | +| `timeout(...)` | `DASHSCOPE_TIMEOUT` | 5 minutes | Single-request timeout (`Duration`) | +| `maxRetries(...)` | `DASHSCOPE_MAX_RETRIES` | 2 | Automatic retries on retryable failures | +| `raiseOnError(...)` | — | `true` | `false` switches to 2.x-style `isError()` returns | +| `wsPingInterval(...)` | `DASHSCOPE_WS_PING_INTERVAL` | 0 (off) | WebSocket keepalive ping; 20–30 s behind NAT/proxies | +| `httpClient(...)` | — | SDK-owned | Inject your own `OkHttpClient` (you own its lifecycle) | +| `executor(...)` | — | SDK-owned | Inject the async executor (you own its lifecycle) | + +Per-call overrides: every resource method has a `(params, RequestOptions)` overload. Null fields +inherit the client config. + +```java +import com.alibaba.dashscope.RequestOptions; +import java.time.Duration; + +RequestOptions options = RequestOptions.builder() + .timeout(Duration.ofSeconds(30)) + .maxRetries(0) + .header("X-Custom-Header", "value") + .enableEncryption(true) // DashScope encrypted HTTP channel for this call + .build(); +// client.chat().completions().create(params, options); +``` + +`RequestOptions` supports `timeout`, `maxRetries`, `apiKey`, `workspace`, extra `headers`, +`enableEncryption`, and `wsQueueCapacity` (bounded WebSocket event buffering). + +HTTP wire logging (environment variable only): set `DASHSCOPE_NETWORK_LOGGING_LEVEL` to `BASIC`, +`HEADERS`, or `BODY` (default `NONE`). Credential headers are always redacted. + +Telemetry opt-out: set `DASHSCOPE_DISABLE_SDK_HEADERS=1` (or `true`) to drop the +`x-dashscope-sdk-client` / `x-dashscope-sdk-session-id` tracking headers; `User-Agent` and +caller-set headers are unaffected. + +## Capabilities + +One entry point per capability on `client.` — each links to a minimal runnable example +(full index and run commands: [examples/README.md](examples/README.md)): + +| Resource | API path | Example | +|---|---|---| +| Chat | `chat().completions().create / createStreaming` | [ChatCompletionsCreate](examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/chat/ChatCompletionsCreate.java) | +| Multimodal | `multimodal().chat().create / createStreaming` | [MultimodalChatCreate](examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/multimodal/MultimodalChatCreate.java) | +| Applications | `apps().completions().create / createStreaming` | [AppsCompletionsCreate](examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/apps/AppsCompletionsCreate.java) | +| Image generation | `images().generate / jobs().create / wait / fetch` | [ImagesGenerate](examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/images/ImagesGenerate.java) | +| Video generation | `videos().generate / jobs().*` | [VideosGenerate](examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/videos/VideosGenerate.java) | +| Embeddings | `embeddings().create` | [EmbeddingsCreate](examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/embeddings/EmbeddingsCreate.java) | +| Rerank | `rerank().create` | [RerankCreate](examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/rerank/RerankCreate.java) | +| Token counting | `tokenization().count` | [TokenizationCount](examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/chat/TokenizationCount.java) | +| Speech recognition / synthesis | `audio().asr() / tts() / voices() / realtime()` | [audio examples](examples/README.md#01-atomic-capabilities-audio-omit-the-atomicaudio-prefix) | +| Fine-tuning | `fineTunes().list / get / create` | [FineTunesCreate](examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/finetunes/FineTunesCreate.java) | +| Deployments | `deployments().list / get / create` | [DeploymentsManage](examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/deployments/DeploymentsManage.java) | +| Files | `files().upload / list / get / delete` | [FilesManage](examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/files/FilesManage.java) | +| Models | `models().list / get` | [ModelsList](examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/models/ModelsList.java) | +| TingWu | `tingwu().jobs().create / wait` | [TingWuJobsCreate](examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/audio/TingWuJobsCreate.java) | +| Decision model | `decision().create` | [DecisionCreate](examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/decision/DecisionCreate.java) | +| AgentStudio | `agentStudio()`: environments / agents / sessions / events | [AgentStudioQuickStart](examples/03_agent_recipes/com/alibaba/dashscope/examples/recipes/agentstudio/AgentStudioQuickStart.java) | + +Also available: `client.wsConnection()` for multiplexing several audio tasks over one WebSocket +([AudioConnectionReuse](examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/audio/AudioConnectionReuse.java)), +and `TokenizerFactory.qwen()` for offline local BPE tokenization without an API key +([TokenizationLocalCount](examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/chat/TokenizationLocalCount.java)). + +## Error Handling + +3.0 throws **unchecked** exceptions rooted at `com.alibaba.dashscope.errors.DashScopeException` +(a `RuntimeException`) — no more checked `ApiException / NoApiKeyException / InputRequiredException`. +Each exception carries `code`, `statusCode`, `requestId`, `body`, and response `headers`. + +- HTTP-status errors: `BadRequestException` (400), `AuthenticationException` (401), + `PermissionDeniedException` (403), `NotFoundException` (404), `RequestTooLargeException` (413), + `RateLimitException` (429), `InternalServerException` (500), `ServiceUnavailableException`, + `GatewayTimeoutException`, and the generic `ApiStatusException`. +- Transport errors: `ApiConnectionException`, `ApiTimeoutException`. +- Business error codes (e.g. content filtering): `ContentFilterException` and other + `DashScopeException` subclasses mapped by `Errors`. +- SDK-side misuse: `SdkException` / `IllegalArgumentException`. + +Prefer the 2.x style of inspecting errors on the result? Build the client with +`raiseOnError(false)`: calls then return normally and `result.isError()` (plus `getCode()` / +`getMessage()`) reports business failures. In-stream error frames surface as a final +error-carrying chunk instead of throwing. + +## Migrating from 2.x + +3.0 is an intentional FQCN, source, and binary compatibility break. Legacy 2.x APIs other than +AgentStudio moved to `com.alibaba.dashscope.legacy_2x.*`, carry type-level `@Deprecated` +(`-Xlint:deprecation` shows details), and will be removed in 4.0. AgentStudio +(`com.alibaba.dashscope.applications.agentstudio.*`) and `shared` are not deprecated. + +| 2.x class (`com.alibaba.dashscope.*`) | 3.0 equivalent (`client.*`) | +|---|---| +| `aigc.generation.Generation` | `chat().completions().create / createStreaming` | +| `aigc.multimodalconversation.MultiModalConversation` | `multimodal().chat().create / createStreaming` | +| `embeddings.TextEmbedding` / `BatchTextEmbedding` | `embeddings().create` | +| `rerank.TextReRank` | `rerank().create` | +| `aigc.imagesynthesis.ImageSynthesis` | `images().generate` + `jobs().create / wait / fetch` | +| `aigc.videosynthesis.VideoSynthesis` | `videos().generate` + `jobs().*` | +| `app.Application` | `apps().completions().create / createStreaming` | +| `decision.DecisionModel` | `decision().create` | +| `audio.asr.*` / `audio.tts.*` / `audio.qwen_tts_realtime.*` | `audio().asr() / tts() / realtime()` | +| `multimodal.tingwu.TingWu` | `tingwu().jobs().create / wait` | +| `tokenizers.*` | `tokenization().count` / `TokenizerFactory` | +| `assistants.*` / `threads.*` | no 3.0 equivalent yet — keep the `legacy_2x` imports | + +Key behavior changes: + +- **Exceptions**: checked `ApiException` family → unchecked `DashScopeException` family + (see [Error Handling](#error-handling)); `raiseOnError(false)` restores result-style errors. +- **Streaming**: sync `streamCall` returning `Flowable` → `createStreaming` returning a typed + `ResponseStream` (for-each, try-with-resources). The async client still exposes `Flowable`. +- **Client lifecycle**: per-capability `new Generation()` objects → one `DashScopeClient` + (or `DashScopeAsyncClient`) in try-with-resources, sharing connection pool and config. +- **AgentStudio**: same business package, new FQCN + `com.alibaba.dashscope.applications.agentstudio.*`; also reachable via `client.agentStudio()`. + The 3.0 `baseUrl` does not apply to AgentStudio; `DASHSCOPE_AGENTSTUDIO_URL` overrides its + endpoint. + +The deprecated 2.x quick-start documentation (callback / `Flowable` / non-stream `Generation` +usage, legacy `DecisionModel` endpoint rules) is preserved in the +[legacy appendix](#legacy-2x-api-deprecated); archived 2.x samples are in +[examples/legacy_2x/](examples/legacy_2x/README.md). + +## Examples + +The [examples/](examples/README.md) project is organized in four layers: atomic capabilities, +advanced engineering (retry/circuit breaking, caching, local mock debugging), agent recipes +(tool calling, RAG, AgentStudio), and real-world scenario harnesses. + +```bash +# Install the SDK from this checkout first (examples resolve version 3.0.0) +mvn install -DskipTests -Dgpg.skip=true -Dmaven.javadoc.skip=true + +export DASHSCOPE_API_KEY=sk-... +mvn -q -f examples/pom.xml compile exec:java \ + -Dexec.mainClass=com.alibaba.dashscope.examples.atomic.chat.ChatCompletionsCreate +``` + +Every example also runs offline against MockWebServer (no API key, no charges): + +```bash +mvn -f examples/pom.xml clean test +``` + +## Building from Source + +The build baseline is JDK 8 (CI builds and tests on JDK 8; bytecode target 8). Building on +JDK 9+ also works — the pom's `jdk9-plus` profile auto-activates and compiles with `release 8` +API checking. + +```bash +mvn clean test # unit + mock tests +./lint.sh # google-java-format check (100-column limit) +``` + +## License + +[Apache License 2.0](LICENSE) + +## Legacy 2.x API (deprecated) + +> **Deprecated.** Everything below documents the legacy 2.x API. Since 3.0 these classes live +> under `com.alibaba.dashscope.legacy_2x.*`, carry type-level `@Deprecated`, and will be +> **removed in 4.0**. New code should use the 3.0 client above. + +To keep existing 2.x code compiling on the 3.0 artifact, update imports: + +- `com.alibaba.dashscope.aigc.*`, `com.alibaba.dashscope.embeddings.*`, … → + `com.alibaba.dashscope.legacy_2x.aigc.*`, `com.alibaba.dashscope.legacy_2x.embeddings.*`, … +- AgentStudio is **not** deprecated: it moved to `com.alibaba.dashscope.applications.agentstudio.*` + and is also reachable via `client.agentStudio()` on the 3.0 client. + +Runnable 2.x samples are archived in [examples/legacy_2x/](examples/legacy_2x/README.md). + +
+Expand the legacy 2.x quick-start documentation ### Generation @@ -31,14 +333,16 @@ Here shows the usages of each method, with the examples of `qwen-turbo` model. #### Support stream and non-stream mode, accept output from callback ```java -import com.alibaba.dashscope.aigc.generation.Generation; -import com.alibaba.dashscope.aigc.generation.GenerationParam; -import com.alibaba.dashscope.aigc.generation.GenerationResult; -import com.alibaba.dashscope.common.Message; -import com.alibaba.dashscope.common.ResultCallback; -import com.alibaba.dashscope.common.Role; -import com.alibaba.dashscope.exception.ApiException; -import com.alibaba.dashscope.utils.JsonUtils; +import com.alibaba.dashscope.legacy_2x.aigc.generation.Generation; +import com.alibaba.dashscope.legacy_2x.aigc.generation.GenerationParam; +import com.alibaba.dashscope.legacy_2x.aigc.generation.GenerationResult; +import com.alibaba.dashscope.legacy_2x.common.Message; +import com.alibaba.dashscope.legacy_2x.common.ResultCallback; +import com.alibaba.dashscope.legacy_2x.common.Role; +import com.alibaba.dashscope.legacy_2x.exception.ApiException; +import com.alibaba.dashscope.legacy_2x.exception.InputRequiredException; +import com.alibaba.dashscope.legacy_2x.exception.NoApiKeyException; +import com.alibaba.dashscope.legacy_2x.utils.JsonUtils; import java.util.Arrays; public class Main { @@ -71,7 +375,11 @@ public class Main { } } - generation.call(param, new ReactCallback()); + try { + generation.call(param, new ReactCallback()); + } catch (ApiException | NoApiKeyException | InputRequiredException e) { + System.err.println("An error occurred: " + e.getMessage()); + } } } ``` @@ -84,15 +392,15 @@ The Exception instance is an `ApiException` instance. This Exception may contain #### Stream only, accept by reactive io ```java -import com.alibaba.dashscope.aigc.generation.Generation; -import com.alibaba.dashscope.aigc.generation.GenerationParam; -import com.alibaba.dashscope.aigc.generation.GenerationResult; -import com.alibaba.dashscope.common.Message; -import com.alibaba.dashscope.common.Role; -import com.alibaba.dashscope.exception.ApiException; -import com.alibaba.dashscope.exception.InputRequiredException; -import com.alibaba.dashscope.exception.NoApiKeyException; -import com.alibaba.dashscope.utils.JsonUtils; +import com.alibaba.dashscope.legacy_2x.aigc.generation.Generation; +import com.alibaba.dashscope.legacy_2x.aigc.generation.GenerationParam; +import com.alibaba.dashscope.legacy_2x.aigc.generation.GenerationResult; +import com.alibaba.dashscope.legacy_2x.common.Message; +import com.alibaba.dashscope.legacy_2x.common.Role; +import com.alibaba.dashscope.legacy_2x.exception.ApiException; +import com.alibaba.dashscope.legacy_2x.exception.InputRequiredException; +import com.alibaba.dashscope.legacy_2x.exception.NoApiKeyException; +import com.alibaba.dashscope.legacy_2x.utils.JsonUtils; import io.reactivex.Flowable; import java.util.Arrays; @@ -131,15 +439,15 @@ The `streamCall` method accepts a `GenerationParam`, and returns a `Flowable`, w #### Non-stream only ```java -import com.alibaba.dashscope.aigc.generation.Generation; -import com.alibaba.dashscope.aigc.generation.GenerationParam; -import com.alibaba.dashscope.aigc.generation.GenerationResult; -import com.alibaba.dashscope.common.Message; -import com.alibaba.dashscope.common.Role; -import com.alibaba.dashscope.exception.ApiException; -import com.alibaba.dashscope.exception.InputRequiredException; -import com.alibaba.dashscope.exception.NoApiKeyException; -import com.alibaba.dashscope.utils.JsonUtils; +import com.alibaba.dashscope.legacy_2x.aigc.generation.Generation; +import com.alibaba.dashscope.legacy_2x.aigc.generation.GenerationParam; +import com.alibaba.dashscope.legacy_2x.aigc.generation.GenerationResult; +import com.alibaba.dashscope.legacy_2x.common.Message; +import com.alibaba.dashscope.legacy_2x.common.Role; +import com.alibaba.dashscope.legacy_2x.exception.ApiException; +import com.alibaba.dashscope.legacy_2x.exception.InputRequiredException; +import com.alibaba.dashscope.legacy_2x.exception.NoApiKeyException; +import com.alibaba.dashscope.legacy_2x.utils.JsonUtils; import java.util.Arrays; public class Main { @@ -173,3 +481,71 @@ public class Main { ``` The `call` method accepts a `GenerationParam`, and returns a `GenerationResult`, you can also catch the exception with a try-catch block. + +### Decision Model + +The decision model answers a batch of multiple-choice (choice), yes/no (noul) and ordered-scale (score) questions against a given business state, see the [Decision Model API document](https://docs.bailian.console.aliyun.com/zh/model-studio/decision-model-api). + +```java +import com.alibaba.dashscope.legacy_2x.decision.DecisionModel; +import com.alibaba.dashscope.legacy_2x.decision.DecisionModelParam; +import com.alibaba.dashscope.legacy_2x.decision.DecisionModelResult; +import com.alibaba.dashscope.legacy_2x.decision.DecisionQuestion; +import com.alibaba.dashscope.legacy_2x.exception.ApiException; +import com.alibaba.dashscope.legacy_2x.exception.InputRequiredException; +import com.alibaba.dashscope.legacy_2x.exception.NoApiKeyException; +import com.alibaba.dashscope.legacy_2x.utils.JsonUtils; +import java.util.Arrays; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +public class Main { + + public static void main(String[] args) { + // The business state. + Map state = new HashMap<>(); + state.put("ticket_id", "T-1001"); + state.put("content", "订单支付后超过 24 小时仍未到账,用户无法继续使用核心服务,要求立即处理。"); + + // The questions. + Map options = new LinkedHashMap<>(); + options.put("billing", "支付、退款和账单问题"); + options.put("technical", "产品故障和集成问题"); + List levels = Arrays.asList( + "轻微问题,不影响功能", + "部分功能受影响,但存在替代方案", + "核心功能不可用,没有替代方案", + "造成严重业务或安全影响"); + Map questions = new LinkedHashMap<>(); + questions.put("department", DecisionQuestion.choice("应该由哪个团队处理?", options)); + questions.put("escalate", DecisionQuestion.noul("是否需要立即通知值班人员?")); + questions.put("severity", DecisionQuestion.score("这个问题有多严重?", levels)); + + DecisionModelParam param = DecisionModelParam.builder() + .model(DecisionModelParam.Models.DECISION_MODEL_PREVIEW) + .state(state) + .questions(questions) + .build(); + + try { + // A workspace id is required: pass it here (new DecisionModel("your-workspace-id")) + // or set the DASHSCOPE_WORKSPACE environment variable before running. + DecisionModel decisionModel = new DecisionModel(); + DecisionModelResult result = decisionModel.call(param); + System.out.println(JsonUtils.toJson(result)); + } catch (ApiException | NoApiKeyException | InputRequiredException e) { + System.err.println("An error occurred: " + e.getMessage()); + } + } +} +``` + +The `call` method accepts a `DecisionModelParam`, and returns a `DecisionModelResult` whose `answers` are keyed by question id. Streaming is not supported. The API key is read from the `DASHSCOPE_API_KEY` environment variable by default, or set explicitly with `apiKey(...)`. + +The endpoint is workspace-scoped: the base URL is composed as `https://{workspace}.{region}.maas.aliyuncs.com/compatible-mode/v1` (the `systemone` path is appended automatically). A workspace id is **required** — pass it to the constructor (`new DecisionModel(workspace)` or `new DecisionModel(workspace, region)`) or set the `DASHSCOPE_WORKSPACE` environment variable; otherwise constructing the client throws `IllegalArgumentException`. The region defaults to `cn-beijing` and can be set via `DASHSCOPE_API_REGION`. + +To target a fully custom endpoint (for example the Token Plan gateway), use the static factory `DecisionModel.withBaseUrl(baseUrl)`. Note that `new DecisionModel(String)` treats its argument as a **workspace id**, not a base URL. You can also override the entire base URL with the `DASHSCOPE_DECISION_BASE_URL` environment variable; the SDK-wide `DASHSCOPE_HTTP_BASE_URL` is intentionally not read here. + +
diff --git a/README_zh.md b/README_zh.md new file mode 100644 index 00000000..ebb9fe7e --- /dev/null +++ b/README_zh.md @@ -0,0 +1,538 @@ +# DashScope Java SDK + +[![Maven Central](https://img.shields.io/maven-central/v/com.alibaba/dashscope-sdk-java.svg)](https://central.sonatype.com/artifact/com.alibaba/dashscope-sdk-java) +[![Build and Test](https://github.com/dashscope/dashscope-sdk-java/actions/workflows/build-and-test.yml/badge.svg)](https://github.com/dashscope/dashscope-sdk-java/actions/workflows/build-and-test.yml) +[![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](LICENSE) + +[English](README.md) | 中文 + +文档站: —— 中英双语指南、2.x 迁移说明与自动生成的 API 文档。 + +[DashScope](https://dashscope.aliyuncs.com)(阿里云百炼)模型的 Java SDK。 +本仓库为 **3.0 新代际**:统一的 `DashScopeClient` 入口 + 类型化资源树,支持阻塞式 SSE 流式, +并提供返回 `CompletableFuture` / RxJava `Flowable` 的异步镜像客户端。运行期要求 **Java 8+**。 + +> 从 2.x 升级?旧 API 已迁至 `com.alibaba.dashscope.legacy_2x.*`,均已废弃并将在 4.0 移除—— +> 见[从 2.x 迁移](#从-2x-迁移)。旧版文档保存在文末「旧版 2.x API」附录。 + +## 安装 + +```xml + + com.alibaba + dashscope-sdk-java + 3.0.0 + +``` + +## 快速开始 + +先设置 API Key:`export DASHSCOPE_API_KEY=sk-...`(在[百炼控制台](https://bailian.console.aliyun.com/)获取)。 + +### 同步调用 + +```java +import com.alibaba.dashscope.DashScopeClient; +import com.alibaba.dashscope.types.completions.ChatCompletion; +import com.alibaba.dashscope.types.completions.ChatCompletionCreateParams; +import com.alibaba.dashscope.types.messages.Message; +import java.util.Collections; + +try (DashScopeClient client = DashScopeClient.builder().build()) { + ChatCompletion result = client.chat().completions().create( + ChatCompletionCreateParams.builder() + .model("qwen-plus") + .messages(Collections.singletonList(Message.user("你好,最近怎么样?"))) + .build()); + System.out.println(result.outputText()); + System.out.println("request_id: " + result.getRequestId()); +} +``` + +### 流式调用(SSE) + +`createStreaming` 返回一次性的 `ResponseStream`——阻塞式类型化迭代器。请务必用 +try-with-resources 关闭以释放底层连接。每个 chunk 的 `delta()` 携带内容增量。 + +```java +import com.alibaba.dashscope.DashScopeClient; +import com.alibaba.dashscope.types.common.ResponseStream; +import com.alibaba.dashscope.types.completions.ChatCompletionChunk; +import com.alibaba.dashscope.types.completions.ChatCompletionCreateParams; +import com.alibaba.dashscope.types.completions.Delta; +import com.alibaba.dashscope.types.messages.Message; +import java.util.Collections; + +try (DashScopeClient client = DashScopeClient.builder().build()) { + try (ResponseStream stream = client.chat().completions().createStreaming( + ChatCompletionCreateParams.builder() + .model("qwen-plus") + .messages(Collections.singletonList(Message.user("你好,最近怎么样?"))) + .build())) { + for (ChatCompletionChunk chunk : stream) { + Delta delta = chunk.delta(); + if (delta != null && delta.getContent() != null) { + System.out.print(delta.getContent()); + } + } + } +} +``` + +### 异步调用 + +`DashScopeAsyncClient` 提供同一资源树:普通调用返回 `CompletableFuture`,流式返回 RxJava +`Flowable`。客户端持有守护线程池,try-with-resources 会自动关闭。 + +```java +import com.alibaba.dashscope.DashScopeAsyncClient; +import com.alibaba.dashscope.types.completions.ChatCompletion; +import com.alibaba.dashscope.types.completions.ChatCompletionCreateParams; +import com.alibaba.dashscope.types.messages.Message; +import java.util.Collections; +import java.util.concurrent.CompletableFuture; + +try (DashScopeAsyncClient client = DashScopeAsyncClient.builder().build()) { + CompletableFuture future = client.chat().completions().create( + ChatCompletionCreateParams.builder() + .model("qwen-plus") + .messages(Collections.singletonList(Message.user("你好,最近怎么样?"))) + .build()); + future.thenAccept(result -> System.out.println(result.outputText())).join(); + + // 流式:client.chat().completions().createStreaming(params) 返回 + // Flowable,可用 blockingForEach 消费或 subscribe。 +} +``` + +## 配置 + +下表所列配置项都走配置链:**Builder 显式参数 > JVM 系统属性 > 环境变量 > +`~/.dashscope/config.toml` > 默认值**(`wsBaseUrl` 没有 config-file 键;`raiseOnError`、 +`httpClient`、`executor` 仅支持 Builder 注入)。API Key 还会额外回退到 1.x 密钥文件 +(`DASHSCOPE_API_KEY_FILE_PATH` 或 `~/.dashscope/api_key`),因此只需导出 +`DASHSCOPE_API_KEY`,`DashScopeClient.builder().build()` 即可直接使用。 + +配置文件为扁平的 `key = value` TOML 子集;时长类取值单位为**秒**: + +```toml +# ~/.dashscope/config.toml +api_key = "sk-..." +base_url = "https://dashscope.aliyuncs.com" +workspace = "llm-xxxx" +region = "cn-beijing" +timeout = 300 # 秒 +max_retries = 2 +ws_ping_interval = 0 # 秒,0 = 关闭 +``` + +客户端级配置(`DashScopeClient.builder()` / `DashScopeAsyncClient.builder()`): + +| Builder 方法 | 环境变量 | 默认值 | 说明 | +|---|---|---|---| +| `apiKey(...)` | `DASHSCOPE_API_KEY` | — | API Key(走上述配置链) | +| `baseUrl(...)` | `DASHSCOPE_BASE_URL` / `DASHSCOPE_HTTP_BASE_URL` | 区域端点 | HTTP base URL | +| `wsBaseUrl(...)` | `DASHSCOPE_WEBSOCKET_BASE_URL` | 区域端点 | WebSocket base URL | +| `workspace(...)` | `DASHSCOPE_WORKSPACE` | — | 工作空间 id(部分 API 必填,如决策模型) | +| `region(...)` | `DASHSCOPE_REGION` | `cn-beijing` | MaaS 网关区域 | +| `timeout(...)` | `DASHSCOPE_TIMEOUT` | 5 分钟 | 单请求超时(`Duration`) | +| `maxRetries(...)` | `DASHSCOPE_MAX_RETRIES` | 2 | 可重试失败的自动重试次数 | +| `raiseOnError(...)` | — | `true` | `false` 切换为 2.x 风格的 `isError()` 返回 | +| `wsPingInterval(...)` | `DASHSCOPE_WS_PING_INTERVAL` | 0(关闭) | WebSocket 保活 ping;NAT/代理后建议 20–30 秒 | +| `httpClient(...)` | — | SDK 持有 | 注入自有 `OkHttpClient`(生命周期由调用方管理) | +| `executor(...)` | — | SDK 持有 | 注入异步线程池(生命周期由调用方管理) | + +单次调用覆盖:每个资源方法都有 `(params, RequestOptions)` 重载,未设置的字段继承客户端配置。 + +```java +import com.alibaba.dashscope.RequestOptions; +import java.time.Duration; + +RequestOptions options = RequestOptions.builder() + .timeout(Duration.ofSeconds(30)) + .maxRetries(0) + .header("X-Custom-Header", "value") + .enableEncryption(true) // 本次调用启用 DashScope 加密 HTTP 通道 + .build(); +// client.chat().completions().create(params, options); +``` + +`RequestOptions` 支持 `timeout`、`maxRetries`、`apiKey`、`workspace`、额外 `headers`、 +`enableEncryption` 和 `wsQueueCapacity`(WebSocket 事件有界缓冲)。 + +HTTP 报文日志(仅环境变量):将 `DASHSCOPE_NETWORK_LOGGING_LEVEL` 设为 `BASIC`、`HEADERS` 或 +`BODY`(默认 `NONE`)。凭证类请求头始终脱敏。 + +遥测关闭:将 `DASHSCOPE_DISABLE_SDK_HEADERS` 设为 `1`(或 `true`)可去掉 +`x-dashscope-sdk-client` / `x-dashscope-sdk-session-id` 跟踪头;`User-Agent` 与调用方自设头 +不受影响。 + +## 能力一览 + +`client.` 上每个能力一个入口——均链接到最小可运行示例 +(完整索引与运行命令见 [examples/README_zh.md](examples/README_zh.md)): + +| 资源 | API 路径 | 示例 | +|---|---|---| +| 文本对话 | `chat().completions().create / createStreaming` | [ChatCompletionsCreate](examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/chat/ChatCompletionsCreate.java) | +| 多模态 | `multimodal().chat().create / createStreaming` | [MultimodalChatCreate](examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/multimodal/MultimodalChatCreate.java) | +| 应用调用 | `apps().completions().create / createStreaming` | [AppsCompletionsCreate](examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/apps/AppsCompletionsCreate.java) | +| 文生图 | `images().generate / jobs().create / wait / fetch` | [ImagesGenerate](examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/images/ImagesGenerate.java) | +| 文生视频 | `videos().generate / jobs().*` | [VideosGenerate](examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/videos/VideosGenerate.java) | +| 向量化 | `embeddings().create` | [EmbeddingsCreate](examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/embeddings/EmbeddingsCreate.java) | +| 重排序 | `rerank().create` | [RerankCreate](examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/rerank/RerankCreate.java) | +| Token 计数 | `tokenization().count` | [TokenizationCount](examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/chat/TokenizationCount.java) | +| 语音识别 / 合成 | `audio().asr() / tts() / voices() / realtime()` | [音频示例](examples/README_zh.md) | +| 模型微调 | `fineTunes().list / get / create` | [FineTunesCreate](examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/finetunes/FineTunesCreate.java) | +| 模型部署 | `deployments().list / get / create` | [DeploymentsManage](examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/deployments/DeploymentsManage.java) | +| 文件管理 | `files().upload / list / get / delete` | [FilesManage](examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/files/FilesManage.java) | +| 模型列表 | `models().list / get` | [ModelsList](examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/models/ModelsList.java) | +| 听悟 | `tingwu().jobs().create / wait` | [TingWuJobsCreate](examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/audio/TingWuJobsCreate.java) | +| 决策模型 | `decision().create` | [DecisionCreate](examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/decision/DecisionCreate.java) | +| AgentStudio | `agentStudio()`:environments / agents / sessions / events | [AgentStudioQuickStart](examples/03_agent_recipes/com/alibaba/dashscope/examples/recipes/agentstudio/AgentStudioQuickStart.java) | + +另有:`client.wsConnection()` 可在一条 WebSocket 上复用多个音频任务 +([AudioConnectionReuse](examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/audio/AudioConnectionReuse.java)); +`TokenizerFactory.qwen()` 提供无需 API Key 的离线本地 BPE 分词 +([TokenizationLocalCount](examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/chat/TokenizationLocalCount.java))。 + +## 错误处理 + +3.0 抛出以 `com.alibaba.dashscope.errors.DashScopeException`(`RuntimeException`)为根的 +**unchecked** 异常——不再是 checked 的 `ApiException / NoApiKeyException / InputRequiredException`。 +每个异常携带 `code`、`statusCode`、`requestId`、`body` 和响应 `headers`。 + +- HTTP 状态码错误:`BadRequestException`(400)、`AuthenticationException`(401)、 + `PermissionDeniedException`(403)、`NotFoundException`(404)、`RequestTooLargeException`(413)、 + `RateLimitException`(429)、`InternalServerException`(500)、`ServiceUnavailableException`、 + `GatewayTimeoutException`,以及通用的 `ApiStatusException`。 +- 传输层错误:`ApiConnectionException`、`ApiTimeoutException`。 +- 业务错误码(如内容审核):`ContentFilterException` 及其他由 `Errors` 映射的 + `DashScopeException` 子类。 +- SDK 侧误用:`SdkException` / `IllegalArgumentException`。 + +更习惯 2.x 的「在结果上检查错误」?用 `raiseOnError(false)` 构建客户端:调用正常返回, +通过 `result.isError()`(配合 `getCode()` / `getMessage()`)判断业务失败;流内错误帧会以 +末尾携带错误的 chunk 呈现,而不是抛异常。 + +## 从 2.x 迁移 + +3.0 是有意的 FQCN、源码与二进制破坏性变更。除 AgentStudio 外的旧 2.x API 已迁至 +`com.alibaba.dashscope.legacy_2x.*`,均带类型级 `@Deprecated`(`-Xlint:deprecation` 显示详情), +并将在 4.0 移除。AgentStudio(`com.alibaba.dashscope.applications.agentstudio.*`)与 +`shared` 不废弃。 + +| 2.x 类(`com.alibaba.dashscope.*`) | 3.0 等价入口(`client.*`) | +|---|---| +| `aigc.generation.Generation` | `chat().completions().create / createStreaming` | +| `aigc.multimodalconversation.MultiModalConversation` | `multimodal().chat().create / createStreaming` | +| `embeddings.TextEmbedding` / `BatchTextEmbedding` | `embeddings().create` | +| `rerank.TextReRank` | `rerank().create` | +| `aigc.imagesynthesis.ImageSynthesis` | `images().generate` + `jobs().create / wait / fetch` | +| `aigc.videosynthesis.VideoSynthesis` | `videos().generate` + `jobs().*` | +| `app.Application` | `apps().completions().create / createStreaming` | +| `decision.DecisionModel` | `decision().create` | +| `audio.asr.*` / `audio.tts.*` / `audio.qwen_tts_realtime.*` | `audio().asr() / tts() / realtime()` | +| `multimodal.tingwu.TingWu` | `tingwu().jobs().create / wait` | +| `tokenizers.*` | `tokenization().count` / `TokenizerFactory` | +| `assistants.*` / `threads.*` | 暂无 3.0 等价物——保留 `legacy_2x` imports | + +关键行为变化: + +- **异常**:checked 的 `ApiException` 家族 → unchecked 的 `DashScopeException` 家族 + (见[错误处理](#错误处理));`raiseOnError(false)` 可恢复结果式错误。 +- **流式**:同步 `streamCall` 返回 `Flowable` → `createStreaming` 返回类型化 + `ResponseStream`(for-each + try-with-resources)。异步客户端仍提供 `Flowable`。 +- **客户端生命周期**:按能力 `new Generation()` → 一个 try-with-resources 的 + `DashScopeClient`(或 `DashScopeAsyncClient`),共享连接池与配置。 +- **AgentStudio**:同一业务包,新 FQCN 为 + `com.alibaba.dashscope.applications.agentstudio.*`;也可经 `client.agentStudio()` 访问。 + 3.0 的 `baseUrl` 不作用于 AgentStudio;`DASHSCOPE_AGENTSTUDIO_URL` 可单独指定其端点。 + +已废弃的 2.x 快速开始文档(回调 / `Flowable` / 非流式 `Generation` 用法、旧版 +`DecisionModel` 端点规则)保存在文末「旧版 2.x API」附录;2.x 示例归档于 +[examples/legacy_2x/](examples/legacy_2x/README.md)。 + +## 示例 + +[examples/](examples/README_zh.md) 工程按四层组织:原子能力、进阶工程(重试/熔断、缓存、 +本地 Mock 调试)、Agent 配方(工具调用、RAG、AgentStudio)、真实场景 Harness。 + +```bash +# 先从本仓库安装 SDK(示例工程解析 3.0.0 版本) +mvn install -DskipTests -Dgpg.skip=true -Dmaven.javadoc.skip=true + +export DASHSCOPE_API_KEY=sk-... +mvn -q -f examples/pom.xml compile exec:java \ + -Dexec.mainClass=com.alibaba.dashscope.examples.atomic.chat.ChatCompletionsCreate +``` + +所有示例也可离线跑在 MockWebServer 上(无需 API Key、不产生费用): + +```bash +mvn -f examples/pom.xml clean test +``` + +## 从源码构建 + +构建基线为 JDK 8(CI 在 JDK 8 上构建与测试;字节码 target 8)。在 JDK 9+ 上构建同样可行—— +pom 的 `jdk9-plus` profile 会自动激活并以 `release 8` 做 API 校验。 + +```bash +mvn clean test # 单元 + Mock 测试 +./lint.sh # google-java-format 检查(100 列限制) +``` + +## 许可证 + +[Apache License 2.0](LICENSE) + +## 旧版 2.x API(已废弃) + +> **已废弃。** 以下内容为旧版 2.x API 文档。自 3.0 起,这些类位于 +> `com.alibaba.dashscope.legacy_2x.*`,均带类型级 `@Deprecated`,并将在 **4.0 移除**。 +> 新代码请使用上文的 3.0 客户端。 + +要让存量 2.x 代码在 3.0 artifact 上继续编译,请调整 imports: + +- `com.alibaba.dashscope.aigc.*`、`com.alibaba.dashscope.embeddings.*` 等 → + `com.alibaba.dashscope.legacy_2x.aigc.*`、`com.alibaba.dashscope.legacy_2x.embeddings.*` 等 +- AgentStudio **不废弃**:迁至 `com.alibaba.dashscope.applications.agentstudio.*`, + 也可通过 3.0 客户端的 `client.agentStudio()` 访问。 + +可运行的 2.x 示例归档于 [examples/legacy_2x/](examples/legacy_2x/README.md)。 + +
+展开旧版 2.x 快速开始文档 + +### 文本生成 + +您可以通过以下方式创建文本生成客户端: + +```java +Generation generation = new Generation(); +``` + +文本生成接口支持流式和非流式查询。这些查询都接受 `GenerationParam` 作为输入,并返回 `GenerationResult` 作为输出。 + +以下是各方法的使用示例,以 `qwen-turbo` 模型为例。 + +#### 支持流式和非流式模式,通过回调接收输出 + +```java +import com.alibaba.dashscope.legacy_2x.aigc.generation.Generation; +import com.alibaba.dashscope.legacy_2x.aigc.generation.GenerationParam; +import com.alibaba.dashscope.legacy_2x.aigc.generation.GenerationResult; +import com.alibaba.dashscope.legacy_2x.common.Message; +import com.alibaba.dashscope.legacy_2x.common.ResultCallback; +import com.alibaba.dashscope.legacy_2x.common.Role; +import com.alibaba.dashscope.legacy_2x.exception.ApiException; +import com.alibaba.dashscope.legacy_2x.exception.InputRequiredException; +import com.alibaba.dashscope.legacy_2x.exception.NoApiKeyException; +import com.alibaba.dashscope.legacy_2x.utils.JsonUtils; +import java.util.Arrays; + +public class Main { + + public static void main(String[] args) { + Generation generation = new Generation(); + GenerationParam param = GenerationParam.builder() + .apiKey(System.getenv("DASHSCOPE_API_KEY")) + .model(Generation.Models.QWEN_TURBO) + .messages(Arrays.asList( + Message.builder() + .role(Role.USER.getValue()) + .content("Hello, how are you?").build() + )).build(); + + class ReactCallback extends ResultCallback { + + @Override + public void onEvent(GenerationResult message) { + System.out.println(JsonUtils.toJson(message)); + } + + public void onComplete() { + // TODO 所有消息已接收 + } + + public void onError(Exception e) { + ApiException apiException = (ApiException) e; + // TODO 处理异常 + } + } + + try { + generation.call(param, new ReactCallback()); + } catch (ApiException | NoApiKeyException | InputRequiredException e) { + System.err.println("An error occurred: " + e.getMessage()); + } + } +} +``` + +异常实例是一个 `ApiException` 实例。该异常可能包含两部分: + +- 一个 `Status` 实例。该实例包含 status_code(HTTP 错误码)、code(服务器错误码)、message(服务器错误信息)、请求 ID 和使用信息。 +- 如果发生异常,`ApiException` 实例可能只包含一个 `Exception` 堆栈跟踪,您可以像平常一样处理它。 + +#### 仅流式模式,通过响应式 IO 接收 + +```java +import com.alibaba.dashscope.legacy_2x.aigc.generation.Generation; +import com.alibaba.dashscope.legacy_2x.aigc.generation.GenerationParam; +import com.alibaba.dashscope.legacy_2x.aigc.generation.GenerationResult; +import com.alibaba.dashscope.legacy_2x.common.Message; +import com.alibaba.dashscope.legacy_2x.common.Role; +import com.alibaba.dashscope.legacy_2x.exception.ApiException; +import com.alibaba.dashscope.legacy_2x.exception.InputRequiredException; +import com.alibaba.dashscope.legacy_2x.exception.NoApiKeyException; +import com.alibaba.dashscope.legacy_2x.utils.JsonUtils; +import io.reactivex.Flowable; +import java.util.Arrays; + +public class Main { + + public static void main(String[] args) { + Generation generation = new Generation(); + + Message systemMsg = Message.builder() + .role(Role.SYSTEM.getValue()) + .content("You are a helpful assistant.") + .build(); + Message userMsg = Message.builder() + .role(Role.USER.getValue()) + .content("Hello!") + .build(); + GenerationParam param = GenerationParam.builder() + .apiKey(System.getenv("DASHSCOPE_API_KEY")) + .model(Generation.Models.QWEN_TURBO) + .messages(Arrays.asList(systemMsg, userMsg)) + .resultFormat(GenerationParam.ResultFormat.MESSAGE) + .build(); + + try { + Flowable result = generation.streamCall(param); + result.blockingForEach(msg -> System.out.println(JsonUtils.toJson(msg))); + } catch (ApiException | NoApiKeyException | InputRequiredException e) { + System.err.println("An error occurred: " + e.getMessage()); + } + } +} +``` + +`streamCall` 方法接受 `GenerationParam`,并返回一个 `Flowable`,您可以通过 `blockingForEach` 获取流式结果,并通过 try-catch 块捕获异常。 + +#### 仅非流式模式 + +```java +import com.alibaba.dashscope.legacy_2x.aigc.generation.Generation; +import com.alibaba.dashscope.legacy_2x.aigc.generation.GenerationParam; +import com.alibaba.dashscope.legacy_2x.aigc.generation.GenerationResult; +import com.alibaba.dashscope.legacy_2x.common.Message; +import com.alibaba.dashscope.legacy_2x.common.Role; +import com.alibaba.dashscope.legacy_2x.exception.ApiException; +import com.alibaba.dashscope.legacy_2x.exception.InputRequiredException; +import com.alibaba.dashscope.legacy_2x.exception.NoApiKeyException; +import com.alibaba.dashscope.legacy_2x.utils.JsonUtils; +import java.util.Arrays; + +public class Main { + + public static void main(String[] args) { + Generation generation = new Generation(); + + Message systemMsg = Message.builder() + .role(Role.SYSTEM.getValue()) + .content("You are a helpful assistant.") + .build(); + Message userMsg = Message.builder() + .role(Role.USER.getValue()) + .content("Hello!") + .build(); + GenerationParam param = GenerationParam.builder() + .apiKey(System.getenv("DASHSCOPE_API_KEY")) + .model(Generation.Models.QWEN_TURBO) + .messages(Arrays.asList(systemMsg, userMsg)) + .resultFormat(GenerationParam.ResultFormat.MESSAGE) + .build(); + + try { + GenerationResult result = generation.call(param); + System.out.println(JsonUtils.toJson(result)); + } catch (ApiException | NoApiKeyException | InputRequiredException e) { + System.err.println("An error occurred: " + e.getMessage()); + } + } +} +``` + +`call` 方法接受 `GenerationParam`,并返回 `GenerationResult`,您也可以通过 try-catch 块捕获异常。 + +### 决策模型 + +决策模型(Decision Model)针对给定的业务状态,批量回答多选一(choice)、是否判断(noul)、有序量表(score)三类问题,详见[决策模型 API 文档](https://docs.bailian.console.aliyun.com/zh/model-studio/decision-model-api)。 + +```java +import com.alibaba.dashscope.legacy_2x.decision.DecisionModel; +import com.alibaba.dashscope.legacy_2x.decision.DecisionModelParam; +import com.alibaba.dashscope.legacy_2x.decision.DecisionModelResult; +import com.alibaba.dashscope.legacy_2x.decision.DecisionQuestion; +import com.alibaba.dashscope.legacy_2x.exception.ApiException; +import com.alibaba.dashscope.legacy_2x.exception.InputRequiredException; +import com.alibaba.dashscope.legacy_2x.exception.NoApiKeyException; +import com.alibaba.dashscope.legacy_2x.utils.JsonUtils; +import java.util.Arrays; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +public class Main { + + public static void main(String[] args) { + // 业务状态 + Map state = new HashMap<>(); + state.put("ticket_id", "T-1001"); + state.put("content", "订单支付后超过 24 小时仍未到账,用户无法继续使用核心服务,要求立即处理。"); + + // 问题列表 + Map options = new LinkedHashMap<>(); + options.put("billing", "支付、退款和账单问题"); + options.put("technical", "产品故障和集成问题"); + List levels = Arrays.asList( + "轻微问题,不影响功能", + "部分功能受影响,但存在替代方案", + "核心功能不可用,没有替代方案", + "造成严重业务或安全影响"); + Map questions = new LinkedHashMap<>(); + questions.put("department", DecisionQuestion.choice("应该由哪个团队处理?", options)); + questions.put("escalate", DecisionQuestion.noul("是否需要立即通知值班人员?")); + questions.put("severity", DecisionQuestion.score("这个问题有多严重?", levels)); + + DecisionModelParam param = DecisionModelParam.builder() + .model(DecisionModelParam.Models.DECISION_MODEL_PREVIEW) + .state(state) + .questions(questions) + .build(); + + try { + // 必须提供 workspace:可在此传入(new DecisionModel("你的-workspace-id")), + // 或在运行前设置 DASHSCOPE_WORKSPACE 环境变量。 + DecisionModel decisionModel = new DecisionModel(); + DecisionModelResult result = decisionModel.call(param); + System.out.println(JsonUtils.toJson(result)); + } catch (ApiException | NoApiKeyException | InputRequiredException e) { + System.err.println("An error occurred: " + e.getMessage()); + } + } +} +``` + +`call` 方法接受 `DecisionModelParam`,并返回 `DecisionModelResult`,其中 `answers` 按问题 id 给出答案,不支持流式输出。API Key 默认从环境变量 `DASHSCOPE_API_KEY` 获取,也可以通过 `apiKey(...)` 指定。 + +请求地址是 workspace 作用域的:base URL 由 `https://{workspace}.{region}.maas.aliyuncs.com/compatible-mode/v1` 拼接而成(`systemone` 路径会自动追加)。**必须**提供 workspace id——通过构造函数传入(`new DecisionModel(workspace)` 或 `new DecisionModel(workspace, region)`),或设置环境变量 `DASHSCOPE_WORKSPACE`;否则构造客户端时会抛出 `IllegalArgumentException`。region 默认为 `cn-beijing`,可通过环境变量 `DASHSCOPE_API_REGION` 设置。 + +若要指向完全自定义的端点(例如 Token Plan 网关),请使用静态工厂方法 `DecisionModel.withBaseUrl(baseUrl)`。注意 `new DecisionModel(String)` 会把参数当作 **workspace id**,而不是 base URL。你也可以用环境变量 `DASHSCOPE_DECISION_BASE_URL` 覆盖整个 base URL;此处的实现有意不读取全局的 `DASHSCOPE_HTTP_BASE_URL`。 + +
diff --git a/RELEASE_NOTES_v2.22.29.md b/RELEASE_NOTES_v2.22.29.md deleted file mode 100644 index 9ebcc60a..00000000 --- a/RELEASE_NOTES_v2.22.29.md +++ /dev/null @@ -1,31 +0,0 @@ -## What's Changed - -### New Features -- Add managed agent deployment APIs for AgentStudio (#253) - - Implement Deployment, DeploymentRun, DeploymentSchedule models - - Add Deployments and DeploymentRuns resource classes - - Support create, list, get, update, delete operations - - Add sample code: AgentStudioDeployments.java - -### Bug Fixes -- Serialize empty deployment metadata correctly -- Parse nested error envelopes in HTTP responses -- Restrict deployment metadata to string values only - -### Deprecations -- Mark Assistants API as deprecated (#254) - - Add @Deprecated annotations to Assistant, AssistantFile, Assistants classes - - Add deprecation warnings to Runs class - - Users should migrate to new API alternatives - -### Code Quality -- Add comprehensive test coverage for AgentStudio Deployments -- Add test resources: agentstudio.json -- Improve code documentation and type safety - -## Full Changelog -https://github.com/dashscope/dashscope-sdk-java/compare/v2.22.28...v2.22.29 - -## 👥 Contributors -- coolsky99 -- luk384090-cloud diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 00000000..52d8b94c --- /dev/null +++ b/docs/README.md @@ -0,0 +1,106 @@ +# Documentation Maintenance Guide + +This directory builds the documentation site at + (MkDocs Material, bilingual, with generated +Javadoc mounted under `/api/`). This file is **excluded from the site** — it is for maintainers. + +Shared Python/Java site structure: [documentation template](../DOCS_TEMPLATE.md). + +## Layout & bilingual convention + +``` +docs/ +├── en/ # English — the canonical source of every page +│ ├── index.md quickstart.md features.md migrating.md legacy.md reference.md +│ ├── examples.md develop.md release-notes.md about.md +│ ├── reference/ # task-oriented index pages for generated Javadoc +│ └── guides/ # chat, async, multimodal, embeddings-rerank, images-videos, audio, +│ # files-finetunes, agentstudio, tokenization, local-mock, errors, configuration +├── zh/ # Simplified Chinese — same file names, translated prose +├── overrides/ # Material theme overrides +├── stylesheets/ # extra.css +├── javadoc/ # material-bridge.css (appended to the Javadoc stylesheet) +├── hooks.py # injects sdk_version (parsed from the root pom.xml) into config.extra +├── main.py # macros module: {{ sdk_version }} + {{ release_notes }} (GitHub Releases table) +└── serve.sh # local preview: Javadoc + mkdocs serve +``` + +Rules: + +- **English first**: write or update `docs/en/.md`, then mirror the change in + `docs/zh/.md` (same relative path). The i18n plugin uses `docs_structure: folder`; + a page missing under `zh/` falls back to the English build, so never leave a translation + half-done — either ship both or neither. +- Code blocks stay identical between languages except for comments/output strings. +- **Full runnable examples are embedded, never copied**: the "Full runnable example + (auto-synced)" collapsibles use `pymdownx.snippets` (`--8<-- "examples/..."`) to include the + real example source at build time. `check_paths: true` fails the build if a referenced file + is missing or renamed, so embedded code can never drift from the CI-verified `examples/` + project. When adding a guide, embed its source example(s) the same way; keep inline snippets + short and instructional. +- Every API claim must be traceable to `src/main/java` or a dry-run-verified example under + `examples/` — do not document methods that do not exist. +- `{{ sdk_version }}` renders the root `pom.xml` version; use it instead of hard-coding + version numbers in install snippets. +- `{{ release_notes }}` (release-notes.md only) renders the five latest published GitHub + Releases as a table, fetched once per build (drafts excluded). If the API is unreachable + it degrades to a plain link — the build never fails offline. CI passes `GITHUB_TOKEN` + only to lift the anonymous rate limit; publishing a release refreshes the table on the + next docs build. + +## Navigation + +There is a single `nav` in `mkdocs.yml` with English titles. Chinese titles come from +`plugins.i18n.languages[zh].nav_translations`. When adding a page: + +1. Add the page to `nav` (English title). +2. Add the same English title → Chinese title mapping to `nav_translations`. + +Non-site files are kept out of the build by `mkdocs-exclude` +(`README.md`, `serve.sh`, `hooks.py`, `main.py`, `javadoc/*`, `overrides/*`). `docs/api/` is +**not** excluded: when present (after `docs/serve.sh`), MkDocs copies it verbatim so the +Javadoc is reachable at `/api/` in local preview; CI attaches it to `site/api/` post-build. + +## Local build & preview + +```bash +# one-time: Python deps (mkdocs 1.x + Material + i18n + macros + jieba) +pip3 install --user -r requirements-doc.txt + +# guides only — strict mode fails on any warning (broken links, missing nav, …) +python3 -m mkdocs build --strict + +# full preview incl. Javadoc under /api/ (needs JDK 17; override with JDK17=/path/to/jdk17) +bash docs/serve.sh # then open http://127.0.0.1:8000 +``` + +`docs/api/` is generated output (gitignored); never edit or commit it. + +## Javadoc generation + +```bash +# run with JDK 17 +mvn -Pdocs -DskipTests -Dgpg.skip=true generate-sources javadoc:javadoc +``` + +- The `docs` Maven profile delomboks `src/main/java` into + `target/generated-sources/delombok` (so builder methods appear in the docs), then runs + `maven-javadoc-plugin` over `com.alibaba.dashscope` **including `legacy_2x`**, with + `doclint none` and parsing level 17 (shipped bytecode stays Java 8). +- Output lands in `target/apidocs`. `docs/serve.sh` and the CI workflow append + `docs/javadoc/material-bridge.css` to `target/apidocs/stylesheet.css` and copy the tree + into the site under `/api/` (the plugin's `addStylesheets` option is unreliable, hence the + post-hoc append). + +## CI publishing + +`.github/workflows/docs.yml`: + +- **Pull requests** touching docs/site inputs: strict build only (no deploy). +- **Push to `main`/`master`**: build (Javadoc + strict MkDocs), attach Javadoc under + `site/api/`, deploy to GitHub Pages via `actions/deploy-pages`. +- **Release published**: a dispatcher job re-runs the workflow on `main` so the published + site always reflects the default branch. + +One-time repository setup: **Settings → Pages → Build and deployment → Source: +GitHub Actions**. No `gh-pages` branch is used. diff --git a/docs/assets/logo.svg b/docs/assets/logo.svg new file mode 100644 index 00000000..d1617b98 --- /dev/null +++ b/docs/assets/logo.svg @@ -0,0 +1,7 @@ + + + + + + \ No newline at end of file diff --git a/docs/en/about.md b/docs/en/about.md new file mode 100644 index 00000000..75544369 --- /dev/null +++ b/docs/en/about.md @@ -0,0 +1,50 @@ +# About + +## The project + +`dashscope-sdk-java` is the official Java client for +[DashScope](https://dashscope.aliyuncs.com) / Alibaba Cloud Model Studio (Bailian). It targets +**Java 8+** at runtime and is built with a JDK 8 toolchain (cross-checked with `release 8` on +modern JDKs). + +- Source: [github.com/dashscope/dashscope-sdk-java](https://github.com/dashscope/dashscope-sdk-java) +- Artifact: [`com.alibaba:dashscope-sdk-java`](https://central.sonatype.com/artifact/com.alibaba/dashscope-sdk-java) on Maven Central +- Service docs: [Model Studio](https://www.alibabacloud.com/help/en/model-studio/) +- API docs: the [API Reference](reference.md) page links the generated Javadoc under `/api/`. + +## License + +Apache License 2.0 — see +[LICENSE](https://github.com/dashscope/dashscope-sdk-java/blob/main/LICENSE) and +[NOTICE](https://github.com/dashscope/dashscope-sdk-java/blob/main/NOTICE). + +## Compatibility and versioning + +- 3.x is the resource-client line for Java 8+. +- The frozen 2.x API requires `com.alibaba.dashscope.legacy_2x.*` imports on the 3.x artifact. It is deprecated and planned for removal in 4.0; see [migration](migrating.md). +- Documentation source version: **{{ sdk_version }}**. See [release notes](release-notes.md) for published releases. + +## Getting help + +- Report bugs and request features via [GitHub Issues](https://github.com/dashscope/dashscope-sdk-java/issues). +- Start with [Quickstart](quickstart.md), find runnable code in [Examples](examples.md), or see [Errors and diagnosis](guides/errors.md) for failing requests. +- To contribute, follow the [developer guide](develop.md). + +## Runtime dependencies + +Versions as declared in the root +[`pom.xml`](https://github.com/dashscope/dashscope-sdk-java/blob/main/pom.xml): + +| Dependency | Version | Role | +|---|---|---| +| `com.squareup.okhttp3:okhttp` | 4.12.0 | HTTP transport (shared connection pool) | +| `com.squareup.okhttp3:okhttp-sse` | 4.12.0 | Server-sent events for streaming | +| `com.squareup.okhttp3:logging-interceptor` | 4.12.0 | Opt-in network logging | +| `com.squareup.okio:okio` | 3.6.0 | OkHttp I/O layer | +| `org.jetbrains.kotlin:kotlin-stdlib-jdk8` | 1.8.21 | Required by OkHttp 4.x | +| `com.fasterxml.jackson.core:jackson-databind` | 2.22.4 | Typed request/response (de)serialization | +| `com.google.code.gson:gson` | 2.8.9 | JSON handling in shared utilities | +| `io.reactivex.rxjava2:rxjava` | 2.2.21 | Async streaming (`Flowable`) | +| `org.slf4j:slf4j-api` | 2.0.7 | Logging facade (bring your own binding) | +| `com.github.victools:jsonschema-generator` | 4.31.1 | Tool/function-call JSON schema generation | +| `org.projectlombok:lombok` | 1.18.42 | **Compile-time only** (`provided`) — builders, not a runtime dependency | diff --git a/docs/en/develop.md b/docs/en/develop.md new file mode 100644 index 00000000..82987d6e --- /dev/null +++ b/docs/en/develop.md @@ -0,0 +1,30 @@ +# Developer guide + +## Set up a checkout + +Use Maven and JDK 8+ for SDK development. The SDK targets Java 8; on newer JDKs the build validates the Java 8 API surface. Use JDK 17 for full Javadoc generation. + +## Format and test + +```bash +bash lint.sh # applies google-java-format to SDK and test sources +mvn clean test +mvn install -DskipTests -Dgpg.skip=true -Dmaven.javadoc.skip=true +mvn -f examples/pom.xml clean test +``` + +The full SDK suite includes Qwen tokenizer tests. To run them offline, provision the vocabulary before `mvn clean test` and point `DASHSCOPE_QWEN_VOCAB` at it. See [tokenization](guides/tokenization.md). + +Install the SDK from the same checkout before testing the separately built examples. See [examples](examples.md) for individual commands and dry-run boundaries. + +## Preview the docs + +```bash +python3 -m venv .venv-docs +source .venv-docs/bin/activate +python -m pip install -r requirements-doc.txt +python -m mkdocs build --strict +JDK17=/path/to/jdk17 bash docs/serve.sh # preview with generated Javadoc +``` + +Update English and Simplified Chinese together. See the [maintenance guide](https://github.com/dashscope/dashscope-sdk-java/blob/main/docs/README.md) and [shared site template](https://github.com/dashscope/dashscope-sdk-java/blob/main/DOCS_TEMPLATE.md). diff --git a/docs/en/examples.md b/docs/en/examples.md new file mode 100644 index 00000000..1a9687c2 --- /dev/null +++ b/docs/en/examples.md @@ -0,0 +1,62 @@ +--- +description: "Run Java SDK examples offline or against Model Studio, from chat and streaming to complete applications." +--- +# Examples + +Start with a runnable class, then use its guide to understand the SDK calls it makes. The examples are a separate Maven project under `examples/`; use a checkout or tag that matches your target SDK. See the [full repository catalog](https://github.com/dashscope/dashscope-sdk-java/blob/main/examples/README.md) for exact classes, inputs, and flags. + +## Run your first example + +Clone the [Java SDK repository](https://github.com/dashscope/dashscope-sdk-java). In its root, with JDK 8+ and Maven, install the SDK from that checkout into your local Maven repository: + +```bash +mvn install -DskipTests -Dgpg.skip=true -Dmaven.javadoc.skip=true +``` + +=== "Offline: success and errors" + + ```bash + mvn -q -f examples/pom.xml compile exec:java \ + -Dexec.mainClass=com.alibaba.dashscope.examples.engineering.testing.LocalMockDebugging + ``` + + No API key or cloud request. Look for response text, token usage, a typed exception, and an inline error response. The gateway listens on loopback; see [local mock debugging](guides/local-mock.md). + +=== "Cloud: chat and streaming" + + ```bash + export DASHSCOPE_API_KEY="" + mvn -q -f examples/pom.xml compile exec:java \ + -Dexec.mainClass=com.alibaba.dashscope.examples.atomic.chat.ChatCompletionsCreate + ``` + + Look for a complete reply and then incremental text. If needed, configure your region, workspace and model. See [configuration](guides/configuration.md). Cloud calls may incur charges. + +## Find an example by capability + +The following example class names are relative to `com.alibaba.dashscope.examples.`. Substitute the full name in `-Dexec.mainClass` above. + +| I want to… | Example class | Learn how | +| --- | --- | --- | +| Chat or stream, synchronously or asynchronously | `atomic.chat.ChatCompletionsCreate`, `atomic.chat.ChatCompletionsCreateAsync` | [Chat and streaming](guides/chat.md), [async client](guides/async.md) | +| Ask a question about an image | `atomic.multimodal.MultimodalChatCreate` | [Multimodal](guides/multimodal.md) | +| Retrieve and rerank knowledge | `atomic.embeddings.EmbeddingsCreate`, `atomic.rerank.RerankCreate` | [Embeddings and rerank](guides/embeddings-rerank.md) | +| Generate media and track jobs | `atomic.images.ImagesGenerate`, `atomic.videos.VideosGenerate` | [Images and videos](guides/images-videos.md) | +| Synthesize, transcribe, or start a realtime session | `atomic.audio.*` — start with the guide's example for your transport and audio input | [Audio](guides/audio.md) | +| Upload data or monitor fine-tuning | `atomic.files.FilesManage`, `atomic.finetunes.FineTunesCreate` | [Files and fine-tuning](guides/files-finetunes.md) | +| Count tokens locally or remotely | `atomic.chat.TokenizationLocalCount`, `atomic.chat.TokenizationCount` | [Tokenization](guides/tokenization.md) | +| Call an app or get a structured decision | `atomic.apps.AppsCompletionsCreate`, `atomic.decision.DecisionCreate` | [App example](https://github.com/dashscope/dashscope-sdk-java/blob/main/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/apps/AppsCompletionsCreate.java), [decision example](https://github.com/dashscope/dashscope-sdk-java/blob/main/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/decision/DecisionCreate.java) | +| Run a managed agent and consume session events | `recipes.agentstudio.AgentStudioQuickStart` | [AgentStudio](guides/agentstudio.md) | + +## Go from a call to an application + +| Layer | What to look for | +| --- | --- | +| `01_atomic_capabilities` | One capability per class: request builders, typed responses, and inputs. | +| `02_advanced_engineering` | Inject a mock, cache results, or use a circuit breaker to switch regions. | +| `03_agent_recipes` | Combine calls in a tool loop, a RAG pipeline, or a managed AgentStudio workflow. | +| `04_real_world_scenarios` | Customer service uses cloud calls. `scenarios.rag.ProductionRagHarness`, `scenarios.meeting.RealtimeMeetingHarness`, and `scenarios.triage.TicketTriageHarness` default to local demos. | + +After installing the SDK from the same checkout, run `mvn -f examples/pom.xml clean test` to exercise the example dry runs without a cloud key. The suite uses mock endpoints; hardware-dependent microphone input and the HTTPS batch-transcription download are not covered. Maven may still need to fetch dependencies on first use. + +Use a test workspace for examples that create resources. Some audio examples need an input file or a microphone. The [legacy archive](https://github.com/dashscope/dashscope-sdk-java/tree/main/examples/legacy_2x) is not built by the examples project; use the [migration guide](migrating.md) when adapting a 2.x example. diff --git a/docs/en/features.md b/docs/en/features.md new file mode 100644 index 00000000..3b150e97 --- /dev/null +++ b/docs/en/features.md @@ -0,0 +1,65 @@ +--- +description: "Java SDK features: resources, usage, protocols, configuration, development tools, and compatibility." +--- +# Features + +The DashScope Java SDK is a typed, resource-style client for Alibaba Cloud Model Studio. Core HTTP resources share the `DashScopeClient` OkHttp connection pool. Build requests with typed builders and read typed responses. + +## Resource map { #resource-map } + +| Capability | Client accessor | Guide | +| --- | --- | --- | +| Chat and tool calls | `client.chat()` | [Chat and streaming](guides/chat.md) | +| Multimodal understanding | `client.multimodal()` | [Multimodal](guides/multimodal.md) | +| Embeddings and rerank | `client.embeddings()`, `client.rerank()` | [Embeddings and rerank](guides/embeddings-rerank.md) | +| Image and video generation | `client.images()`, `client.videos()` | [Images and videos](guides/images-videos.md) | +| Speech and meetings | `client.audio()`, `client.tingwu()` | [Audio](guides/audio.md) | +| Files, models, and fine-tuning | `client.files()`, `client.models()`, `client.fineTunes()`, `client.deployments()` | [Files and fine-tuning](guides/files-finetunes.md) | +| Managed agents and Workflows | `client.agentStudio()` | [AgentStudio](guides/agentstudio.md) | +| Token counting | `client.tokenization()` | [Tokenization](guides/tokenization.md) | +| Applications and decisions | `client.apps()`, `client.decision()` | [Client resources](reference/resources.md) | + +Find short calls in [capability recipes](guides/recipes.md), and source code and run commands in the [examples hub](examples.md). + +## Sync and async { #sync-async } + +- Use `DashScopeClient` for sync calls. `DashScopeAsyncClient` returns `CompletableFuture` for unary operations and RxJava `Flowable` for streaming. Manage client lifetime with try-with-resources. +- The async `audio()` accessor supports batch ASR only; duplex WebSocket sessions use the sync client. The audio module is still under development, so check for interface changes when upgrading. + +See [async client](guides/async.md). + +## Streaming { #streaming } + +Chat streams return incremental output over SSE. Sync `createStreaming()` returns a closeable, iterable `ResponseStream`; read the delta from each chunk and close the stream even when stopping early. Interrupted streams are not automatically resumed. + +See [chat and streaming](guides/chat.md). + +## Protocols and transport { #protocols } + +- **Chat:** `chat().completions()` uses the native Model Studio API: HTTP/JSON for regular requests and SSE for streamed responses. Java has no `protocol` option for switching to OpenAI-compatible or Anthropic-compatible chat protocols. See [protocols and transport](reference/protocols.md). +- **Duplex audio:** speech and realtime APIs that need bidirectional transport use WebSocket. Choose an [HTTP or WebSocket audio API](guides/audio.md) for your task. + +## Configuration and request options { #configuration } + +Configuration resolves from explicit builder options → JVM system properties → environment variables → `~/.dashscope/config.toml` → defaults. The API key can also fall back to a saved key file. `ClientOptions` covers endpoints, region, workspace, timeouts, retries, custom OkHttp clients, and executors. Use `RequestOptions` to override timeout, retries, credentials, and headers per request. + +See [configuration](guides/configuration.md). + +## Errors and diagnosis { #errors } + +Failed requests raise typed `DashScopeException` subclasses by default. Read the error code, HTTP status, and request ID. Non-streaming HTTP calls retry eligible failures according to policy. When investigating auth, rate limits, or network failures, capture both the request ID and error code. + +See [errors and diagnosis](guides/errors.md). + +## Local development { #local-development } + +- **Mock debugging:** point `baseUrl` at a loopback mock gateway to exercise success and failure paths without a real API key. See [local mock debugging](guides/local-mock.md). The example project's Maven dry-run suite also checks examples that can run offline. +- **Tokenization:** use `client.tokenization().count()` for server-side counts or `TokenizerFactory.qwen()` with an available vocabulary to estimate budgets locally. First use may download the vocabulary. See [tokenization](guides/tokenization.md). + +## SDK-specific capabilities { #sdk-specific } + +- **Request envelope encryption:** opt in for an HTTP request with `enableEncryption(true)` in `RequestOptions`. The SDK fetches and caches the gateway public key. See [encrypted channel](guides/configuration.md). + +## Legacy compatibility { #legacy } + +Use 3.x resources for new code. The frozen 2.x API lives under `com.alibaba.dashscope.legacy_2x.*`; upgrading from the old artifact requires changing imports, and the facade is planned for removal in 4.0. See [migration](migrating.md). diff --git a/docs/en/guides/agentstudio.md b/docs/en/guides/agentstudio.md new file mode 100644 index 00000000..576d4be0 --- /dev/null +++ b/docs/en/guides/agentstudio.md @@ -0,0 +1,169 @@ +# AgentStudio + +AgentStudio is the managed-agent platform: environments, agents, sessions, events, files, +memory stores, vaults, skills, webhooks, and scheduled deployments. It is **shared by the 2.x +and 3.0 SDK generations** and is not deprecated. + +`client.agentStudio()` lazily mounts a single shared `AgentStudioClient` — workspace and region +forward from the client config, but the 3.0 `baseUrl` does **not** apply; override its endpoint +with `DASHSCOPE_AGENTSTUDIO_URL`. The subarea allocates its own HTTP clients; errors use the 3.0 +unchecked exception family. + +## Resources + +| Accessor (`studio.*`) | Manages | +|---|---| +| `environments()` | Sandboxed execution environments | +| `agents()` | Agent definitions (system prompt, model, tools) | +| `dynamicWorkflows()` | Published JavaScript Workflow definitions and fixed versions | +| `sessions()` | Conversation sessions; `sessions().events()` sends/streams events | +| `deployments()` / `deploymentRuns()` | Scheduled agent deployments and their runs | +| `memoryStores()` | Persistent memory: `memories()`, `memoryVersions()` | +| `files()` | Session/agent files | +| `vaults()` | Credential vaults | +| `skills()` | Reusable skills | +| `webhookEndpoints()` | Webhook subscriptions | +| `security()` / `usage()` | Security settings and usage reports | + +## End-to-end quickstart + +Create environment → create agent → create session → send message → stream events → archive. +Adapted from +[AgentStudioQuickStart](https://github.com/dashscope/dashscope-sdk-java/blob/main/examples/03_agent_recipes/com/alibaba/dashscope/examples/recipes/agentstudio/AgentStudioQuickStart.java): + +```java +import com.alibaba.dashscope.applications.agentstudio.AgentStudioClient; +import com.alibaba.dashscope.applications.agentstudio.message.ClientEvents; +import com.alibaba.dashscope.applications.agentstudio.model.Agent; +import com.alibaba.dashscope.applications.agentstudio.model.Environment; +import com.alibaba.dashscope.applications.agentstudio.model.Session; +import com.alibaba.dashscope.applications.agentstudio.param.AgentCreateParam; +import com.alibaba.dashscope.applications.agentstudio.param.EnvironmentCreateParam; +import com.alibaba.dashscope.applications.agentstudio.param.SessionCreateParam; +import com.alibaba.dashscope.applications.agentstudio.resource.AgentStudioEventStream; + +try (DashScopeClient client = DashScopeClient.builder() + .workspace("trial") // DASHSCOPE_WORKSPACE selects the AgentStudio workspace + .build()) { + AgentStudioClient studio = client.agentStudio(); + + Environment env = studio.environments().create( + EnvironmentCreateParam.builder().name("quickstart-env").config(config).build()); + Agent agent = studio.agents().create( + AgentCreateParam.builder() + .name("quickstart-agent") + .systemPrompt("You are a friendly demo agent. Reply briefly.") + .model("qwen3.8-max") + .tools(tools) + .build()); + Session session = studio.sessions().create( + SessionCreateParam.builder() + .agent(agent.getId()).environmentId(env.getId()).title("quickstart").build()); + + studio.sessions().events().send(session.getId(), + Collections.singletonList(ClientEvents.userMessage("Tell me a fun fact about Hangzhou."))); + + try (AgentStudioEventStream stream = studio.sessions().events().stream(session.getId())) { + for (String text : stream.textStream()) { + System.out.print(text); + } + } +} +``` + +??? example "Full runnable example: AgentStudioQuickStart.java (auto-synced)" + ```java + --8<-- "examples/03_agent_recipes/com/alibaba/dashscope/examples/recipes/agentstudio/AgentStudioQuickStart.java" + ``` + +## SSE stream semantics + +`AgentStudioEventStream` is `Iterable` + `Closeable` with deliberate constraints: + +- **Single-pass**: the queue drains into one reader; a second `iterator()` throws + `IllegalStateException`. Open another stream to read events again. +- `textStream()` yields terminal full text; `textDeltas()` yields incremental deltas **only + when the stream was opened with `event_deltas`** — + `events().stream(sessionId, Arrays.asList("message"))` (also accepts `"reasoning"`). +- An idle gap longer than the stream timeout throws `ApiTimeoutException` (distinct from real + end-of-stream). + +## Memory stores + +Persistent, versioned memory the agent can read. Adapted from +[AgentStudioMemoryStores](https://github.com/dashscope/dashscope-sdk-java/blob/main/examples/03_agent_recipes/com/alibaba/dashscope/examples/recipes/agentstudio/AgentStudioMemoryStores.java): + +```java +MemoryStore store = studio.memoryStores().create( + MemoryStoreCreateParam.builder() + .name("demo-preferences") + .description("Per-user preferences and project context.") // read by the agent + .build()); + +Memory memory = studio.memoryStores().memories().create(store.getId(), + MemoryCreateParam.builder() + .path("/formatting_standards.md") + .content("All reports use GAAP formatting.") + .build()); + +// view=full returns content (default basic is metadata only); iteration auto-paginates. +CursorPage page = studio.memoryStores().memories() + .list(store.getId(), MemoryListParam.builder().view("full").build()); + +// Optimistic-lock update: pass the contentSha256 you read. +Memory updated = studio.memoryStores().memories().update(store.getId(), memory.getId(), + MemoryUpdateParam.builder() + .content("All reports use GAAP formatting. ISO-8601 dates.") + .contentSha256(memory.getContentSha256()) + .build()); + +// Every mutation produces a version snapshot; versions can be redacted. +studio.memoryStores().memoryVersions().list(store.getId(), MemoryVersionListParam.builder().build()); +studio.memoryStores().delete(store.getId()); +``` + +??? example "Full runnable example: AgentStudioMemoryStores.java (auto-synced)" + ```java + --8<-- "examples/03_agent_recipes/com/alibaba/dashscope/examples/recipes/agentstudio/AgentStudioMemoryStores.java" + ``` + +## Dynamic Workflows + +`studio.dynamicWorkflows()` exposes `create`, `retrieve`, `update`, `list`, +`archive`, `listVersions` and `retrieveVersion`. Each operation has an +`Async` counterpart returning `CompletableFuture`. Creation publishes version 1; +updates publish a new immutable version. An empty update leaves the version unchanged. + +Updates preserve omitted fields. Set `clearDescription(true)` to send +`description: null`, or `clearInputSchema(true)` to send `input_schema: null`. +An empty `JsonObject` also clears input constraints. Do not combine a clear flag +with a value for the same field. + +`list` accepts `limit`, `page` and `includeArchived`; `listVersions` accepts +`limit` and `page`. Both return `CursorPage`: iteration fetches +subsequent pages and `getNext()` returns a future. List items include the script +and input schema. Archiving preserves the published status and version; details +and fixed versions remain readable, while updates are rejected. + +On Agent creation or update, `multiagent.workflows` controls inline creation +(`inline_agents` and `predefined_agents`), while `multiagent.reuse_workflows` +controls reuse of the bound Workflow IDs and fixed versions. The two permission +switches are independent. Agent Workflow tools initiate execution; the management +resource does not run Workflows. Send the complete nested configuration you intend +to retain on Agent update, and use the returned Agent version for new Sessions. + +The example requires `DASHSCOPE_API_KEY` and a configured workspace, for example +`DASHSCOPE_WORKSPACE`. It demonstrates all seven operations, explicit nulls and +Agent bindings, then archives its dedicated Agent and Workflow in `finally`. + +??? example "Full runnable example: AgentStudioDynamicWorkflows.java (auto-synced)" + ```java + --8<-- "examples/03_agent_recipes/com/alibaba/dashscope/examples/recipes/agentstudio/AgentStudioDynamicWorkflows.java" + ``` + +## More examples + +- [AgentStudioDeploymentsManage](https://github.com/dashscope/dashscope-sdk-java/blob/main/examples/03_agent_recipes/com/alibaba/dashscope/examples/recipes/agentstudio/AgentStudioDeploymentsManage.java) + — scheduled deployments. +- Javadoc: + [AgentStudio API](../reference/agentstudio.md). diff --git a/docs/en/guides/async.md b/docs/en/guides/async.md new file mode 100644 index 00000000..e9bb9b8d --- /dev/null +++ b/docs/en/guides/async.md @@ -0,0 +1,74 @@ +# Async Client + +`DashScopeAsyncClient` provides async counterparts for most resources. Supported unary calls return +`CompletableFuture`; streaming calls return RxJava `Flowable`. These services delegate to sync +implementations on an executor and share the retry, error, and configuration behavior. + +The async `audio()` accessor only exposes batch ASR. Use the synchronous [audio API](../reference/audio.md) for duplex WebSocket sessions. + +Adapted from the runnable +[ChatCompletionsCreateAsync](https://github.com/dashscope/dashscope-sdk-java/blob/main/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/chat/ChatCompletionsCreateAsync.java). + +??? example "Full runnable example: ChatCompletionsCreateAsync.java (auto-synced)" + ```java + --8<-- "examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/chat/ChatCompletionsCreateAsync.java" + ``` + +## Unary calls: CompletableFuture + +```java +import com.alibaba.dashscope.DashScopeAsyncClient; +import com.alibaba.dashscope.types.completions.ChatCompletion; +import java.util.concurrent.CompletableFuture; + +try (DashScopeAsyncClient client = DashScopeAsyncClient.builder().build()) { + // The call returns immediately; compose on the future. + CompletableFuture future = client.chat().completions().create(params); + CompletableFuture answer = future.thenApply(resp -> { + System.out.println(resp.outputText()); + System.out.println("usage: " + resp.getUsage().getTotalTokens() + + " tokens, request_id: " + resp.getRequestId()); + return resp.outputText(); + }); + answer.join(); +} +``` + +Failures complete the future exceptionally with the same typed +[DashScopeException family](errors.md) the sync client throws — unwrap +`CompletionException.getCause()` when handling. + +## Streaming: Flowable + +```java +import com.alibaba.dashscope.types.completions.ChatCompletionChunk; +import com.alibaba.dashscope.types.completions.Delta; +import io.reactivex.Flowable; + +Flowable stream = client.chat().completions().createStreaming(params); +// blockingForEach consumes chunks on the calling thread; subscribe(...) for reactive pipelines. +stream.blockingForEach(chunk -> { + Delta delta = chunk.delta(); + if (delta != null && delta.getContent() != null) { + System.out.print(delta.getContent()); + System.out.flush(); + } +}); +``` + +## Lifecycle & executor + +- Work runs on a **daemon executor owned by the client**; try-with-resources (`close()`) shuts + it down. Create one client and share it — do not build a client per call. +- Inject your own executor with `DashScopeAsyncClient.builder().executor(...)` to control + threading; when injected, **you own its lifecycle** (the SDK will not shut it down). The same + applies to `httpClient(...)`. See [Configuration](configuration.md). + +## Sync vs async at a glance + +| | `DashScopeClient` | `DashScopeAsyncClient` | +|---|---|---| +| Unary | `ChatCompletion create(params)` | `CompletableFuture create(params)` | +| Streaming | `ResponseStream` (for-each, try-with-resources) | `Flowable` (blockingForEach / subscribe) | +| Per-request options | `(params, RequestOptions)` overload | same | +| Closing | try-with-resources | try-with-resources (also shuts down the owned executor) | diff --git a/docs/en/guides/audio.md b/docs/en/guides/audio.md new file mode 100644 index 00000000..e5309e1b --- /dev/null +++ b/docs/en/guides/audio.md @@ -0,0 +1,150 @@ +# Audio (TTS / ASR / Realtime) + +`client.audio()` groups the speech resources: `tts()` (synthesis), `asr()` (recognition), +`realtime()` (spoken dialog over WebSocket), plus `voices()`, `vocabularies()`, `phrases()` and +`voiceDesign()`. TingWu meeting transcription lives at `client.tingwu()`. All snippets are +adapted from the runnable +[audio examples](https://github.com/dashscope/dashscope-sdk-java/tree/main/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/audio). + +!!! warning "Under development" + The `client.audio()` module is still under development; interfaces may change in future + releases (matching the Javadoc of the `com.alibaba.dashscope.audio` package; `client.tingwu()` + is not affected). Watch for API changes on this page when upgrading the SDK. + +!!! note "Qwen Live is a separate API" + The 3.x `realtime()` examples below use Omni or Qwen-Audio, not the Qwen Live protocol. + The dedicated `QwenLiveConversation` API is in `legacy_2x.audio.live` on the 3.x artifact. + The archived Qwen Live examples use the old 2.x imports; see [migration](../migrating.md) before reusing them. + +## Text-to-speech + +One-shot HTTP synthesis returns the whole audio as bytes (raw PCM when `format("pcm")`); prefer +the streaming variant for long text: + +```java +import com.alibaba.dashscope.types.audio.TtsSynthesizeParams; + +byte[] pcm = client.audio().tts().http().synthesize( + TtsSynthesizeParams.builder() + .model("qwen-audio-3.1-tts-flash") + .voice("longanhuan_v3.1") + .text("Hello from DashScope") + .format("pcm") // raw PCM; wrap into WAV yourself if needed + .sampleRate(24000) + .build()); +``` + +- `tts().stream(params)` → `ResponseStream` — incremental audio over HTTP. +- `tts().connect(TtsConnectParams)` → `SynthesisSession` — WebSocket synthesis for + incremental text input. + +Examples: `TtsHttpSynthesize`, `TtsHttpStreamSynthesize`, `TtsWebsocketConnect`. + +??? example "Full runnable example: TtsHttpSynthesize.java (auto-synced)" + ```java + --8<-- "examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/audio/TtsHttpSynthesize.java" + ``` + +## Speech recognition + +Realtime recognition opens a `RecognitionSession`: send paced audio frames on one thread while +iterating `results()` on another: + +```java +import com.alibaba.dashscope.resources.audio.RecognitionSession; +import com.alibaba.dashscope.types.audio.AsrRecognizeParams; +import com.alibaba.dashscope.types.audio.AsrResult; + +RecognitionSession session = client.audio().asr().recognize( + AsrRecognizeParams.builder() + .model("qwen-audio-3.1-asr-flash-streaming") + .format("pcm") + .sampleRate(16000) + .build()); +try { + session.start(); + // receiver thread: for (AsrResult r : session.results()) { r.getSentence().getText(); ... } + for (byte[] frame : pcmChunks) { // pace ~100 ms of audio per frame + session.sendAudioFrame(frame); + } + session.stop(); +} finally { + session.close(); +} +``` + +`AsrResult.Sentence.getSentenceEnd()` distinguishes final sentences from partials; +`session.getRequestId()` and `getFirstPackageDelay()` support diagnostics (the delay stays null +when nothing was recognized). + +For file transcription, `asr().transcribe(AsrTranscribeParams)` submits an async `Job` +(`asr().jobs()` to wait/fetch). Examples: `AsrWebsocketRecognize`, `AsrHttpStreamRecognize`, +`AsrMicrophoneRecognize`, `AsrJobsTranscribe`. + +??? example "Full runnable example: AsrWebsocketRecognize.java (auto-synced)" + ```java + --8<-- "examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/audio/AsrWebsocketRecognize.java" + ``` + +## Realtime spoken dialog + +`realtime().connect(RealtimeParams)` opens a `RealtimeSession` (WebSocket). Configure the +session, append audio, then commit and request a response; a single receiver thread consumes +`events()`: + +```java +import com.alibaba.dashscope.resources.audio.RealtimeSession; +import com.alibaba.dashscope.types.audio.RealtimeParams; +import com.alibaba.dashscope.types.audio.UpdateSessionParams; + +RealtimeSession session = client.audio().realtime().connect( + RealtimeParams.builder().model("qwen-audio-3.0-realtime-plus").build()); +try { + session.connect(); + session.updateSession(UpdateSessionParams.builder() + .modalities(Arrays.asList("text", "audio")) + .voice("longanqian") + .inputAudioFormat("pcm") + .outputAudioFormat("pcm") + .enableTurnDetection(false) // manual end-of-turn: commit + createResponse + .build()); + // receiver thread iterates session.events() (single-use stream) + session.appendAudio(pcmFrame); + session.commit(); + session.createResponse(); +} finally { + session.close(); +} +``` + +Examples: `RealtimeQwenAudioDialog` (Qwen-Audio dialect), `RealtimeOmniDialog` (omni), +`RealtimeTranslation` (live translate). + +??? example "Full runnable example: RealtimeQwenAudioDialog.java (auto-synced)" + ```java + --8<-- "examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/audio/RealtimeQwenAudioDialog.java" + ``` + +## Connection reuse & voice management + +- `client.wsConnection()` multiplexes several audio tasks over one WebSocket + (`AudioConnectionReuse`); pass it to `asr().recognize(params, connection)` / + `tts().connect(params, connection)`. +- `audio().voices()` manages cloned voices (`VoiceCloneManage`); `vocabularies()` / `phrases()` + customize recognition; `voiceDesign()` designs voices. +- Behind NAT/proxies, set `wsPingInterval` (20–30 s) to keep WebSockets alive — see + [Configuration](configuration.md). + +## TingWu (meeting transcription) + +```java +Job job = client.tingwu().jobs().create(params); // submit a transcription task +Job done = client.tingwu().jobs().wait(job.getTaskId(), RequestOptions.NONE); +``` + +Example: `TingWuJobsCreate`. + +??? example "Full runnable example: TingWuJobsCreate.java (auto-synced)" + ```java + --8<-- "examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/audio/TingWuJobsCreate.java" + ``` diff --git a/docs/en/guides/chat.md b/docs/en/guides/chat.md new file mode 100644 index 00000000..64e204aa --- /dev/null +++ b/docs/en/guides/chat.md @@ -0,0 +1,134 @@ +# Chat and Streaming + +`client.chat().completions()` is the text-generation entry point — the 3.0 replacement for +2.x `Generation`. Every snippet below is adapted from the runnable +[chat examples](https://github.com/dashscope/dashscope-sdk-java/tree/main/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/chat). + +## Create a completion + +```java +import com.alibaba.dashscope.DashScopeClient; +import com.alibaba.dashscope.types.completions.ChatCompletion; +import com.alibaba.dashscope.types.completions.ChatCompletionCreateParams; +import com.alibaba.dashscope.types.messages.Message; +import java.util.Arrays; +import java.util.List; + +List messages = Arrays.asList( + Message.system("You are a helpful assistant."), + Message.user("Introduce Hangzhou in one sentence")); + +try (DashScopeClient client = DashScopeClient.builder().build()) { + ChatCompletion resp = client.chat().completions().create( + ChatCompletionCreateParams.builder() + .model("qwen-plus") + .messages(messages) + .build()); + System.out.println(resp.outputText()); + System.out.println("usage: " + resp.getUsage().getTotalTokens() + + " tokens, request_id: " + resp.getRequestId()); +} +``` + +`Message` has role factories: `Message.system(...)`, `Message.user(...)`, +`Message.assistant(...)`, `Message.tool(...)` — no role-string plumbing. + +## Multi-turn conversations + +Keep a `List` and append each turn: the user input, then the assistant reply +(`Message.assistant(resp.outputText())`). The API is stateless — the full history travels with +every request. + +## Streaming + +`createStreaming` returns a typed `ResponseStream` — iterable like a plain +collection and `AutoCloseable`. Each chunk's delta carries a content increment (the SDK asks the +server for incremental frames by default when streaming): + +```java +import com.alibaba.dashscope.types.common.ResponseStream; +import com.alibaba.dashscope.types.completions.ChatCompletionChunk; +import com.alibaba.dashscope.types.completions.Delta; + +try (ResponseStream stream = + client.chat().completions().createStreaming( + ChatCompletionCreateParams.builder() + .model("qwen-plus") + .messages(messages) + .build())) { + for (ChatCompletionChunk chunk : stream) { + Delta delta = chunk.delta(); + if (delta != null && delta.getContent() != null) { + System.out.print(delta.getContent()); + System.out.flush(); + } + } +} +``` + +The SDK retry policy does not automatically retry or replay chat SSE requests. An in-stream error frame raises a typed `DashScopeException` during iteration by default. With `raiseOnError(false)`, a chat stream returns a final error chunk; check it with `isError()`. See [Errors and Diagnosis](errors.md). + +## Tool calling (agent loop) + +Send a tool schema with `.tools(...)`; whenever the model asks to call a tool +(`message.getToolCalls()`), execute it locally, append the result as a `role="tool"` message, +and call again — until the model returns a plain answer. Guard the loop with a turn limit. + +```java +import com.alibaba.dashscope.types.completions.ChatCompletionMessage; +import com.alibaba.dashscope.types.messages.ToolCall; + +// tools: OpenAI-shaped function schemas (type=function, function={name, description, parameters}) +List history = new ArrayList<>(); +history.add(Message.system("You are an assistant that can call tools.")); +history.add(Message.user("What's the weather in Hangzhou?")); + +for (int turn = 0; turn < MAX_TURNS; turn++) { + ChatCompletion resp = client.chat().completions().create( + ChatCompletionCreateParams.builder() + .model("qwen-plus") + .messages(history) + .tools(tools) + .build()); + ChatCompletionMessage message = resp.getChoices().get(0).getMessage(); + if (message.getToolCalls() == null || message.getToolCalls().isEmpty()) { + System.out.println("final: " + message.getContent()); + break; + } + // Echo the assistant tool-call turn back verbatim ... + history.add(Message.assistant(message.getContent(), message.getToolCalls())); + // ... then run each tool and append its JSON result. + for (ToolCall call : message.getToolCalls()) { + String result = runTool(call.getFunction().getName(), call.getFunction().getArguments()); + history.add(Message.tool(result, call.getFunction().getName(), call.getId())); + } +} +``` + +The complete state machine (schema builder, JSON argument parsing, error results, `MAX_TURNS` +guard) is the runnable recipe +[ToolCallLoop](https://github.com/dashscope/dashscope-sdk-java/blob/main/examples/03_agent_recipes/com/alibaba/dashscope/examples/recipes/chat/ToolCallLoop.java). + +??? example "Full runnable example: ToolCallLoop.java (auto-synced)" + ```java + --8<-- "examples/03_agent_recipes/com/alibaba/dashscope/examples/recipes/chat/ToolCallLoop.java" + ``` + +## Async + +`DashScopeAsyncClient` mirrors this surface with `CompletableFuture` / `Flowable` — see +[Async Client](async.md). + +## Runnable examples + +| Example | Shows | +|---|---| +| [ChatCompletionsCreate](https://github.com/dashscope/dashscope-sdk-java/blob/main/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/chat/ChatCompletionsCreate.java) | Non-streaming + streaming | +| [ChatCompletionsCreateAsync](https://github.com/dashscope/dashscope-sdk-java/blob/main/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/chat/ChatCompletionsCreateAsync.java) | `CompletableFuture` + `Flowable` | +| [ChatCompletionsCreateEncrypted](https://github.com/dashscope/dashscope-sdk-java/blob/main/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/chat/ChatCompletionsCreateEncrypted.java) | Encrypted HTTP channel | +| [ToolCallLoop](https://github.com/dashscope/dashscope-sdk-java/blob/main/examples/03_agent_recipes/com/alibaba/dashscope/examples/recipes/chat/ToolCallLoop.java) | Multi-turn tool-call agent loop | + +??? example "Full runnable example: ChatCompletionsCreate.java (auto-synced)" + ```java + --8<-- "examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/chat/ChatCompletionsCreate.java" + ``` diff --git a/docs/en/guides/configuration.md b/docs/en/guides/configuration.md new file mode 100644 index 00000000..2e5996b2 --- /dev/null +++ b/docs/en/guides/configuration.md @@ -0,0 +1,120 @@ +# Configuration + +Every setting resolves through a config chain: + +**builder > JVM system property > environment variable > `~/.dashscope/config.toml` > default** + +`wsBaseUrl` has no config-file key; `raiseOnError`, `httpClient` and `executor` are builder-only. +The API key additionally falls back to the 1.x key file (`DASHSCOPE_API_KEY_FILE_PATH` or +`~/.dashscope/api_key`), so `DashScopeClient.builder().build()` works with just +`DASHSCOPE_API_KEY` exported. + +## Client options + +Client-level options (`DashScopeClient.builder()` / `DashScopeAsyncClient.builder()`): + +| Builder method | Environment variable | Default | Description | +|---|---|---|---| +| `apiKey(...)` | `DASHSCOPE_API_KEY` | — | API key (config chain above) | +| `baseUrl(...)` | `DASHSCOPE_BASE_URL` / `DASHSCOPE_HTTP_BASE_URL` | region endpoint | HTTP base URL | +| `wsBaseUrl(...)` | `DASHSCOPE_WEBSOCKET_BASE_URL` | region endpoint | WebSocket base URL | +| `workspace(...)` | `DASHSCOPE_WORKSPACE` | — | Workspace id (required by some APIs, e.g. decision) | +| `region(...)` | `DASHSCOPE_REGION` | `cn-beijing` | MaaS gateway region | +| `timeout(...)` | `DASHSCOPE_TIMEOUT` | 5 minutes | Single-request timeout (`Duration`) | +| `maxRetries(...)` | `DASHSCOPE_MAX_RETRIES` | 2 | Automatic retries on retryable failures | +| `raiseOnError(...)` | — | `true` | `false` switches to 2.x-style `isError()` returns | +| `wsPingInterval(...)` | `DASHSCOPE_WS_PING_INTERVAL` | 0 (off) | WebSocket keepalive ping; 20–30 s behind NAT/proxies | +| `httpClient(...)` | — | SDK-owned | Inject your own `OkHttpClient` (you own its lifecycle) | +| `executor(...)` | — | SDK-owned | Inject the async executor (you own its lifecycle) | + +```java +try (DashScopeClient client = DashScopeClient.builder() + .apiKey(System.getenv("DASHSCOPE_API_KEY")) + .workspace("llm-xxxx") + .timeout(Duration.ofSeconds(60)) + .maxRetries(3) + .build()) { + // ... +} +``` + +Each setting also has a JVM system property (e.g. `-Ddashscope.api.key=sk-...`, +`-Ddashscope.base.url=http://127.0.0.1:8000/api/v1`, `-Ddashscope.timeout=60`), which sits between the +builder and the environment variable in the chain. + +## Config file + +The config file is a flat `key = value` TOML subset; duration values are in **seconds**. +Its path defaults to `~/.dashscope/config.toml` and can be overridden with `DASHSCOPE_CONFIG`: + +```toml +# ~/.dashscope/config.toml +api_key = "sk-..." +workspace = "llm-xxxx" +region = "cn-beijing" +timeout = 300 # seconds +max_retries = 2 +ws_ping_interval = 0 # seconds, 0 = off +``` + +Without `base_url`, the SDK resolves the endpoint from the region and workspace. To override the native HTTP endpoint, provide the full API root (for example, `https://dashscope.aliyuncs.com/api/v1`); the SDK does not append `/api/v1` to an explicit URL. + +## Per-request overrides + +Every resource method has a `(params, RequestOptions)` overload. Null fields inherit the client +config. + +```java +import com.alibaba.dashscope.RequestOptions; +import java.time.Duration; + +RequestOptions options = RequestOptions.builder() + .timeout(Duration.ofSeconds(30)) + .maxRetries(0) + .header("X-Custom-Header", "value") + .enableEncryption(true) // DashScope encrypted HTTP channel for this call + .build(); +client.chat().completions().create(params, options); +``` + +`RequestOptions` supports `timeout`, `maxRetries`, `apiKey`, `workspace`, extra `headers`, +`enableEncryption`, and `wsQueueCapacity` (bounded WebSocket event buffering). + +## Encrypted channel + +`enableEncryption(true)` turns on the DashScope encrypted HTTP channel (RSA envelope +encryption) for that call — useful for sensitive payloads. End-to-end example: +[ChatCompletionsCreateEncrypted](https://github.com/dashscope/dashscope-sdk-java/blob/main/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/chat/ChatCompletionsCreateEncrypted.java). + +??? example "Full runnable example: ChatCompletionsCreateEncrypted.java (auto-synced)" + ```java + --8<-- "examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/chat/ChatCompletionsCreateEncrypted.java" + ``` + +## Custom HTTP client & executor + +Inject your own `OkHttpClient` to control proxies, connection pools, or interceptors — when you +inject it, **you own its lifecycle** (the SDK will not shut it down on `close()`). The same +applies to `executor(...)` on the async client. + +```java +OkHttpClient http = new OkHttpClient.Builder() + .proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.corp", 8080))) + .build(); +try (DashScopeClient client = DashScopeClient.builder().httpClient(http).build()) { + // ... +} +``` + +## Logging & telemetry + +- **Wire logging** (environment variable only): `DASHSCOPE_NETWORK_LOGGING_LEVEL` = `BASIC`, + `HEADERS`, or `BODY` (default `NONE`). The built-in logger masks only predefined headers, not custom credential headers. `BODY` can log request and response content. See [Errors and Diagnosis](errors.md#wire-logging). +- **Telemetry opt-out**: `DASHSCOPE_DISABLE_SDK_HEADERS=1` (or `true`) drops the + `x-dashscope-sdk-client` / `x-dashscope-sdk-session-id` tracking headers; `User-Agent` and + caller-set headers are unaffected. + +## AgentStudio endpoint + +The 3.0 `baseUrl` does **not** apply to AgentStudio. Its endpoint is overridden separately with +`DASHSCOPE_AGENTSTUDIO_URL`. diff --git a/docs/en/guides/embeddings-rerank.md b/docs/en/guides/embeddings-rerank.md new file mode 100644 index 00000000..4a86ca1f --- /dev/null +++ b/docs/en/guides/embeddings-rerank.md @@ -0,0 +1,97 @@ +# Embeddings and Rerank + +Two building blocks for retrieval pipelines: `client.embeddings()` turns text into vectors, +`client.rerank()` reorders candidate documents by relevance to a query. Adapted from the runnable +[EmbeddingsCreate](https://github.com/dashscope/dashscope-sdk-java/blob/main/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/embeddings/EmbeddingsCreate.java) +and +[RerankCreate](https://github.com/dashscope/dashscope-sdk-java/blob/main/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/rerank/RerankCreate.java). + +??? example "Full runnable example: EmbeddingsCreate.java (auto-synced)" + ```java + --8<-- "examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/embeddings/EmbeddingsCreate.java" + ``` + +??? example "Full runnable example: RerankCreate.java (auto-synced)" + ```java + --8<-- "examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/rerank/RerankCreate.java" + ``` + +## Embeddings + +One batch `create` call replaces 2.x `TextEmbedding` / `BatchTextEmbedding`: + +```java +import com.alibaba.dashscope.types.embeddings.Embedding; +import com.alibaba.dashscope.types.embeddings.EmbeddingCreateParams; +import com.alibaba.dashscope.types.embeddings.EmbeddingResponse; +import java.util.Arrays; +import java.util.List; + +List texts = Arrays.asList( + "Hangzhou is the capital of Zhejiang", + "Shanghai is a municipality of China"); + +EmbeddingResponse resp = client.embeddings().create( + EmbeddingCreateParams.builder() + .model("text-embedding-v4") + .texts(texts) + .dimension(1024) + .build()); +for (Embedding item : resp.getEmbeddings()) { + System.out.println("index=" + item.getIndex() + + ", embedding dim=" + item.getEmbedding().size()); +} +System.out.println("usage: " + resp.getUsage().getTotalTokens() + " tokens"); +``` + +### Batch embedding over a file + +For large corpora, an async-task facade embeds a file (one text per line): + +```java +Job job = client.embeddings().jobs().create( + BatchEmbeddingCreateParams.builder() + .model("text-embedding-v4") + .fileUrl("https://.../texts.txt") + .build()); +Job result = client.embeddings().jobs().wait(job.getTaskId(), RequestOptions.NONE); +``` + +## Rerank + +```java +import com.alibaba.dashscope.types.rerank.RerankCreateParams; +import com.alibaba.dashscope.types.rerank.RerankResponse; +import com.alibaba.dashscope.types.rerank.RerankResult; +import java.util.Arrays; + +RerankResponse resp = client.rerank().create( + RerankCreateParams.builder() + .model("gte-rerank-v2") + .query("Where is Harbin?") + .documents(Arrays.asList( + "Heilongjiang borders Russia", + "Harbin is the capital of Heilongjiang, in northeast China")) + .topN(5) + .returnDocuments(true) + .instruct("Retrieval document that can answer users query.") + .build()); +for (RerankResult result : resp.getResults()) { + String document = result.getDocument() == null ? null : result.getDocument().getText(); + System.out.println("index=" + result.getIndex() + + ", score=" + result.getRelevanceScore() + + ", document=" + document); +} +``` + +- `topN` caps how many results come back; `returnDocuments(true)` echoes the document text. +- `instruct` steers the ranking task description (optional). + +## Putting it together (RAG) + +Embed the corpus, retrieve candidates by vector similarity, then rerank the shortlist with +`rerank()` before handing it to the model. Complete pipelines: +[RagExpertSystem](https://github.com/dashscope/dashscope-sdk-java/blob/main/examples/03_agent_recipes/com/alibaba/dashscope/examples/recipes/rag/RagExpertSystem.java) +(recipe) and +[ProductionRagHarness](https://github.com/dashscope/dashscope-sdk-java/blob/main/examples/04_real_world_scenarios/com/alibaba/dashscope/examples/scenarios/rag/ProductionRagHarness.java) +(scenario harness). \ No newline at end of file diff --git a/docs/en/guides/errors.md b/docs/en/guides/errors.md new file mode 100644 index 00000000..ac7fceeb --- /dev/null +++ b/docs/en/guides/errors.md @@ -0,0 +1,112 @@ +# Errors and Diagnosis + +3.0 throws **unchecked** exceptions rooted at +{{ javadoc("DashScopeException", "errors/DashScopeException.html") }} +(a `RuntimeException`) — no more checked `ApiException` / `NoApiKeyException` / +`InputRequiredException`. Every exception carries `code`, `statusCode`, `requestId`, `body`, +and the response `headers`. + +## Exception family + +```text +DashScopeException (RuntimeException) +├── ApiStatusException — HTTP status errors +│ ├── BadRequestException (400) +│ │ └── ContentFilterException (business code: content filtering) +│ ├── AuthenticationException (401) +│ ├── PermissionDeniedException (403) +│ ├── NotFoundException (404) +│ ├── RequestTooLargeException (413) +│ ├── RateLimitException (429) +│ ├── InternalServerException (500) +│ ├── GatewayTimeoutException +│ └── ServiceUnavailableException +├── ApiConnectionException — transport / IO failures +│ └── ApiTimeoutException — request timed out +└── SdkException — SDK-side misuse +``` + +Business error codes (e.g. content filtering) are mapped to typed subclasses by `Errors`; +anything unmapped surfaces as the generic `DashScopeException` / `ApiStatusException` with the +raw `code` intact. SDK-side misuse may also throw plain `IllegalArgumentException`. + +## Catching and diagnosing + +```java +import com.alibaba.dashscope.errors.AuthenticationException; +import com.alibaba.dashscope.errors.DashScopeException; +import com.alibaba.dashscope.errors.RateLimitException; + +try { + ChatCompletion resp = client.chat().completions().create(params); +} catch (RateLimitException e) { + // The SDK may have retried; apply your own backoff and retry budget. +} catch (AuthenticationException e) { + // check DASHSCOPE_API_KEY / workspace +} catch (DashScopeException e) { + System.err.println("code=" + e.getCode() + + " status=" + e.getStatusCode() + + " requestId=" + e.getRequestId()); +} +``` + +When reporting an issue, always include the **`requestId`** — it identifies the exact server-side +request. + +| Symptom | Likely cause | What to do | +|---|---|---| +| `AuthenticationException` (401) | Missing / invalid API key | Check `DASHSCOPE_API_KEY`; see [Configuration](configuration.md) | +| `PermissionDeniedException` (403) | Key lacks access to the model / workspace | Check model authorization and `workspace` | +| `RateLimitException` (429) | QPS / quota exceeded | Back off; the SDK already retries with jitter | +| `ContentFilterException` | Input or output hit content filtering | Adjust the prompt / input | +| `ApiTimeoutException` | Request exceeded `timeout` | Raise `timeout` or use streaming | +| `ApiConnectionException` | Network / DNS / proxy failure | Check connectivity; enable wire logging (below) | +| `SdkException` / `IllegalArgumentException` | Missing required param, client misuse | Fix the call site | + +## Automatic retries + +The SDK retry policy uses the request's retry settings and failure type. It does not check whether the operation is idempotent: + +- Retryable HTTP statuses: **408, 409, 429, 500, 502, 503, 504**, plus connection-level IO + failures. +- Honors `Retry-After` / `Retry-After-ms` / `X-Should-Retry` response headers. +- Exponential backoff **500 ms → 8 s** with ±25% jitter; default `maxRetries = 2` + (client-wide via `maxRetries(...)`, per call via `RequestOptions.maxRetries(...)`). +- **SSE requests and WebSocket handshakes bypass the SDK retry policy.** Do not automatically replay a stream that has already emitted output. + +Do not assume side-effecting operations, such as submitting generation or training jobs, are exempt from retries. To disable SDK retries for a request, pass `RequestOptions.builder().maxRetries(0).build()`; if you already have a task ID, query the original task first. + +For application-level policies (circuit breaking, retry budgets) see the engineering example +[CircuitBreakerRetry](https://github.com/dashscope/dashscope-sdk-java/blob/main/examples/02_advanced_engineering/com/alibaba/dashscope/examples/engineering/resilience/CircuitBreakerRetry.java). + +??? example "Full runnable example: CircuitBreakerRetry.java (auto-synced)" + ```java + --8<-- "examples/02_advanced_engineering/com/alibaba/dashscope/examples/engineering/resilience/CircuitBreakerRetry.java" + ``` + +## Result-style errors (`raiseOnError(false)`) + +Prefer the 2.x style of inspecting errors on the result? Build the client with +`raiseOnError(false)`: + +```java +try (DashScopeClient client = DashScopeClient.builder() + .raiseOnError(false) + .build()) { + ChatCompletion resp = client.chat().completions().create(params); + if (resp.isError()) { + System.err.println(resp.getCode() + ": " + resp.getMessage()); + } +} +``` + +For non-streaming errors that can be represented as a result, check `isError()` with `getCode()` and `getMessage()`. In-stream errors throw by default; with `raiseOnError(false)`, streams that can represent an error, such as chat, return a final error chunk instead. Streams that cannot represent errors as items, such as raw audio bytes, still throw. A non-success HTTP response when opening the stream also still throws. + +## Wire logging { #wire-logging } + +Set `DASHSCOPE_NETWORK_LOGGING_LEVEL` to `BASIC`, `HEADERS`, or `BODY` (default `NONE`) to log +HTTP traffic through SLF4J. The built-in logger masks `Authorization`, `Proxy-Authorization`, `Cookie`, `Set-Cookie`, and `X-DashScope-EncryptionKey`, but not custom credential headers. `BODY` can log sensitive request and response content. Enable it only for data safe to log, and review and redact logs before sharing them. + +To reproduce failures offline with zero tokens and no API key, point `baseUrl` at a local mock +server — see the +[LocalMockDebugging example](https://github.com/dashscope/dashscope-sdk-java/blob/main/examples/02_advanced_engineering/com/alibaba/dashscope/examples/engineering/testing/LocalMockDebugging.java). diff --git a/docs/en/guides/files-finetunes.md b/docs/en/guides/files-finetunes.md new file mode 100644 index 00000000..3b552f6a --- /dev/null +++ b/docs/en/guides/files-finetunes.md @@ -0,0 +1,97 @@ +# Files and Fine-tuning + +The training pipeline: upload a training file (`files()`), create a fine-tune job +(`fineTunes()`), then deploy the tuned model (`deployments()`). `models()` browses the model +catalog. Adapted from the runnable examples +[FilesManage](https://github.com/dashscope/dashscope-sdk-java/blob/main/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/files/FilesManage.java), +[FineTunesCreate](https://github.com/dashscope/dashscope-sdk-java/blob/main/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/finetunes/FineTunesCreate.java), +[DeploymentsManage](https://github.com/dashscope/dashscope-sdk-java/blob/main/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/deployments/DeploymentsManage.java), +[ModelsList](https://github.com/dashscope/dashscope-sdk-java/blob/main/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/models/ModelsList.java). + +??? example "Full runnable example: FilesManage.java (auto-synced)" + ```java + --8<-- "examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/files/FilesManage.java" + ``` + +??? example "Full runnable example: FineTunesCreate.java (auto-synced)" + ```java + --8<-- "examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/finetunes/FineTunesCreate.java" + ``` + +## Files: upload / list / get / delete + +```java +import com.alibaba.dashscope.types.files.DeletionStatus; +import com.alibaba.dashscope.types.files.FileList; +import com.alibaba.dashscope.types.files.FileObject; +import com.alibaba.dashscope.types.files.FileUploadParams; + +FileObject uploaded = client.files().upload( + FileUploadParams.builder() + .file(filePath) // java.nio.file.Path to a JSONL file + .purpose(FileUploadParams.PURPOSE_FINE_TUNE) + .description("training data") + .build()); + +FileList files = client.files().list(1, 10); // paged +FileObject item = client.files().get(uploaded.getFileId()); +DeletionStatus deleted = client.files().delete(uploaded.getFileId()); +``` + +## Fine-tunes + +Read-only inspection runs as-is; **creation is billed** — the examples show the +create → wait → delete lifecycle commented out: + +```java +import com.alibaba.dashscope.types.finetunes.FineTune; +import com.alibaba.dashscope.types.finetunes.FineTuneList; + +FineTuneList page = client.fineTunes().list(1, 10); +FineTune job = client.fineTunes().get(page.getJobs().get(0).getJobId()); + +// Billed lifecycle — uncomment after uploading a training file: +// FineTune created = client.fineTunes().create( +// FineTuneCreateParams.builder() +// .model("qwen-turbo") +// .trainingFileIds(Collections.singletonList(trainingFileId)) +// .mode("sft") +// .hyperParameters(Collections.singletonMap("n_epochs", 2)) +// .finetunedModel("my-finetuned-model") +// .build()); +// FineTune finalJob = client.fineTunes().wait(created.getJobId(), RequestOptions.NONE); +// client.fineTunes().delete(created.getJobId()); +``` + +## Deployments + +Deploy a fine-tuned model to dedicated capacity. **Capacity is billed until the deployment is +deleted**; the create → scale → delete lifecycle is shown commented out in the example: + +```java +import com.alibaba.dashscope.types.deployments.Deployment; +import com.alibaba.dashscope.types.deployments.DeploymentList; + +DeploymentList page = client.deployments().list(1, 10); +Deployment deployment = client.deployments().get(page.getDeployments().get(0).getDeployedModel()); + +// Billed lifecycle: +// Deployment created = client.deployments().create( +// DeploymentCreateParams.builder().model("my-finetuned-model").capacity(1).build()); +// Deployment scaled = client.deployments().scale(created.getDeployedModel(), 2); +// client.deployments().delete(created.getDeployedModel()); +``` + +This is the model-deployment service — not the AgentStudio scheduled-deployment service under +`client.agentStudio().deployments()`. + +## Models + +```java +import com.alibaba.dashscope.types.models.Model; +import com.alibaba.dashscope.types.models.ModelList; + +ModelList page = client.models().list(1, 10); // paged catalog +page = client.models().list(1, 10, "Bailian", RequestOptions.NONE); // provider filter +Model item = client.models().get("qwen-plus"); // get by name +``` \ No newline at end of file diff --git a/docs/en/guides/images-videos.md b/docs/en/guides/images-videos.md new file mode 100644 index 00000000..8ee5905c --- /dev/null +++ b/docs/en/guides/images-videos.md @@ -0,0 +1,90 @@ +# Images and Videos + +`client.images()` and `client.videos()` offer both `generate()` and a manual `jobs()` flow. Use `generate()` when you only need the final result. Explicitly call `jobs().create()` when you need a `task_id` to query later or hand to another process. + +`images().generate()` depends on the model: task-protocol models submit and poll, while models using the synchronous multimodal protocol return in one HTTP request. The SDK wraps either result as a `Job`, but the synchronous result has no task ID to poll. + +!!! note "Billing" + Generation tasks incur charges. The snippets below are adapted from the runnable + [ImagesGenerate](https://github.com/dashscope/dashscope-sdk-java/blob/main/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/images/ImagesGenerate.java) + and + [VideosGenerate](https://github.com/dashscope/dashscope-sdk-java/blob/main/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/videos/VideosGenerate.java) + examples. + +??? example "Full runnable example: ImagesGenerate.java (auto-synced)" + ```java + --8<-- "examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/images/ImagesGenerate.java" + ``` + +??? example "Full runnable example: VideosGenerate.java (auto-synced)" + ```java + --8<-- "examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/videos/VideosGenerate.java" + ``` + +## Image generation + +```java +import com.alibaba.dashscope.resources.jobs.Job; +import com.alibaba.dashscope.types.images.ImageGenerateParams; + +// This example model uses the task protocol: submit and wait. +Job job = client.images().generate( + ImageGenerateParams.builder() + .model("wanx2.1-t2i-turbo") + .prompt("A flower shop with elegant windows and a wooden door") + .n(1) + .size("1024*1024") + .build()); +if (job.isSucceeded()) { + for (String url : job.getImageUrls()) { + System.out.println("image url: " + url); + } +} else { + System.out.println("job failed: " + job.getOutput()); +} +``` + +### Manual async-task flow + +Submit first, then wait or fetch by `task_id` — useful when you want to persist the task id and +poll from another process: + +```java +import com.alibaba.dashscope.RequestOptions; +import com.alibaba.dashscope.types.common.Page; + +Job pending = client.images().jobs().create(params); +String taskId = pending.getTaskId(); + +Job finished = client.images().jobs().wait(taskId, RequestOptions.NONE); // blocks until done +Job snapshot = client.images().jobs().fetch(taskId, RequestOptions.NONE); // one status poll + +Page history = client.images().jobs().list(null, RequestOptions.NONE); // historical tasks +``` + +## Video generation + +Same shape, different result accessor. Video tasks take a while — be patient with `wait`: + +```java +import com.alibaba.dashscope.types.videos.VideoGenerateParams; + +Job job = client.videos().generate( + VideoGenerateParams.builder() + .model("wan2.7-t2v") + .prompt("A kitten running under the moonlight") + .build()); +if (job.isSucceeded()) { + System.out.println("video url: " + job.getVideoUrl()); +} +``` + +`client.videos().jobs().create / wait / fetch / list` mirror the image task flow exactly. + +## Job semantics + +- `Job.isSucceeded()` / `isFinished()` / `getTaskStatus()` report task state; on failure + `getOutput()` carries the server-side detail. +- After submitting a job explicitly, save `getTaskId()` immediately. A synchronous image result has no ID for `fetch` or `wait`; read its output directly. +- The 2.x `ImageSynthesis` / `VideoSynthesis` entry points map here — see + [Migrating from 2.x](../migrating.md). diff --git a/docs/en/guides/local-mock.md b/docs/en/guides/local-mock.md new file mode 100644 index 00000000..b33e5cbe --- /dev/null +++ b/docs/en/guides/local-mock.md @@ -0,0 +1,97 @@ +# Local Mock Debugging + +Develop and debug against a canned gateway with **zero network calls beyond loopback and zero +token cost**. A JDK `HttpServer` serves canned chat envelopes in-process; pointing the client at +it via `builder.baseUrl(...)` exercises success and error paths deterministically — before +spending a single real token. Drop the override and the exact same calling code runs against +the real gateway. + +Full runnable example: +[LocalMockDebugging](https://github.com/dashscope/dashscope-sdk-java/blob/main/examples/02_advanced_engineering/com/alibaba/dashscope/examples/engineering/testing/LocalMockDebugging.java). + +??? example "Full runnable example: LocalMockDebugging.java (auto-synced)" + ```java + --8<-- "examples/02_advanced_engineering/com/alibaba/dashscope/examples/engineering/testing/LocalMockDebugging.java" + ``` + +## The mock gateway + +Route by request body so one server serves many scenarios — a message containing +`trigger-error` gets a 400, anything else a normal completion envelope: + +```java +import com.sun.net.httpserver.HttpServer; +import java.net.InetSocketAddress; + +HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); +server.createContext("/", exchange -> { + String body = new String(readAll(exchange.getRequestBody()), StandardCharsets.UTF_8); + byte[] payload; + int status; + if (body.contains("trigger-error")) { + status = 400; + payload = "{\"code\":\"InvalidParameter\",\"message\":\"mocked bad request\"}" + .getBytes(StandardCharsets.UTF_8); + } else { + status = 200; + payload = ("{\"output\":{\"choices\":[{\"finish_reason\":\"stop\",\"message\":" + + "{\"role\":\"assistant\",\"content\":\"Hello from the local mock.\"}}]}," + + "\"usage\":{\"input_tokens\":8,\"output_tokens\":4,\"total_tokens\":12}," + + "\"request_id\":\"mock-req-1\"}").getBytes(StandardCharsets.UTF_8); + } + exchange.getResponseHeaders().set("Content-Type", "application/json; charset=utf-8"); + exchange.sendResponseHeaders(status, payload.length); + try (OutputStream out = exchange.getResponseBody()) { + out.write(payload); + } + exchange.close(); +}); +server.start(); +``` + +## Point the client at it + +```java +String baseUrl = "http://127.0.0.1:" + server.getAddress().getPort() + "/api/v1"; +try (DashScopeClient client = DashScopeClient.builder() + .apiKey("sk-mock") // never validated by the mock + .baseUrl(baseUrl) // equivalently: -Ddashscope.base.url=http://127.0.0.1:/api/v1 + .build()) { + ChatCompletion resp = client.chat().completions().create( + ChatCompletionCreateParams.builder() + .model("qwen-plus") + .messages(Collections.singletonList(Message.user("Hello"))) + .build()); + System.out.println(resp.outputText()); +} +``` + +## Drill the error paths + +```java +// Path 1: typed exception by default (raiseOnError=true). +try { + chat(client, "trigger-error"); +} catch (DashScopeException exc) { + System.out.println(exc.getClass().getSimpleName() + " " + exc.getCode() + + " status=" + exc.getStatusCode()); +} + +// Path 2: inspect the error inline. The derived client shares the parent's connection pool +// and must not outlive it. +DashScopeClient lenient = + client.withOptions(ClientOptions.builder().raiseOnError(false).build()); +ChatCompletion err = chat(lenient, "trigger-error"); +System.out.println("is_error=" + err.isError() + " code=" + err.getCode()); +``` + +Swap the canned 400 for a 429 envelope or a content-filter business code to rehearse +`RateLimitException` / `ContentFilterException` handling — see [Errors and Diagnosis](errors.md). + +## Offline test suite + +The whole `examples/` project also runs offline against MockWebServer (no API key, no charges): + +```bash +mvn -f examples/pom.xml clean test +``` \ No newline at end of file diff --git a/docs/en/guides/multimodal.md b/docs/en/guides/multimodal.md new file mode 100644 index 00000000..c8edf844 --- /dev/null +++ b/docs/en/guides/multimodal.md @@ -0,0 +1,80 @@ +# Multimodal + +`client.multimodal().chat()` handles image + text understanding (qwen-vl family) — the 3.0 +replacement for 2.x `MultiModalConversation`. Adapted from the runnable +[MultimodalChatCreate](https://github.com/dashscope/dashscope-sdk-java/blob/main/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/multimodal/MultimodalChatCreate.java). + +??? example "Full runnable example: MultimodalChatCreate.java (auto-synced)" + ```java + --8<-- "examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/multimodal/MultimodalChatCreate.java" + ``` + +## Messages: content parts + +Multimodal messages carry a list of typed content parts instead of a plain string: +`ContentPart.image(url)` and `ContentPart.text(...)`. The image URL must be publicly accessible. + +```java +import com.alibaba.dashscope.types.multimodal.ContentPart; +import com.alibaba.dashscope.types.multimodal.MultimodalChatCreateParams; +import com.alibaba.dashscope.types.multimodal.MultimodalChatCompletion; +import com.alibaba.dashscope.types.multimodal.MultimodalMessage; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +String imageUrl = + "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/" + + "zh-CN/20241022/emyrja/dog_and_girl.jpeg"; +List messages = Collections.singletonList( + MultimodalMessage.user( + Arrays.asList(ContentPart.image(imageUrl), ContentPart.text("What is in this picture?")))); + +MultimodalChatCompletion resp = client.multimodal().chat().create( + MultimodalChatCreateParams.builder() + .model("qwen3-vl-plus") + .messages(messages) + .build()); +System.out.println(resp.outputText()); +System.out.println("usage: " + resp.getUsage().getTotalTokens() + + " tokens, request_id: " + resp.getRequestId()); +``` + +## Streaming + +Same shape as text chat, with multimodal chunk types — the text increment lives on the first +choice's message: + +```java +import com.alibaba.dashscope.types.common.ResponseStream; +import com.alibaba.dashscope.types.multimodal.MultimodalChatChunk; +import com.alibaba.dashscope.types.multimodal.MultimodalChoice; + +try (ResponseStream stream = + client.multimodal().chat().createStreaming( + MultimodalChatCreateParams.builder() + .model("qwen3-vl-plus") + .messages(messages) + .build())) { + for (MultimodalChatChunk chunk : stream) { + MultimodalChoice choice = chunk.firstChoice(); + if (choice == null || choice.getMessage() == null) { + continue; + } + String text = choice.getMessage().text(); + if (!text.isEmpty()) { + System.out.print(text); + System.out.flush(); + } + } +} +``` + +## Notes + +- The async client mirrors this surface (`CompletableFuture` / `Flowable`) — see + [Async Client](async.md). +- Realtime omni / live-translate conversations use the WebSocket-based audio resources instead; + see [Audio](audio.md). +- Model availability and supported modalities follow the + [Model Studio model list](https://www.alibabacloud.com/help/en/model-studio/models). \ No newline at end of file diff --git a/docs/en/guides/recipes.md b/docs/en/guides/recipes.md new file mode 100644 index 00000000..492c4764 --- /dev/null +++ b/docs/en/guides/recipes.md @@ -0,0 +1,102 @@ +--- +description: "Quick Java SDK calls by task: chat, multimodal, retrieval, media generation, audio, apps, and AgentStudio." +--- +# Capability recipes + +Use this page to find the method to call and the result to read. Snippets reuse a sync `DashScopeClient` (see [Quickstart](../quickstart.md)); `params` denotes the typed parameters built in the linked guide. The guides show full examples. For run commands, offline mocks, and complete scenarios, see the [examples hub](../examples.md). + +Except for local tokenization and mocks, the calls below require an API key. Some also require a workspace, model access, or specific inputs. Generation jobs and training may incur charges. + +## Chat and multimodal + +```java +ChatCompletion response = client.chat().completions().create( + ChatCompletionCreateParams.builder() + .model("qwen-plus") + .messages(Collections.singletonList(Message.user("Describe Hangzhou in one sentence"))) + .build()); +System.out.println(response.outputText()); + +// The user message in multimodalParams contains ContentPart.image(url) and ContentPart.text(question). +MultimodalChatCompletion visual = client.multimodal().chat().create(multimodalParams); +System.out.println(visual.outputText()); +``` + +Use `createStreaming()` for chat streams. The service must be able to access the image URL. See [chat and streaming](chat.md) and [multimodal](multimodal.md) for working examples. + +## Embeddings, rerank, and token counting + +```java +EmbeddingResponse vectors = client.embeddings().create(embeddingParams); +System.out.println(vectors.getEmbeddings().get(0).getEmbedding().size()); + +RerankResponse ranked = client.rerank().create(rerankParams); +System.out.println(ranked.getResults().get(0).getIndex()); + +TokenCount count = client.tokenization().count(tokenCountParams); +System.out.println(count.getInputTokens()); +``` + +A rerank index refers to the order of `documents` in that request. For offline estimates, use `TokenizerFactory.qwen()` with a pre-provisioned vocabulary. See [embeddings and rerank](embeddings-rerank.md) and [tokenization](tokenization.md). + +## Image and video generation + +```java +Job imageJob = client.images().generate(imageParams); +if (imageJob.isSucceeded()) { + System.out.println(imageJob.getImageUrls()); +} + +Job videoJob = client.videos().generate(videoParams); +if (videoJob.isSucceeded()) { + System.out.println(videoJob.getVideoUrl()); +} +``` + +Use `generate()` when you only need the final result. Some image models return synchronously and their `Job` has no task ID to poll. To wait in another process, explicitly submit with `jobs().create()`, save `getTaskId()`, and query the original task instead of submitting twice. See [images and videos](images-videos.md). + +## Speech and meetings + +| Task | Call | What to check | +| --- | --- | --- | +| HTTP speech synthesis | `client.audio().tts().http().synthesize(ttsParams)` | The result is audio bytes; raw PCM has no WAV header. | +| Batch file recognition | `client.audio().asr().jobs()` | Submit and poll. The [batch transcription example](https://github.com/dashscope/dashscope-sdk-java/blob/main/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/audio/AsrJobsTranscribe.java) shows HTTPS inputs and result downloads. | +| Duplex realtime audio | `client.audio().realtime().connect(realtimeParams)` | Use the sync client and handle pending events before closing the session. | +| TingWu meeting transcription | `client.tingwu().jobs().create(tingwuParams)` | Save `job.getTaskId()` and wait with `jobs().wait(...)`. | + +See the [audio guide](audio.md) for full examples of HTTP, WebSocket, and audio jobs. + +## Files, models, and fine-tuning + +```java +FileObject uploaded = client.files().upload(fileUploadParams); +System.out.println(uploaded.getFileId()); + +ModelList models = client.models().list(1, 10); +FineTuneList jobs = client.fineTunes().list(1, 10); +``` + +For training data, set `FileUploadParams.PURPOSE_FINE_TUNE`. Save the uploaded file ID separately from the fine-tuning job ID. See [files and fine-tuning](files-finetunes.md). + +## Applications and decisions + +```java +AppCompletion app = client.apps().completions().create( + AppCompletionCreateParams.builder().appId(appId).prompt("Hello").build()); +System.out.println(app.getText()); + +DecisionResult decision = client.decision().create(decisionParams); +System.out.println(decision.getAnswers()); +``` + +An app call needs an application ID. Question IDs in the decision request are the keys returned by `getAnswers()`. See the [application](https://github.com/dashscope/dashscope-sdk-java/blob/main/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/apps/AppsCompletionsCreate.java) and [decision](https://github.com/dashscope/dashscope-sdk-java/blob/main/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/decision/DecisionCreate.java) examples. + +## AgentStudio and Dynamic Workflow + +```java +AgentStudioClient studio = client.agentStudio(); +DynamicWorkflow workflow = studio.dynamicWorkflows().create(workflowParams); +System.out.println(workflow.getId()); +``` + +Use a workspace where you have the required permissions. Creating a Workflow publishes its definition; an Agent tool initiates execution. See the [AgentStudio guide](agentstudio.md) for management, binding, and archival. diff --git a/docs/en/guides/tokenization.md b/docs/en/guides/tokenization.md new file mode 100644 index 00000000..6a6a746d --- /dev/null +++ b/docs/en/guides/tokenization.md @@ -0,0 +1,79 @@ +# Tokenization + +Two ways to count tokens: server-side counting via `client.tokenization().count(...)`, and a +fully offline local BPE tokenizer via `TokenizerFactory.qwen()`. Adapted from +[TokenizationCount](https://github.com/dashscope/dashscope-sdk-java/blob/main/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/chat/TokenizationCount.java) +and +[TokenizationLocalCount](https://github.com/dashscope/dashscope-sdk-java/blob/main/examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/chat/TokenizationLocalCount.java). + +??? example "Full runnable example: TokenizationCount.java (auto-synced)" + ```java + --8<-- "examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/chat/TokenizationCount.java" + ``` + +??? example "Full runnable example: TokenizationLocalCount.java (auto-synced)" + ```java + --8<-- "examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/chat/TokenizationLocalCount.java" + ``` + +## Server-side counting + +Count a plain prompt or a full chat message list: + +```java +import com.alibaba.dashscope.types.tokenization.TokenCount; +import com.alibaba.dashscope.types.tokenization.TokenizationCountParams; + +TokenCount resp = client.tokenization().count( + TokenizationCountParams.builder() + .model("qwen-plus") + .prompt("Introduce Hangzhou in one sentence") + .build()); +System.out.println("input_tokens: " + resp.getInputTokens()); +System.out.println("token_ids: " + resp.getTokenIds()); + +// Or over messages: +resp = client.tokenization().count( + TokenizationCountParams.builder() + .model("qwen-plus") + .messages(Arrays.asList( + Message.system("You are a helpful assistant."), + Message.user("Introduce Hangzhou in one sentence"))) + .build()); +``` + +## Local BPE tokenizer (offline) + +`TokenizerFactory.qwen()` needs **no Model Studio API key**. Tokenization runs offline with a local vocabulary; first use may download the vocabulary if it is missing. To stay offline, provision it in advance and set `DASHSCOPE_QWEN_VOCAB`: + +```java +import com.alibaba.dashscope.tokenization.Tokenizer; +import com.alibaba.dashscope.tokenization.TokenizerFactory; +import java.util.List; + +Tokenizer tokenizer = TokenizerFactory.qwen(); + +// Ordinary encoding: special tokens in the text are treated as plain text. +List ids = tokenizer.encodeOrdinary("你好,杭州!"); +System.out.println("token count: " + ids.size()); +System.out.println("decoded: " + tokenizer.decode(ids)); + +// Special-token-aware encoding: "all" recognizes <|im_start|> / <|im_end|> as single tokens. +List chatIds = tokenizer.encode("<|im_start|>user\n你好<|im_end|>", "all"); +``` + +`encode(text, mode)` accepts `"all"`, `"none"` (forbid special tokens), and `"none_raise"` +(throws `NoSpecialTokenException` when the input contains no special token). + +### Vocabulary resolution + +The `qwen.tiktoken` vocabulary is resolved in order from: + +1. `DASHSCOPE_QWEN_VOCAB` (path to a vocab file — useful for hermetic tests), +2. the classpath, +3. a verified local cache, +4. a one-time ModelScope download. + +!!! note "Approximation" + Local results are approximate: they are not guaranteed to match the model's own + tokenization exactly. Use server-side counting when exact billing-relevant counts matter. diff --git a/docs/en/index.md b/docs/en/index.md new file mode 100644 index 00000000..fd7b13fd --- /dev/null +++ b/docs/en/index.md @@ -0,0 +1,187 @@ +# DashScope Java SDK + +

+[**v{{ sdk_version }}**](release-notes.md){ .hero-badge } +[**JDK 8+**](#requirements){ .hero-badge } +[**Apache-2.0**](https://github.com/dashscope/dashscope-sdk-java/blob/main/LICENSE){ .hero-badge } +

+ +The DashScope Java SDK is the official Java client for **Alibaba Cloud Model Studio (Bailian)**: +chat completions, multimodal understanding, embeddings, reranking, image and video generation, +speech synthesis & recognition, realtime voice, fine-tuning, and managed agents and applications. + +
+[Quickstart](quickstart.md){ .md-button .md-button--primary } +[Explore examples](examples.md){ .md-button } +[Get an API key](https://bailian.console.aliyun.com/){ .md-button } +
+ +The SDK is a typed, resource-style client — `DashScopeClient.builder().build()` — modeled on the +ergonomics of the OpenAI SDK: one client holds a shared connection pool, every capability hangs off +it as a typed resource, responses are typed objects, and failures throw typed exceptions by default. + +Migrating existing 2.x code? See [Migrating from 2.x](migrating.md). + +## Features + +
+ +- :material-package-variant:{ .lg .middle } **Typed resources** + + --- + + `client.chat()`, `client.images()`, `client.audio()`, … — every capability + hangs off one client as a typed resource. + +- :material-sync:{ .lg .middle } **Sync & async** + + --- + + `DashScopeAsyncClient` uses `CompletableFuture` for supported unary calls + and RxJava `Flowable` for streams. See [async limits](guides/async.md). + +- :material-waveform:{ .lg .middle } **Text-like streaming** + + --- + + Iterate `ResponseStream` like a plain collection; + each chunk's delta carries a content increment. + +- :material-stethoscope:{ .lg .middle } **Typed errors & diagnosis** + + --- + + Exceptions carry `code` and `request_id`; opt-in retries and a local + mock make failures debuggable offline. + +- :material-lock-outline:{ .lg .middle } **Encrypted channel** + + --- + + Opt-in RSA envelope encryption protects sensitive payloads end to end. + +- :material-archive-outline:{ .lg .middle } **Frozen 2.x facade** + + --- + + Frozen 2.x APIs remain available in 3.x; classes moved to `legacy_2x` require updated imports. + +
+ +The full list: [Features](features.md). + +## Requirements + +- JDK 8 or later. +- A Model Studio API key — create one in the + [Model Studio console](https://bailian.console.aliyun.com/), then export it: + +```bash +export DASHSCOPE_API_KEY="sk-..." +``` + +## Installation + +=== "Maven" + + ```xml + + com.alibaba + dashscope-sdk-java + {{ sdk_version }} + + ``` + +=== "Gradle" + + ```groovy + implementation 'com.alibaba:dashscope-sdk-java:{{ sdk_version }}' + ``` + +## Examples + +### Create it + +```java +import com.alibaba.dashscope.DashScopeClient; + +// Reads DASHSCOPE_API_KEY from the config chain (env / -Ddashscope.api.key / config file). +try (DashScopeClient client = DashScopeClient.builder().build()) { + // every capability hangs off the client +} +``` + +### Run it + +=== "Sync" + + ```java + List messages = Arrays.asList( + Message.system("You are a helpful assistant."), + Message.user("Tell me a joke")); + + ChatCompletion resp = client.chat().completions().create( + ChatCompletionCreateParams.builder() + .model("qwen-plus") + .messages(messages) + .build()); + + System.out.println(resp.outputText()); + System.out.println(resp.getUsage().getTotalTokens()); + ``` + +=== "Async" + + ```java + try (DashScopeAsyncClient client = DashScopeAsyncClient.builder().build()) { + CompletableFuture future = client.chat().completions().create(params); + future.thenAccept(resp -> System.out.println(resp.outputText())).join(); + } + ``` + +### Stream it + +Pass `createStreaming` to get a `ResponseStream`. Each chunk's delta carries a content increment; +the stream is `AutoCloseable` and closes automatically when exhausted: + +```java +try (ResponseStream stream = + client.chat().completions().createStreaming( + ChatCompletionCreateParams.builder() + .model("qwen-plus") + .messages(messages) + .build())) { + for (ChatCompletionChunk chunk : stream) { + Delta delta = chunk.delta(); + if (delta != null && delta.getContent() != null) { + System.out.print(delta.getContent()); + } + } +} +``` + +See [Quickstart](quickstart.md) for the complete walkthrough and [Features](features.md) for the +full capability map. + +## Protocols and transport { #protocols } + +The Java SDK's `chat().completions()` uses the **native Model Studio API**: HTTP/JSON for regular calls and SSE for streamed responses. Duplex realtime [audio APIs](guides/audio.md) use WebSocket. + +Unlike the Python SDK, the Java client has no `protocol=` option for switching among native, OpenAI-compatible, and Anthropic-compatible chat protocols. `baseUrl(...)` and `wsBaseUrl(...)` configure endpoints, not the request protocol. See [protocols and transport](reference/protocols.md). + +## Errors and diagnosis + +Failures raise typed `DashScopeException` subclasses with `code`, `request_id`, and the response body by default. Non-streaming HTTP calls are retried according to the failure and request settings, not the operation's idempotency. SSE bypasses that retry policy. See [Errors and Diagnosis](guides/errors.md) and [Configuration](guides/configuration.md). + +## Legacy 2.x + +When upgrading from 2.x to 3.x, update imports for frozen APIs moved to `com.alibaba.dashscope.legacy_2x`; the old package names are not preserved for those classes. AgentStudio and `shared` are outside the frozen layer. See [Legacy 2.x](legacy.md) and [Migration](migrating.md). + +## Dependencies + +The SDK builds on OkHttp (+ SSE), Jackson, Gson, RxJava 2, SLF4J and victools jsonschema-generator; +Lombok is compile-time only. The full list: see [About](about.md). + +## License + +This project is licensed under the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). diff --git a/docs/en/legacy.md b/docs/en/legacy.md new file mode 100644 index 00000000..0a049b87 --- /dev/null +++ b/docs/en/legacy.md @@ -0,0 +1,56 @@ +# Legacy 2.x + +!!! warning "Deprecated — removed in 4.0" + The legacy 2.x surface is **frozen**: it receives no new features and will be removed in + SDK 4.0. New code should use the [3.0 client](index.md); existing code should plan a + [migration](migrating.md). + +## What moved where + +To keep using frozen APIs moved to `com.alibaba.dashscope.legacy_2x.*` with the 3.x artifact, insert the `legacy_2x` segment in imports and recompile. This rewrite does not apply to AgentStudio or `shared`: + +```java +// 2.x (on the 2.x artifact) +import com.alibaba.dashscope.aigc.generation.Generation; +import com.alibaba.dashscope.common.Message; +import com.alibaba.dashscope.exception.ApiException; + +// 3.0 artifact, legacy facade +import com.alibaba.dashscope.legacy_2x.aigc.generation.Generation; +import com.alibaba.dashscope.legacy_2x.common.Message; +import com.alibaba.dashscope.legacy_2x.exception.ApiException; +``` + +The facades keep the historical behavior: checked `ApiException` / `NoApiKeyException` / +`InputRequiredException`, `ResultCallback` streaming, `Flowable`-based `streamCall`, and +per-capability entry objects (`new Generation()`, `new ImageSynthesis()`, …). + +Every legacy type carries type-level `@Deprecated`; compile with `-Xlint:deprecation` to see +the details and the suggested 3.0 replacement. + +## Not deprecated + +- **AgentStudio** moved to `com.alibaba.dashscope.applications.agentstudio.*` (not under + `legacy_2x`) and is actively developed; it is also reachable via `client.agentStudio()`. +- **`shared`** (`com.alibaba.dashscope.shared.*`) holds neutral constants used by both + generations. +- `assistants.*` / `threads.*` have no 3.0 equivalent yet — keep the `legacy_2x` imports for + those until a replacement ships. + +## Reference & samples + +- Javadoc for the frozen facades: + {{ javadoc("legacy_2x packages in Javadoc") }} + (included in the auto-generated [API Reference](reference.md)). +- Archived runnable 2.x samples: + [examples/legacy_2x/](https://github.com/dashscope/dashscope-sdk-java/tree/main/examples/legacy_2x). +- The root README keeps a legacy appendix with the original 2.x quick-start documentation. + +## Migration + +The [Migrating from 2.x](migrating.md) page has the full entry-point mapping table and a +before/after example. The two changes that touch most code: + +- checked exceptions → the unchecked [DashScopeException family](guides/errors.md) + (or `raiseOnError(false)` for result-style errors); +- per-capability objects → one `DashScopeClient` in try-with-resources. diff --git a/docs/en/migrating.md b/docs/en/migrating.md new file mode 100644 index 00000000..fd0c757a --- /dev/null +++ b/docs/en/migrating.md @@ -0,0 +1,94 @@ +# Migrating from 2.x + +3.0 is an intentional **FQCN, source, and binary compatibility break**. Legacy 2.x APIs other +than AgentStudio moved to `com.alibaba.dashscope.legacy_2x.*`, carry type-level `@Deprecated` +(`-Xlint:deprecation` shows details), and will be **removed in 4.0**. AgentStudio +(`com.alibaba.dashscope.applications.agentstudio.*`) and `shared` are not deprecated. + +Two migration paths: + +1. **Keep compiling now** — prefix your 2.x imports with `legacy_2x` (see [Legacy 2.x](legacy.md)). +2. **Move to the 3.0 client** — use the mapping table below; new code should always use 3.0. + +## Entry-point mapping + +| 2.x class (`com.alibaba.dashscope.*`) | 3.0 equivalent (`client.*`) | +|---|---| +| `aigc.generation.Generation` | `chat().completions().create / createStreaming` | +| `aigc.multimodalconversation.MultiModalConversation` | `multimodal().chat().create / createStreaming` | +| `embeddings.TextEmbedding` / `BatchTextEmbedding` | `embeddings().create` | +| `rerank.TextReRank` | `rerank().create` | +| `aigc.imagesynthesis.ImageSynthesis` | `images().generate` + `jobs().create / wait / fetch` | +| `aigc.videosynthesis.VideoSynthesis` | `videos().generate` + `jobs().*` | +| `app.Application` | `apps().completions().create / createStreaming` | +| `decision.DecisionModel` | `decision().create` | +| `audio.asr.*` / `audio.tts.*` / `audio.qwen_tts_realtime.*` | `audio().asr() / tts() / realtime()` | +| `multimodal.tingwu.TingWu` | `tingwu().jobs().create / wait` | +| `tokenizers.*` | `tokenization().count` / `TokenizerFactory` | +| `assistants.*` / `threads.*` | no 3.0 equivalent yet — keep the `legacy_2x` imports | + +## Before / after + +=== "2.x" + + ```java + import com.alibaba.dashscope.aigc.generation.Generation; + import com.alibaba.dashscope.aigc.generation.GenerationParam; + import com.alibaba.dashscope.aigc.generation.GenerationResult; + import com.alibaba.dashscope.common.Message; + import com.alibaba.dashscope.common.Role; + + Generation generation = new Generation(); + GenerationParam param = GenerationParam.builder() + .apiKey(System.getenv("DASHSCOPE_API_KEY")) + .model("qwen-plus") + .messages(Arrays.asList( + Message.builder().role(Role.USER.getValue()).content("Tell me a joke").build())) + .build(); + GenerationResult result = generation.call(param); // throws checked ApiException + ``` + +=== "3.0" + + ```java + import com.alibaba.dashscope.DashScopeClient; + import com.alibaba.dashscope.types.completions.ChatCompletion; + import com.alibaba.dashscope.types.completions.ChatCompletionCreateParams; + import com.alibaba.dashscope.types.messages.Message; + + // Reads DASHSCOPE_API_KEY from the config chain; one client, shared connection pool. + try (DashScopeClient client = DashScopeClient.builder().build()) { + ChatCompletion resp = client.chat().completions().create( + ChatCompletionCreateParams.builder() + .model("qwen-plus") + .messages(Collections.singletonList(Message.user("Tell me a joke"))) + .build()); + System.out.println(resp.outputText()); + } + ``` + +## Key behavior changes + +- **Exceptions** — checked `ApiException` / `NoApiKeyException` / `InputRequiredException` → + unchecked [DashScopeException family](guides/errors.md). Build the client with + `raiseOnError(false)` to restore 2.x-style result inspection (`result.isError()`). +- **Streaming** — sync `streamCall` returning `Flowable` → `createStreaming` returning a typed + `ResponseStream` (for-each, try-with-resources). The async client still exposes `Flowable`. +- **Client lifecycle** — per-capability `new Generation()` objects → one `DashScopeClient` + (or `DashScopeAsyncClient`) in try-with-resources, sharing connection pool and config. +- **Configuration** — per-param `apiKey(...)` and global constants → the + [config chain](guides/configuration.md): builder > system property > environment variable > + `~/.dashscope/config.toml` > default. `DashScopeClient.builder().build()` works with just + `DASHSCOPE_API_KEY` exported. +- **AgentStudio** — same business package, new FQCN + `com.alibaba.dashscope.applications.agentstudio.*`; also reachable via `client.agentStudio()`. + The 3.0 `baseUrl` does **not** apply to AgentStudio; `DASHSCOPE_AGENTSTUDIO_URL` overrides its + endpoint. + +## Where to go next + +- [Legacy 2.x](legacy.md) — keeping existing code compiling on the 3.0 artifact. +- [Errors and Diagnosis](guides/errors.md) — the new exception family and retry behavior. +- [Configuration](guides/configuration.md) — the config chain and per-request overrides. +- Archived runnable 2.x samples: + [examples/legacy_2x/](https://github.com/dashscope/dashscope-sdk-java/tree/main/examples/legacy_2x). \ No newline at end of file diff --git a/docs/en/quickstart.md b/docs/en/quickstart.md new file mode 100644 index 00000000..eea5ef24 --- /dev/null +++ b/docs/en/quickstart.md @@ -0,0 +1,182 @@ +# Quickstart + +Get from zero to a streaming chat response in a few minutes. + +## 1. Requirements + +- JDK 8 or later (`java -version`). +- Maven 3.6+ or Gradle 6+. +- A Model Studio API key — create one in the + [Model Studio console](https://www.alibabacloud.com/help/en/model-studio/get-api-key). + +## 2. Install + +=== "Maven" + + ```xml + + com.alibaba + dashscope-sdk-java + {{ sdk_version }} + + ``` + +=== "Gradle (Groovy)" + + ```groovy + implementation 'com.alibaba:dashscope-sdk-java:{{ sdk_version }}' + ``` + +=== "Gradle (Kotlin)" + + ```kotlin + implementation("com.alibaba:dashscope-sdk-java:{{ sdk_version }}") + ``` + +## 3. Configure the API key + +The client resolves credentials from a config chain: system property +`-Ddashscope.api.key=sk-...`, environment variable `DASHSCOPE_API_KEY`, then the SDK config file. +The simplest setup: + +```bash +export DASHSCOPE_API_KEY="sk-..." +``` + +You can also pass the key explicitly: `DashScopeClient.builder().apiKey("sk-...").build()`. +See the Configuration guide for the full chain (base URL, region, workspace, timeouts, proxies). + +## 4. First call (sync) + +```java +import com.alibaba.dashscope.DashScopeClient; +import com.alibaba.dashscope.types.completions.ChatCompletion; +import com.alibaba.dashscope.types.completions.ChatCompletionCreateParams; +import com.alibaba.dashscope.types.messages.Message; +import java.util.Arrays; +import java.util.List; + +public class QuickStart { + public static void main(String[] args) { + List messages = Arrays.asList( + Message.system("You are a helpful assistant."), + Message.user("请用一句话介绍杭州")); + + try (DashScopeClient client = DashScopeClient.builder().build()) { + ChatCompletion resp = client.chat().completions().create( + ChatCompletionCreateParams.builder() + .model("qwen-plus") + .messages(messages) + .build()); + System.out.println(resp.outputText()); + System.out.println("usage: " + resp.getUsage().getTotalTokens() + + " tokens, request_id: " + resp.getRequestId()); + } + } +} +``` + +The client is `AutoCloseable`: try-with-resources releases the shared connection pool. Create one +client and reuse it — every capability hangs off it as a typed resource. + +## 5. Streaming + +`createStreaming` returns a `ResponseStream` — iterable and `AutoCloseable`. +The SDK asks the server for incremental frames by default, so each chunk's delta is a content +increment. Save this complete example as `QuickStartStreaming.java`: + +```java +import com.alibaba.dashscope.DashScopeClient; +import com.alibaba.dashscope.types.common.ResponseStream; +import com.alibaba.dashscope.types.completions.ChatCompletionChunk; +import com.alibaba.dashscope.types.completions.ChatCompletionCreateParams; +import com.alibaba.dashscope.types.completions.Delta; +import com.alibaba.dashscope.types.messages.Message; +import java.util.Collections; + +public class QuickStartStreaming { + public static void main(String[] args) { + ChatCompletionCreateParams params = ChatCompletionCreateParams.builder() + .model("qwen-plus") + .messages(Collections.singletonList(Message.user("Describe Hangzhou in one sentence"))) + .build(); + + try (DashScopeClient client = DashScopeClient.builder().build(); + ResponseStream stream = + client.chat().completions().createStreaming(params)) { + for (ChatCompletionChunk chunk : stream) { + Delta delta = chunk.delta(); + if (delta != null && delta.getContent() != null) { + System.out.print(delta.getContent()); + System.out.flush(); + } + } + System.out.println(); + } + } +} +``` + +## 6. Async + +`DashScopeAsyncClient` uses `CompletableFuture` for supported unary calls and RxJava `Flowable` for +streaming. See the [async guide](guides/async.md) for coverage, including audio limits. Save this complete example as `QuickStartAsync.java`: + +```java +import com.alibaba.dashscope.DashScopeAsyncClient; +import com.alibaba.dashscope.types.completions.ChatCompletion; +import com.alibaba.dashscope.types.completions.ChatCompletionChunk; +import com.alibaba.dashscope.types.completions.ChatCompletionCreateParams; +import com.alibaba.dashscope.types.completions.Delta; +import com.alibaba.dashscope.types.messages.Message; +import io.reactivex.Flowable; +import java.util.Collections; +import java.util.concurrent.CompletableFuture; + +public class QuickStartAsync { + public static void main(String[] args) { + ChatCompletionCreateParams params = ChatCompletionCreateParams.builder() + .model("qwen-plus") + .messages(Collections.singletonList(Message.user("Describe Hangzhou in one sentence"))) + .build(); + + try (DashScopeAsyncClient client = DashScopeAsyncClient.builder().build()) { + CompletableFuture future = client.chat().completions().create(params); + future.thenAccept(resp -> System.out.println(resp.outputText())).join(); + + Flowable stream = client.chat().completions().createStreaming(params); + stream.blockingForEach(chunk -> { + Delta delta = chunk.delta(); + if (delta != null && delta.getContent() != null) { + System.out.print(delta.getContent()); + } + }); + System.out.println(); + } + } +} +``` + +??? example "Full runnable example: ChatCompletionsCreate.java (auto-synced)" + ```java + --8<-- "examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/chat/ChatCompletionsCreate.java" + ``` + +??? example "Full runnable example: ChatCompletionsCreateAsync.java (auto-synced)" + ```java + --8<-- "examples/01_atomic_capabilities/com/alibaba/dashscope/examples/atomic/chat/ChatCompletionsCreateAsync.java" + ``` + +## Error handling + +Failed requests raise typed `DashScopeException` subclasses by default. For async unary calls, unwrap `CompletionException` to inspect its cause. Capture the request ID and error code for diagnosis; see [errors and diagnosis](guides/errors.md) before adding retries. + +## Next steps + +- [Features](features.md) — the full capability map. +- [Capability recipes](guides/recipes.md) — short calls and runnable classes by task. +- The Guides section — chat & tool calls, multimodal, embeddings, audio, images/video, + files & fine-tuning, AgentStudio, tokenization, configuration, errors, local mock debugging. +- [API overview](reference.md) — browse generated Javadoc by capability. +- [Migration](migrating.md) — move 2.x code to 3.0. +- [Examples](examples.md) — pick a capability, run a mock or a cloud example, and explore complete applications. diff --git a/docs/en/reference.md b/docs/en/reference.md new file mode 100644 index 00000000..00361a6b --- /dev/null +++ b/docs/en/reference.md @@ -0,0 +1,44 @@ +# API overview + +The API reference is **generated automatically from source Javadoc** on every docs build +(`maven-javadoc-plugin` + Lombok delombok, so builder and getter members are included). It covers +every public package shipped in the jar — the 3.0 resources, types, transport, errors, config, +tokenization, AgentStudio, and the frozen `legacy_2x` facades. + +{{ javadoc("Open the full Javadoc") }} + +!!! note "Local preview" + Run `bash docs/serve.sh` to generate the Javadoc bundle and serve the site locally; the + reference is then available at `/api/` on the preview server too. + +## API by capability + +The links below group Java's generated Javadoc by the same tasks as the learning guides. For runnable code, start in the [examples hub](examples.md). + +| Category | Start here | +| --- | --- | +| [Client & configuration](reference/client.md) | Client entry points, options and configuration | +| [Chat](reference/chat.md) | Completions and streaming | +| [Audio](reference/audio.md) | Speech services and session APIs | +| [Protocols and transport](reference/protocols.md) | Native chat, HTTP/SSE, and WebSocket | +| [Client resources](reference/resources.md) | Retrieval, generation, files and other services | +| [AgentStudio](reference/agentstudio.md) | Hosted agents, workflows and events | +| [Types](reference/types.md) | Messages, results and shared types | +| [Errors](reference/errors.md) and [devkit](reference/devkit.md) | Typed errors, mock debugging and engineering utilities | +| [Legacy API](legacy.md) | Frozen 2.x surface and migration paths | + +## Entry points + +Start with {{ javadoc("DashScopeClient", "DashScopeClient.html") }} or {{ javadoc("DashScopeAsyncClient", "DashScopeAsyncClient.html") }}. See [client & configuration](reference/client.md) for options. + +## Requests & responses + +See [types](reference/types.md) for request builders, response models and shared streams. + +## Errors + +See [errors](reference/errors.md) for the unchecked exception hierarchy. + +## Resources & infrastructure + +See [client resources](reference/resources.md) for service entry points. The generated {{ javadoc("transport package", "transport/package-summary.html") }} and {{ javadoc("local tokenizer", "tokenization/package-summary.html") }} cover lower-level APIs. diff --git a/docs/en/reference/agentstudio.md b/docs/en/reference/agentstudio.md new file mode 100644 index 00000000..c14f8816 --- /dev/null +++ b/docs/en/reference/agentstudio.md @@ -0,0 +1,11 @@ +# AgentStudio + +| API | Role | +| --- | --- | +| {{ javadoc("AgentStudioClient", "applications/agentstudio/AgentStudioClient.html") }} | AgentStudio entry point, exposed by `client.agentStudio()`. | +| {{ javadoc("Resources", "applications/agentstudio/resource/package-summary.html") }} | Agents, sessions, events, deployments, workflows and other managed resources. | +| {{ javadoc("Models", "applications/agentstudio/model/package-summary.html") }} | Returned domain objects. | +| {{ javadoc("Parameters", "applications/agentstudio/param/package-summary.html") }} | Typed request builders. | +| {{ javadoc("Pagination", "applications/agentstudio/pagination/package-summary.html") }} | Cursor-based page types. | + +See the [AgentStudio guide](../guides/agentstudio.md) for authentication, sessions and Dynamic Workflow. diff --git a/docs/en/reference/audio.md b/docs/en/reference/audio.md new file mode 100644 index 00000000..e566c8fe --- /dev/null +++ b/docs/en/reference/audio.md @@ -0,0 +1,11 @@ +# Audio + +| API | Role | +| --- | --- | +| {{ javadoc("AudioService", "resources/audio/AudioService.html") }} | Entry point for TTS, ASR, realtime, voices and hotwords. | +| {{ javadoc("AudioAsyncService", "resources/audio/AudioAsyncService.html") }} | Async batch ASR. The duplex sessions stay on the sync client. | +| {{ javadoc("Audio resource classes", "resources/audio/package-summary.html") }} | HTTP and WebSocket service and session types. | +| {{ javadoc("Audio request and result types", "types/audio/package-summary.html") }} | Models for speech and realtime sessions. | +| {{ javadoc("TingWu", "resources/tingwu/package-summary.html") }} | Meeting transcription resources. | + +Choose by transport and input type in the [audio guide](../guides/audio.md). diff --git a/docs/en/reference/chat.md b/docs/en/reference/chat.md new file mode 100644 index 00000000..cb018a63 --- /dev/null +++ b/docs/en/reference/chat.md @@ -0,0 +1,11 @@ +# Chat + +| API | Role | +| --- | --- | +| {{ javadoc("ChatCompletionsService", "resources/chat/ChatCompletionsService.html") }} | Synchronous `create` and `createStreaming`. | +| {{ javadoc("ChatCompletionsAsyncService", "resources/chat/ChatCompletionsAsyncService.html") }} | Async completions and streams. | +| {{ javadoc("Completion models", "types/completions/package-summary.html") }} | Request builders, replies, chunks and deltas. | +| {{ javadoc("Message models", "types/messages/package-summary.html") }} | Roles, content and tool calls. | +| {{ javadoc("ResponseStream", "types/common/ResponseStream.html") }} | Closeable iterable for synchronous stream consumption. | + +See [chat and streaming](../guides/chat.md) for the runnable workflow and tool-call example. diff --git a/docs/en/reference/client.md b/docs/en/reference/client.md new file mode 100644 index 00000000..0d11504b --- /dev/null +++ b/docs/en/reference/client.md @@ -0,0 +1,11 @@ +# Client & configuration + +| API | Role | +| --- | --- | +| {{ javadoc("DashScopeClient", "DashScopeClient.html") }} | Synchronous resource client; reuse and close it when done. | +| {{ javadoc("DashScopeAsyncClient", "DashScopeAsyncClient.html") }} | Async resource client; unary calls use `CompletableFuture` and streaming calls use `Flowable` where supported. | +| {{ javadoc("ClientOptions", "ClientOptions.html") }} | Client-wide credentials, endpoints, timeout, retries, executor and HTTP transport. | +| {{ javadoc("RequestOptions", "RequestOptions.html") }} | Per-request options including headers and encryption. | +| {{ javadoc("ResolvedConfig", "config/ResolvedConfig.html") }} | Resolved client settings. | + +See [configuration](../guides/configuration.md) for precedence and [async client](../guides/async.md) for lifecycle and capabilities. diff --git a/docs/en/reference/devkit.md b/docs/en/reference/devkit.md new file mode 100644 index 00000000..9121f725 --- /dev/null +++ b/docs/en/reference/devkit.md @@ -0,0 +1,5 @@ +# Devkit + +Java uses configuration and transport injection rather than a separate `devkit` package. Point the builder at a test endpoint or supply your own OkHttp client via {{ javadoc("ClientOptions", "ClientOptions.html") }}. Set request-level options via {{ javadoc("RequestOptions", "RequestOptions.html") }}. + +See [local mock debugging](../guides/local-mock.md) for a loopback mock and [examples](../examples.md) for the Maven dry-run suite. For typed error fields and logging, see [errors and diagnosis](../guides/errors.md). diff --git a/docs/en/reference/errors.md b/docs/en/reference/errors.md new file mode 100644 index 00000000..f2c4ee93 --- /dev/null +++ b/docs/en/reference/errors.md @@ -0,0 +1,5 @@ +# Errors + +{{ javadoc("DashScopeException", "errors/DashScopeException.html") }} is the unchecked base class for the 3.x client. Use the {{ javadoc("errors package", "errors/package-summary.html") }} to find typed authentication, rate limit, timeout, transport, and SDK exceptions. + +For `CompletableFuture` calls, inspect the cause of `CompletionException`. For recovery and diagnostics, see [errors and diagnosis](../guides/errors.md). diff --git a/docs/en/reference/protocols.md b/docs/en/reference/protocols.md new file mode 100644 index 00000000..62f5ecb8 --- /dev/null +++ b/docs/en/reference/protocols.md @@ -0,0 +1,25 @@ +--- +description: "Native chat, HTTP/SSE, WebSocket, and endpoint configuration for the Java SDK." +--- +# Protocols and transport + +`client.chat().completions()` uses the native Model Studio API. Java does not offer the Python SDK's `protocol=` setting. Pointing `baseUrl(...)` at a compatible-mode endpoint does not switch request formatting or response parsing to OpenAI or Anthropic compatibility. + +| Surface | Transport | Entry point | +| --- | --- | --- | +| Regular chat | Native request and HTTP/JSON response | `chat().completions().create(...)`; see the [chat API](chat.md). | +| Streaming chat | Same native endpoint with an HTTP SSE response | `chat().completions().createStreaming(...)`; consume and close the stream. | +| Duplex speech and realtime voice | WebSocket | Choose the [audio resource](audio.md) for your task; `client.wsConnection()` opens a shared low-level WebSocket. | + +## Endpoints and resource exceptions + +- `baseUrl(...)` sets the HTTP endpoint; `wsBaseUrl(...)` sets the WebSocket endpoint. See [configuration](../guides/configuration.md) for precedence. +- `decision().create(...)` uses the fixed compatible-mode resource path `/compatible-mode/v1/systemone` on the default gateway. This is a {{ javadoc("decision resource", "resources/decision/DecisionService.html") }} route, not a chat protocol switch. + +## Transport API + +| Type | Role | +| --- | --- | +| {{ javadoc("HttpTransport", "transport/HttpTransport.html") }} | Sends HTTP requests and handles shared responses and transport options. | +| {{ javadoc("SseStream", "transport/sse/SseStream.html") }} | Low-level SSE frames; application code generally uses `ResponseStream` or `Flowable`. | +| {{ javadoc("WsConnection", "transport/ws/WsConnection.html") }} | Shared WebSocket connection that can multiplex audio tasks. | diff --git a/docs/en/reference/resources.md b/docs/en/reference/resources.md new file mode 100644 index 00000000..0d251417 --- /dev/null +++ b/docs/en/reference/resources.md @@ -0,0 +1,12 @@ +# Client resources + +| Accessor | Generated API | Guide | +| --- | --- | --- | +| `multimodal()` | {{ javadoc("Multimodal", "resources/multimodal/package-summary.html") }} | [Multimodal](../guides/multimodal.md) | +| `embeddings()`, `rerank()` | {{ javadoc("Embeddings", "resources/embeddings/package-summary.html") }}, {{ javadoc("rerank", "resources/rerank/package-summary.html") }} | [Embeddings and rerank](../guides/embeddings-rerank.md) | +| `images()`, `videos()` | {{ javadoc("Images", "resources/images/package-summary.html") }}, {{ javadoc("videos", "resources/videos/package-summary.html") }}, {{ javadoc("jobs", "resources/jobs/package-summary.html") }} | [Images and videos](../guides/images-videos.md) | +| `files()`, `models()`, `fineTunes()`, `deployments()` | {{ javadoc("Files", "resources/files/package-summary.html") }}, {{ javadoc("models", "resources/models/package-summary.html") }}, {{ javadoc("fine-tuning", "resources/finetunes/package-summary.html") }}, {{ javadoc("deployments", "resources/deployments/package-summary.html") }} | [Files and fine-tuning](../guides/files-finetunes.md) | +| `apps()`, `decision()` | {{ javadoc("Apps", "resources/apps/package-summary.html") }}, {{ javadoc("decision", "resources/decision/package-summary.html") }} | [Examples](../examples.md) | +| `tokenization()` | {{ javadoc("Tokenization", "resources/tokenization/package-summary.html") }} | [Tokenization](../guides/tokenization.md) | + +For chat, audio, and managed agents, see [chat](chat.md), [audio](audio.md), and [AgentStudio](agentstudio.md). diff --git a/docs/en/reference/types.md b/docs/en/reference/types.md new file mode 100644 index 00000000..e6e19061 --- /dev/null +++ b/docs/en/reference/types.md @@ -0,0 +1,10 @@ +# Types + +Start with the package for the capability you are calling. Builder methods and getters are included in the generated Javadoc. + +| Category | Generated API | +| --- | --- | +| Message roles, content and tool calls | {{ javadoc("types.messages", "types/messages/package-summary.html") }} | +| Completions and deltas | {{ javadoc("types.completions", "types/completions/package-summary.html") }} | +| Shared response and stream types | {{ javadoc("types.common", "types/common/package-summary.html") }} | +| Media, retrieval and training types | Open the package summary for a capability in the [client resources](resources.md) and follow the method signature. | diff --git a/docs/en/release-notes.md b/docs/en/release-notes.md new file mode 100644 index 00000000..ab6b6185 --- /dev/null +++ b/docs/en/release-notes.md @@ -0,0 +1,36 @@ +# Release Notes + +The authoritative, per-release changelog is published on +[GitHub Releases](https://github.com/dashscope/dashscope-sdk-java/releases). +Documentation source version: **{{ sdk_version }}**. Published versions are listed below. + +{{ release_notes }} + +## 3.0 highlights + +The first 3.0 release rebuilds the SDK around a typed, resource-style client. Legacy calls remain available through frozen facades moved under `com.alibaba.dashscope.legacy_2x`. AgentStudio and `shared` are outside that frozen layer. + +| Area | What's new | +|---|---| +| Resource-style client | One `DashScopeClient` entry point with 16 typed resources (`chat()`, `embeddings()`, `audio()`, `agentStudio()`, …), Lombok-builder request params and typed responses. See [Features](features.md). | +| Async client | Supported unary calls return `CompletableFuture` and streams use RxJava `Flowable`. The async audio accessor exposes batch ASR, not duplex sessions. See [Async Client](guides/async.md). | +| Text-like streaming | `createStreaming` returns `ResponseStream` (`Iterable` + `AutoCloseable`) with incremental deltas by default. See [Chat and Streaming](guides/chat.md). | +| Typed errors | Unchecked `DashScopeException` family (`AuthenticationException`, `RateLimitException`, `ContentFilterException`, `ApiTimeoutException`, …) carrying `code`, HTTP status and `request_id`. See [Errors and Diagnosis](guides/errors.md). | +| Automatic retries | Non-streaming HTTP retries use the request settings and failure type, not operation idempotency. Supports backoff and `Retry-After` / `Retry-After-ms` / `X-Should-Retry`, with per-request overrides via `RequestOptions`. See [Errors and Diagnosis](guides/errors.md). | +| Config chain | Builder > system property > environment variable > `~/.dashscope/config.toml` > defaults; per-request `RequestOptions`. See [Configuration](guides/configuration.md). | +| Encrypted channel | Opt-in RSA envelope encryption (`RequestOptions.enableEncryption(true)`) with automatic gateway public-key fetch and caching. | +| AgentStudio | Managed-agent resources (agents, sessions, events, memory stores, vaults, …) decoupled from `legacy_2x`, with its own endpoint (`DASHSCOPE_AGENTSTUDIO_URL`) and single-pass SSE streams. See [AgentStudio](guides/agentstudio.md). | +| Local tokenizer | `TokenizerFactory.qwen()` counts offline when the vocabulary is available; it may download the vocabulary if missing. Remote counting is available via `tokenization().count`. See [Tokenization](guides/tokenization.md). | +| Frozen 2.x facade | APIs moved to `legacy_2x` are deprecated for removal in 4.0. AgentStudio and `shared` are not covered by that removal. See [Migrating from 2.x](migrating.md). | +| Engineering | JDK 8+ bytecode, ErrorProne checks, and CI mock dry-runs. Microphone recognition and batch transcription requiring HTTPS result downloads are excluded; archived legacy examples are not built. See [Examples](examples.md). | + +## 2.x line + +The 2.x generation (released through **v2.23.8**, November 2026) was built around +per-capability entry classes — `new Generation()`, `new MultiModalConversation()`, +`new ImageSynthesis()`, … — with checked `ApiException` / `NoApiKeyException` / +`InputRequiredException` and `ResultCallback` / `Flowable` streaming. + +To keep using APIs moved to `com.alibaba.dashscope.legacy_2x` with the 3.x artifact, update imports and recompile. That layer is **frozen** and deprecated for removal in 4.0. See [Legacy 2.x](legacy.md) for the package mapping and [Migrating from 2.x](migrating.md) for the entry-point table. +Per-release 2.x changelogs remain available on +[GitHub Releases](https://github.com/dashscope/dashscope-sdk-java/releases). diff --git a/docs/hooks.py b/docs/hooks.py new file mode 100644 index 00000000..8032ec2e --- /dev/null +++ b/docs/hooks.py @@ -0,0 +1,15 @@ +"""Build hook: inject the SDK version from the root pom.xml into the site.""" +import re +from pathlib import Path + + +def on_config(config, **kwargs): + pom = Path(config.config_file_path).parent / "pom.xml" + text = pom.read_text(encoding="utf-8") + # The right after the project artifactId is the SDK version (parent pom + # coordinates come first, so anchor on the artifactId to skip them). + m = re.search( + r"dashscope-sdk-java\s*([^<]+)", text + ) + config.extra["sdk_version"] = m.group(1) if m else "unknown" + return config \ No newline at end of file diff --git a/docs/javadoc/material-bridge.css b/docs/javadoc/material-bridge.css new file mode 100644 index 00000000..c464e03b --- /dev/null +++ b/docs/javadoc/material-bridge.css @@ -0,0 +1,42 @@ +/* Material-bridge overlay for JDK 17 Javadoc (added via --add-stylesheet). + Keeps the default Javadoc layout; aligns colors and fonts with the + MkDocs Material indigo theme used by the guide pages. */ +:root { + --link-color: #3f51b5; + --link-color-hover: #5c6bc0; +} +body { + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, + "Helvetica Neue", Arial, "Noto Sans", "PingFang SC", "Microsoft YaHei", + sans-serif; +} +a:link, +a:visited { + color: #3f51b5; +} +a:hover, +a:focus { + color: #5c6bc0; +} +.header .title, +h1, +h2, +h3 { + color: #283593; +} +.top-nav { + background-color: #3f51b5; +} +.sub-nav { + background-color: #e8eaf6; +} +.member-name-link, +.element-name-link { + color: #3f51b5; +} +.block { + line-height: 1.6; +} +div.table-tabs > button.active-table-tab { + background: #3f51b5; +} \ No newline at end of file diff --git a/docs/main.py b/docs/main.py new file mode 100644 index 00000000..3f758656 --- /dev/null +++ b/docs/main.py @@ -0,0 +1,104 @@ +"""Macros module: build-time values so docs never drift from their source of truth. + +- ``{{ sdk_version }}`` <- root pom.xml +- ``{{ release_notes }}`` <- published GitHub Releases (latest-release table + linking to each release page), refreshed on every docs build. +""" +import json +import os +import posixpath +import re +import urllib.request +from html import escape +from pathlib import Path + +_RELEASES_URL = ( + "https://api.github.com/repos/dashscope/dashscope-sdk-java/releases?per_page=20" +) +_RELEASES_PAGE = "https://github.com/dashscope/dashscope-sdk-java/releases" +_RELEASES_SHOWN = 5 +# Fetch once per build process; the i18n plugin runs two locale passes. +_RELEASES_CACHE = None + + +def _fetch_releases(): + """Published releases, newest first; None when the API is unreachable. + + Drafts are excluded so an unpublished release skeleton never leaks into + the docs. GITHUB_TOKEN (set in CI) only lifts the anonymous rate limit; + the data is public. Offline builds fall back to a link, never fail. + """ + global _RELEASES_CACHE + if _RELEASES_CACHE is not None: + return _RELEASES_CACHE or None + headers = { + "Accept": "application/vnd.github+json", + "User-Agent": "dashscope-sdk-docs-build", + } + token = os.environ.get("GITHUB_TOKEN") + if token: + headers["Authorization"] = "Bearer " + token + try: + request = urllib.request.Request(_RELEASES_URL, headers=headers) + with urllib.request.urlopen(request, timeout=10) as response: + releases = json.load(response) + releases = [r for r in releases if not r.get("draft")] + releases.sort(key=lambda r: r.get("published_at") or "", reverse=True) + _RELEASES_CACHE = releases + return releases or None + except Exception: + _RELEASES_CACHE = [] + return None + + +def _render_release_notes(lang): + releases = _fetch_releases() + zh = lang == "zh" + if not releases: + return ( + "构建时未能加载 GitHub Releases,完整变更日志请参阅" + f"[GitHub Releases]({_RELEASES_PAGE})。" + if zh + else "Release notes could not be loaded at build time; see " + f"[GitHub Releases]({_RELEASES_PAGE}) for the full changelog." + ) + parts = ["## 近期发布" if zh else "## Recent releases", ""] + parts.append("| Tag | 说明 |" if zh else "| Tag | Notes |") + parts.append("| --- | --- |") + for release in releases[:_RELEASES_SHOWN]: + tag = release.get("tag_name") or "" + if release.get("prerelease"): + tag += "(预发布)" if zh else " (pre-release)" + date = (release.get("published_at") or "")[:10] + label = "发布说明" if zh else "Release notes" + parts.append( + f"| {tag} | {date} · [{label}]({release.get('html_url')}) |", + ) + return "\n".join(parts) + + +def define_env(env): + text = (Path(env.project_dir) / "pom.xml").read_text(encoding="utf-8") + m = re.search( + r"dashscope-sdk-java\s*([^<]+)", text + ) + env.variables["sdk_version"] = m.group(1) if m else "unknown" + + @env.macro + def javadoc(label, path=""): + """Link to generated Javadoc on the same site, including in preview.""" + page_url = env.page.url + page_dir = page_url if page_url.endswith("/") else posixpath.dirname(page_url) + target = f"api/com/alibaba/dashscope/{path}" if path else "api/index.html" + href = posixpath.relpath(target, page_dir or ".") + # HTML avoids Markdown link resolution: CI mounts Javadoc after MkDocs. + return f'{escape(label)}' + + +def on_pre_page_macros(env): + # Only release-notes.md uses {{ release_notes }}; don't hit the network + # for other pages. i18n folder structure prefixes zh pages with "zh/". + src = env.page.file.src_uri + if src.endswith("release-notes.md"): + lang = "zh" if src.startswith("zh/") else "en" + env.variables["release_notes"] = _render_release_notes(lang) diff --git a/docs/overrides/404.html b/docs/overrides/404.html new file mode 100644 index 00000000..9ab9bcca --- /dev/null +++ b/docs/overrides/404.html @@ -0,0 +1,38 @@ +{% extends "base.html" %} + +{#- + Override of the theme's static 404 template. mkdocs renders it once, + without a page context and with absolute URLs, because GitHub Pages + serves it for every missing path. zh readers hop to zh/404/ via the + script below; the bilingual link covers JS-disabled clients. +-#} +{% block htmltitle %} + Page not found - {{ config.site_name }} +{% endblock %} + +{% block content %} +

Page not found

+

+ The page you requested does not exist — it may have moved during the + 3.0 documentation restructure. +

+ +

+ 页面不存在——可能在 3.0 文档重构中被移动。 + 查看中文页面。 +

+ +{% endblock %} \ No newline at end of file diff --git a/docs/overrides/main.html b/docs/overrides/main.html new file mode 100644 index 00000000..d0b42898 --- /dev/null +++ b/docs/overrides/main.html @@ -0,0 +1,64 @@ +{% extends "base.html" %} + +{% block htmltitle %} + {% if page and page.url == "zh/" %} + {# The i18n homepage is not marked as page.is_homepage by Material. #} + {{ config.site_name }} + {% else %} + {{ super() }} + {% endif %} +{% endblock %} + +{% block extrahead %} + {{ super() }} + {% if page and page.url == "zh/404/" %} + {# The localized 404 is a live 200 page; keep it out of search engines. #} + + {% endif %} +{% endblock %} + +{# Elastic-style per-page action block; desktop shows the sidebar copy + from partials/toc.html instead, this one serves viewports <60em. #} +{% block content %} + {{ super() }} + {% set zh = (i18n_page_locale | default("en")) == "zh" %} + +{% endblock %} + +{% block scripts %} + {{ super() }} + {# Below 60em Material renders search as a fullscreen panel that swallows + every click, and the decorative .md-search__overlay circle has + pointer-events: none -- so unlike desktop, clicking outside can never + toggle #__search and the dialog looks stuck. Restore the desktop + "click elsewhere to close" behavior on narrow viewports: a click on + the panel outside the form, suggestions and result links closes it. #} + +{% endblock %} \ No newline at end of file diff --git a/docs/overrides/partials/alternate.html b/docs/overrides/partials/alternate.html new file mode 100644 index 00000000..536f75af --- /dev/null +++ b/docs/overrides/partials/alternate.html @@ -0,0 +1,19 @@ +{#- + Segmented EN | 中 language switch instead of Material's translate-icon + dropdown (the same 文A button fastapi.tiangolo.com uses). Two locales + make a dropdown pointless: show both, highlight the active one, switch + in a single click. Overrides partials/alternate.html. +-#} +{% set current = i18n_page_locale | default("en") %} +
+ +
\ No newline at end of file diff --git a/docs/overrides/partials/header.html b/docs/overrides/partials/header.html new file mode 100644 index 00000000..234b7fd3 --- /dev/null +++ b/docs/overrides/partials/header.html @@ -0,0 +1,92 @@ +{#- + Material header with keyboard-operable mobile drawer and search toggles. + The drawer uses a native button for Enter/Space behavior; the search toggle + must stay a