diff --git a/README.md b/README.md index 33fef68..9f5638e 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,6 @@ # Ark Runtime Java SDK -The Ark Runtime Java SDK provides convenient access to the Volcengine Ark -REST API from Java 8+ applications. It includes typed request/response -models for every API endpoint, synchronous and streaming helpers, and -automatic retry logic. +The official Java library for accessing ModelArk on Volcengine and BytePlus. It provides typed request and response models, synchronous and streaming helpers, authentication, and automatic retries for Java 8+ applications. ## Installation @@ -23,34 +20,45 @@ automatic retry logic. implementation 'com.volcengine:ark-runtime:0.4.0' ``` -## Usage +## Choose Volcengine or BytePlus + +Set `ARK_API_KEY`, then choose the builder for the service you use. The builder configures the correct base URL and region; request construction and all subsequent SDK calls are the same. + +### Volcengine (China) -### Authentication +```java +ArkService service = ArkService.volc() + .apiKey(System.getenv("ARK_API_KEY")) + .build(); +``` -The SDK reads the `ARK_API_KEY` environment variable by default. You can -also pass the key explicitly via the builder: +### BytePlus (BP) ```java -ArkService service = ArkService.builder() +ArkService service = ArkService.byteplus() .apiKey(System.getenv("ARK_API_KEY")) .build(); ``` +Use a model ID available in the corresponding Volcengine or BytePlus account. Model IDs can differ between the two services; the examples use `doubao-seed-2-1-pro-260628` for Volcengine and `seed-2-0-lite-260428` for BytePlus. Override either default with `ARK_MODEL`. + +## Quick start + ### Responses API The Responses API is the primary interface for generating text with Ark models. ```java -import com.volcengine.ark.runtime.ArkService; +import com.volcengine.ark.runtime.service.ArkService; import com.volcengine.ark.runtime.models.responses.*; -ArkService service = ArkService.builder() +ArkService service = ArkService.volc() .apiKey(System.getenv("ARK_API_KEY")) .build(); ResponsesRequest request = ResponsesRequest.builder() - .model("doubao-seed-2-1-pro-260628") + .model(System.getenv("ARK_MODEL")) .input(ResponsesInput.ofString("Explain Java generics in two sentences.")) .build(); @@ -60,13 +68,17 @@ System.out.println(response.getOutput()); service.shutdownExecutor(); ``` +Set `ARK_MODEL` to a model ID from your account before running the example. + +## Usage + ### Chat Completions ```java import com.volcengine.ark.runtime.models.chat.*; ChatCompletionRequest request = ChatCompletionRequest.builder() - .model("doubao-seed-2-1-pro-260628") + .model(System.getenv("ARK_MODEL")) .messages(Arrays.asList( ChatCompletionRequestUserMessage.builder() .role(ChatCompletionRequestMessageType.USER) @@ -104,10 +116,9 @@ method -- you do not need to set it on the request builder. ```java import io.reactivex.Flowable; import com.volcengine.ark.runtime.models.responses.*; -import com.volcengine.ark.runtime.models.responses.events.*; ResponsesRequest request = ResponsesRequest.builder() - .model("doubao-seed-2-1-pro-260628") + .model(System.getenv("ARK_MODEL")) .input(ResponsesInput.ofString("Write a haiku about Java.")) .build(); @@ -142,19 +153,28 @@ Build tools with `FunctionTool.builder()` and pass them in the request: ```java import com.volcengine.ark.runtime.models.responses.*; +import java.util.*; + +Map city = new HashMap<>(); +city.put("type", "string"); +city.put("description", "City name"); + +Map properties = new HashMap<>(); +properties.put("city", city); + +Map parameters = new HashMap<>(); +parameters.put("type", "object"); +parameters.put("properties", properties); +parameters.put("required", Collections.singletonList("city")); FunctionTool weatherTool = FunctionTool.builder() .name("get_weather") .description("Get the current weather for a city") - .parameters(Map.of( - "type", "object", - "properties", Map.of( - "city", Map.of("type", "string", "description", "City name")), - "required", List.of("city"))) + .parameters(parameters) .build(); ResponsesRequest request = ResponsesRequest.builder() - .model("doubao-seed-2-1-pro-260628") + .model(System.getenv("ARK_MODEL")) .input(ResponsesInput.ofString("What is the weather in Beijing?")) .tools(Collections.singletonList(Tool.ofFunction(weatherTool))) .build(); @@ -178,32 +198,19 @@ try { } ``` -## API Reference - -| API | Method | -|------------------------|----------------------------------------------------------------------------| -| Responses | `service.createResponse()` / `service.streamResponse()` | -| Chat Completions | `service.createChatCompletion()` / `service.streamChatCompletion()` | -| Embeddings | `service.createEmbedding()` | -| Multimodal Embeddings | `service.createMultiModalEmbedding()` | -| Content Generation | `service.createContentGenerationTask()` | -| Images | `service.createImageGeneration()` | -| Files | `service.createFile()` / `service.listFiles()` / `service.deleteFile()` | -| Tokenization | `service.createTokenization()` | - ## Examples +For detailed usage guidance and legacy migration, see +[`docs/README.md`](docs/README.md) and +[`docs/migration.md`](docs/migration.md). + Runnable single-file programs are available in the [examples/](./examples) directory: -- **Responses** -- `CreateResponseExample`, `ResponseOperationsExample` -- **Chat Completions** -- `ChatCompletionsExample`, `ChatCompletionsFunctionCallExample`, `ChatCompletionsVisionExample` -- **Embeddings** -- `EmbeddingsExample`, `MultiModalEmbeddingsExample`, `SparseEmbeddingsExample` -- **Content Generation** -- `ContentGenerationTaskExample` -- **Images** -- `ImageGenerationExample` -- **Files** -- `FileUploadExample`, `FileVideoResponsesExample` -- **Tokenization** -- `TokenizationExample` -- **Batch** -- `BatchChatCompletionsExample` +- **[Volcengine China examples](./examples/volc)** -- Chat, Responses, images, video generation, embeddings, files, tokenization, batch APIs, and resource APIs using `ArkService.volc()` +- **[BytePlus examples](./examples/byteplus)** -- supported counterparts using `ArkService.byteplus()` and BytePlus model IDs + +MCP is demonstrated in both clouds with `ark-beta-mcp: true`. Other built-in-tool examples are CN-only and explicitly send their required beta headers. ## Requirements diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000..b704204 --- /dev/null +++ b/docs/README.md @@ -0,0 +1,40 @@ +# Ark Runtime Java SDK documentation + +This directory contains detailed usage and migration guidance for the Ark +Runtime Java SDK. + +## Choose the right document + +- [Usage guide](usage.md): dependency setup, regional + clients, generated request models, streaming, and built-in tools. +- [Migration guide](migration.md): migrate from either legacy Volcengine or + BytePlus Java SDK. +- [`../examples/volc`](../examples/volc): runnable Volcengine examples. +- [`../examples/byteplus`](../examples/byteplus): runnable BytePlus examples. + +## Important usage rules + +1. Use `ArkService.volc()` for CN or `ArkService.byteplus()` for BytePlus. Only + client creation and regional model identifiers differ; request setup stays + the same. +2. Read `ARK_API_KEY` from the environment. Never insert credentials into + source, build files, fixtures, logs, or generated patches. +3. Build requests with classes under `com.volcengine.ark.runtime.models`. + Respect generated union factories such as `ResponsesInput.ofString`. +4. Responses streams contain typed event subclasses. Handle the subclasses the + application needs and tolerate additional event types. +5. MCP is supported in CN and BytePlus. Other hosted built-in tools shown in + this repository are CN-only. Pass the matching `ark-beta-*` header to both + streaming and non-streaming requests. +6. Call `shutdownExecutor()` when an application owns the service lifecycle. + +## Minimal verification + +```bash +mvn test +mvn checkstyle:check +``` + +Also run one streaming and one non-streaming request in the selected cloud. +Smoke-test each built-in tool separately to validate its entitlement and beta +header. diff --git a/docs/migration.md b/docs/migration.md new file mode 100644 index 0000000..584417a --- /dev/null +++ b/docs/migration.md @@ -0,0 +1,150 @@ +# Migrate from the legacy Java SDK + +This guide covers: + +- `com.volcengine:volcengine-java-sdk-ark-runtime` +- `com.byteplus:byteplus-java-sdk-v2-ark-runtime` + +Both migrate to `com.volcengine:ark-runtime`. The new common Java package is +also `com.volcengine.ark.runtime` for BytePlus applications. + +## 1. Migration order + +Migrate one API flow at a time: + +1. Choose the target cloud: Volcengine (CN) or BytePlus. +2. Replace the Ark Runtime dependency and select the regional service builder. +3. Update imports to the new common package and API-specific generated models. +4. Rebuild request unions with the new factories and generated enums. +5. Update response types, Chat deltas, and Responses event subclasses. +6. Add the required beta header to every built-in-tool request and remove any + CN-only tool from a BytePlus target. +7. Compile and smoke-test that flow before migrating the next one. + +Do not bulk-replace the old model package or event class names. The correct new +class depends on the request variant and the events the application consumes. + +## 2. Dependency and client mapping + +```xml + + com.volcengine + ark-runtime + 0.1.0 + +``` + +| Legacy | New | +|---|---| +| `ArkService.builder()` | CN: `ArkService.volc()`; BP: `ArkService.byteplus()` | +| `new ArkService(apiKey)` | use regional builder, `.apiKey(apiKey).build()` | +| `com.byteplus.ark.runtime...` | `com.volcengine.ark.runtime...` | +| old `.model...` packages | new `.models...` API-specific classes | + +Preserve dispatcher, connection pool, timeout, and API key calls after changing +the builder entry point. + +## 3. Request-model mapping + +The generated model layer changed substantially; do not bulk-replace `model` +with `models` and assume the result is correct. + +Chat mappings: + +| Legacy | New | +|---|---| +| `model.completion.chat.ChatMessage` | typed `models.chat.ChatCompletionRequest*Message` subtype | +| `ChatMessageRole.USER` | `ChatCompletionRequestMessageType.USER` | +| string message content | `ChatCompletionMessageContent.ofString(value)` | +| `ChatCompletionRequest` | `models.chat.ChatCompletionRequest` | + +Responses mappings: + +| Legacy | New | +|---|---| +| `CreateResponsesRequest` | `ResponsesRequest` | +| `ResponseObject` | `Response` | +| `ResponsesInput.builder().stringValue(v).build()` | `ResponsesInput.ofString(v)` | +| list input builder | `ResponsesInput.ofList(List)` | +| `ResponsesThinking` | `Thinking` | +| `ResponsesConstants` values | generated enums such as `ThinkingMode` and `MessageRole` | + +For a list input, construct a concrete `InputItem` implementation, place it in +a `List`, then call `ResponsesInput.ofList`. For function results, +use `ItemFunctionToolCallOutput` and keep both the tool call ID and previous +response ID. + +If the old application persists serialized request JSON, add a fixture test +that deserializes or rebuilds it with new models and compares the outgoing JSON +field by field. + +## 4. Streaming mapping + +The RxJava flow remains, but payload access changed. + +Chat: + +| Legacy | New | +|---|---| +| `choice.getChoices().get(0).getMessage().getContent()` | `chunk.getChoices().get(0).getDelta().getContent()` | + +Responses: + +| Legacy | New | +|---|---| +| `model.responses.event.StreamEvent` | `models.responses.ResponseStreamEvent` | +| old event subpackages | generated event classes directly in `models.responses` | +| `OutputTextDeltaEvent` | `ResponseTextDeltaEvent` | +| `ResponseCompletedEvent` | new `ResponseCompletedEvent` class and `Response` payload | + +Use `instanceof` before casting. Capture function/MCP IDs from their typed +output-item event and response IDs from the completed event. Preserve +`doOnError` or an equivalent error path; `blockingForEach` returning normally is +the end of stream, not proof that every expected event was present. + +## 5. Extra headers and regional behavior + +Both ordinary and stream methods have header-map overloads: + +```java +Map headers = Collections.singletonMap("ark-beta-mcp", "true"); +service.createResponse(request, headers); +service.streamResponse(request, headers); +``` + +MCP (`ark-beta-mcp`) is supported in both clouds. Web search +(`ark-beta-web-search`), knowledge search (`ark-beta-knowledge-search`), Doubao +App (`ark-beta-doubao-app`), and image process (`ark-beta-image-process`) are +CN-only. A BytePlus migration must stop for review if it finds one of those +tools. + +## 6. Regional model IDs + +Model names and endpoint IDs are cloud-specific. Prefer application +configuration, and update any legacy hard-coded default when changing clouds: + +| API | Volcengine (CN) example | BytePlus example | +|---|---|---| +| Responses / Chat | `doubao-seed-2-1-pro-260628` | `seed-2-0-lite-260428` | +| Multimodal / sparse embeddings | `doubao-embedding-vision-251215` | `skylark-embedding-vision-251215` | +| Image generation | `doubao-seedream-5-0-pro-260628` | `dola-seedream-5-0-pro-260628` | +| Video generation | `doubao-seedance-2-0-fast-260128` | `dreamina-seedance-2-0-fast-260128` | + +Use a model or endpoint ID provisioned for the target account if it differs +from these example defaults. + +## 7. Validate the migration + +1. Search for the legacy dependency, package names, model imports, and generic + service builder; none should remain in migrated Ark Runtime code. +2. Run `mvn test` and `mvn checkstyle:check`. +3. Verify one non-streaming and one streaming Chat or Responses request. +4. Confirm stream text comes from deltas and typed Responses events. +5. Smoke-test every built-in tool with its required beta header. +6. Test CN and BytePlus independently if both are supported. Never reuse a + regional key, model ID, endpoint ID, or service instance across clouds. +7. Confirm `shutdownExecutor()` runs when the owning application shuts down. + +A migration is not complete merely because the project compiles. The live +stream and tool checks catch missing deltas, incorrect event casts, unsupported +regional tools, and omitted headers. diff --git a/docs/usage.md b/docs/usage.md new file mode 100644 index 0000000..8d6a59b --- /dev/null +++ b/docs/usage.md @@ -0,0 +1,191 @@ +# Usage guide + +Use this guide when creating or changing a Java application with Ark Runtime. +Complete request shapes live in the regional example projects. + +## 1. Add the dependency + +```xml + + com.volcengine + ark-runtime + 0.1.0 + +``` + +Set `ARK_API_KEY` outside source control and let the application accept its +model or endpoint ID through configuration. + +## 2. Select the cloud + +Only the builder entry point changes: + +```java +// Volcengine (CN) +ArkService service = ArkService.volc() + .apiKey(System.getenv("ARK_API_KEY")) + .build(); + +// BytePlus +ArkService service = ArkService.byteplus() + .apiKey(System.getenv("ARK_API_KEY")) + .build(); +``` + +The remainder of connection-pool, dispatcher, timeout, request, and response +setup is identical. + +Use a model available in the selected cloud. Current examples use: + +| API | Volcengine (CN) | BytePlus | +|---|---|---| +| Responses / Chat | `doubao-seed-2-1-pro-260628` | `seed-2-0-lite-260428` | +| Multimodal / sparse embeddings | `doubao-embedding-vision-251215` | `skylark-embedding-vision-251215` | +| Image generation | `doubao-seedream-5-0-pro-260628` | `dola-seedream-5-0-pro-260628` | +| Video generation | `doubao-seedance-2-0-fast-260128` | `dreamina-seedance-2-0-fast-260128` | + +User configuration overrides example defaults. + +BytePlus currently has no model for the text-only `/embeddings` endpoint, so +its examples use `/embeddings/multimodal` instead. + +## 3. Build requests with generated models + +All public model classes are under `com.volcengine.ark.runtime.models`. Use +builders for objects and the generated factory for a union value. + +Simple Responses input: + +```java +ResponsesRequest request = ResponsesRequest.builder() + .model(model) + .input(ResponsesInput.ofString("Explain LLMs in one sentence.")) + .build(); +Response response = service.createResponse(request); +``` + +List-valued Responses input: + +```java +ResponsesInput input = ResponsesInput.ofList( + Collections.singletonList( + ItemEasyMessage.builder() + .role(MessageRole.USER) + .content(MessageContent.ofString("Hello")) + .build())); +``` + +Chat uses explicit message types: + +```java +List messages = new ArrayList<>(); +messages.add(ChatCompletionRequestUserMessage.builder() + .role(ChatCompletionRequestMessageType.USER) + .content(ChatCompletionMessageContent.ofString("Hello")) + .build()); + +ChatCompletionRequest request = ChatCompletionRequest.builder() + .model(model) + .messages(messages) + .build(); +``` + +Do not use maps for typed request fields merely to avoid generated union +classes. Maps are appropriate only where the public model intentionally accepts +arbitrary JSON, such as a function parameter schema. + +## 4. Handle streams + +Chat streaming yields completion chunks. Text is on the delta, not the full +message: + +```java +service.streamChatCompletion(request) + .doOnError(Throwable::printStackTrace) + .blockingForEach(chunk -> { + if (chunk.getChoices() == null || chunk.getChoices().isEmpty()) { + return; + } + String text = chunk.getChoices().get(0).getDelta().getContent(); + if (text != null) { + System.out.print(text); + } + }); +``` + +Responses streaming yields `ResponseStreamEvent` subclasses: + +```java +service.streamResponse(request).blockingForEach(event -> { + if (event instanceof ResponseTextDeltaEvent) { + System.out.print(((ResponseTextDeltaEvent) event).getDelta()); + } else if (event instanceof ResponseCompletedEvent) { + String responseId = ((ResponseCompletedEvent) event).getResponse().getId(); + // Store only if a later turn needs it. + } +}); +``` + +Text delta, reasoning, output-item, function-call, MCP, completed, and error +events have different payloads. Never cast before checking the subtype. Add no +catch-all failure for an unknown subtype; new event types should be safely +ignored unless the application needs them. + +## 5. Built-in tools and headers + +Use the overload that accepts headers: + +```java +Map headers = new HashMap<>(); +headers.put("ark-beta-mcp", "true"); + +Response response = service.createResponse(request, headers); +service.streamResponse(request, headers).blockingForEach(/* handler */); +``` + +| Tool | Cloud | Required header | +|---|---|---| +| MCP | CN and BytePlus | `ark-beta-mcp: true` | +| Web search | CN only | `ark-beta-web-search: true` | +| Knowledge search | CN only | `ark-beta-knowledge-search: true` | +| Doubao App | CN only | `ark-beta-doubao-app: true` | +| Image process | CN only | `ark-beta-image-process: true` | + +Do not move a CN-only built-in tool into BytePlus code. Application-defined +function calling is separate from hosted built-in tools. + +## 6. Navigate the examples + +Start in [`examples/volc`](../examples/volc) or +[`examples/byteplus`](../examples/byteplus). Both regional projects include +Chat and Responses streaming and non-streaming flows, plus the APIs available +in that cloud. The CN tree additionally contains CN-only built-in-tool examples. + +Choose the class by intent: + +| Intent | Example class | +|---|---| +| Chat stream/non-stream | `ChatCompletionsExample` | +| Chat reasoning, vision, structured output, function calling | matching `ChatCompletions*Example` | +| Responses and typed stream events | `CreateResponseExample` | +| Response retrieval/input operations | `ResponseOperationsExample` | +| Text embeddings (Volcengine only) | `EmbeddingsExample` | +| Sparse or multimodal embeddings | `SparseEmbeddingsExample`, `MultiModalEmbeddingsExample` | +| Image generation | `ImageGenerationExample` | +| Video generation | `ContentGenerationTaskExample` | +| Files | `FileUploadExample` | +| Agents, sessions, memory stores, environments | matching lifecycle example | +| Token counting | `TokenizationExample` | + +Use built-in-tool examples only in the clouds where they appear. + +## 7. Completion checklist + +- The only Ark Runtime dependency is `com.volcengine:ark-runtime`. +- The service uses one explicit regional builder. +- Imports use `com.volcengine.ark.runtime.models`, including BytePlus code. +- Request union factories and typed messages are preserved. +- Stream handlers check event/chunk types before accessing payloads. +- Built-in tool requests carry the right header and respect cloud support. +- Service shutdown is owned and called once. +- Tests and checkstyle pass. diff --git a/examples/README.md b/examples/README.md index c3683c6..d0e9bc5 100644 --- a/examples/README.md +++ b/examples/README.md @@ -1,47 +1,24 @@ # Examples -Runnable examples for the `ark-runtime-java` SDK. Each class has a `main` that -reads `ARK_API_KEY` from env: +Runnable examples for the `ark-runtime-java` SDK. Set `ARK_API_KEY` and, for most examples, `ARK_MODEL` to a model ID available in your account. ```bash export ARK_API_KEY=... -cd examples +export ARK_MODEL=... mvn -q -DskipTests install -mvn -q exec:java -Dexec.mainClass=com.volcengine.ark.runtime.examples.CreateResponseExample +mvn -q -f examples/volc/pom.xml compile exec:java \ + -Dexec.mainClass=com.volcengine.ark.runtime.examples.volc.CreateResponseExample ``` -First-time setup: `mvn -q -DskipTests install` at the parent repo root so -the examples module can resolve the `ark-runtime` jar from the local Maven -cache. The examples module is **not** wired into the parent aggregator -pom on purpose — install the SDK first, then build the examples separately. - -| Class | What it shows | -|---|---| -| `CreateResponseExample` | Create a response, stream the output | -| `ResponseOperationsExample` | get / delete / list input items | -| `KnowledgeSearchCreateResponsesExample` | Create with knowledge search tool | -| `DoubaoAppCreateResponsesExample` | Create with Doubao app tools | -| `MultiModalEmbeddingsExample` | POST /embeddings/multimodal | -| `ContentGenerationTaskExample` | full lifecycle on POST /contents/generations/tasks (create / poll / list / delete) | -| `ImageGenerationExample` | POST /images/generations — Seedream T2I, Seededit edit-from-image, sequential image generation | -| `AgentsLifecycleExample` | Managed-Agents: Agent lifecycle — Create/Get/List/Update/ListVersions/Delete | -| `EnvironmentsLifecycleExample` | Managed-Agents: Environment lifecycle — Create/Get/List/Update/Delete (cloud + unrestricted networking) | -| `SessionsLoopExample` | Managed-Agents: end-to-end agent loop — Agent + Env + Session, send user.message, stream events until idle | -| `MemoryStoresLifecycleExample` | Managed-Agents: MemoryStore + nested Memory CRUD | -| `SelfHostedWorkerExample` | Managed-Agents: self-hosted worker poll / handle loop | - -`SelfHostedWorkerExample` uses the client's production default `https://ark.cn-beijing.volces.com/api/v3`. - -The Managed-Agents examples additionally accept `ARK_MODEL_ID` for the model id (falls back to a `${YOUR_MODEL_ID}` placeholder that will 400 at runtime). - -Only currently-implemented APIs have runnable examples. See the API Coverage -table in the top-level README for the roadmap. - -## Known limitations - -Responses API requests use a union `ResponsesInput` (string-or-list) and a -union `MessageContent` (string-or-list). The OpenAPI-generated stubs for -these unions are empty placeholders today, so the ported responses examples -construct the request shape without populating the input body. Once codegen -emits real setters for the union variants, the examples should be updated -to pass actual prompts through `ResponsesInput` / `MessageContent`. +Run `mvn -q -DskipTests install` at the repository root first so the example modules can resolve the `ark-runtime` jar from your local Maven cache. Replace `volc` with `byteplus` in the path and main-class package to run the BytePlus version. + +All service-calling examples are grouped by cloud: + +- `com.volcengine.ark.runtime.examples.volc` uses `ArkService.volc()` and Volcengine China model IDs. +- `com.volcengine.ark.runtime.examples.byteplus` uses `ArkService.byteplus()` and BytePlus model IDs. + +`com.volcengine.ark.runtime.examples.volc.SelfHostedWorkerExample` demonstrates the Managed-Agents self-hosted worker poll/handle loop and uses the client's production default `https://ark.cn-beijing.volces.com/api/v3`. + +The paired multimodal and sparse embedding examples default to `doubao-embedding-vision-251215` / `skylark-embedding-vision-251215`. The paired image examples default to `doubao-seedream-5-0-pro-260628` / `dola-seedream-5-0-pro-260628`. The paired video-generation examples default to `doubao-seedance-2-0-fast-260128` / `dreamina-seedance-2-0-fast-260128`. + +MCP is available in both clouds and its calls explicitly send `ark-beta-mcp: true`. Other built-in tools are CN-only: Knowledge Search sends `ark-beta-knowledge-search: true`, and Doubao App sends `ark-beta-doubao-app: true`. diff --git a/examples/byteplus/pom.xml b/examples/byteplus/pom.xml new file mode 100644 index 0000000..b94e421 --- /dev/null +++ b/examples/byteplus/pom.xml @@ -0,0 +1,35 @@ + + + 4.0.0 + + com.volcengine + ark-runtime-byteplus-examples + 0.1.0 + + + 0.4.0 + 8 + 8 + UTF-8 + + + + + com.volcengine + ark-runtime + ${ark-runtime.version} + + + + + + + org.codehaus.mojo + exec-maven-plugin + 3.1.0 + + + + diff --git a/examples/byteplus/src/main/java/com/volcengine/ark/runtime/examples/byteplus/AgentsLifecycleExample.java b/examples/byteplus/src/main/java/com/volcengine/ark/runtime/examples/byteplus/AgentsLifecycleExample.java new file mode 100644 index 0000000..a1d8b61 --- /dev/null +++ b/examples/byteplus/src/main/java/com/volcengine/ark/runtime/examples/byteplus/AgentsLifecycleExample.java @@ -0,0 +1,79 @@ +package com.volcengine.ark.runtime.examples.byteplus; + +import com.volcengine.ark.runtime.models.agent.Agent; +import com.volcengine.ark.runtime.models.agent.CreateAgentRequest; +import com.volcengine.ark.runtime.models.agent.DeleteAgentResponse; +import com.volcengine.ark.runtime.models.agent.ListAgentsResponse; +import com.volcengine.ark.runtime.models.agent.ModelConfig; +import com.volcengine.ark.runtime.models.agent.UpdateAgentRequest; +import com.volcengine.ark.runtime.service.ArkService; + +/** + * Managed Agents — Agent lifecycle example. + * + *

Runs against the outward /api/v3/agents endpoint. Exercises the smallest + * useful CRUD sequence: + * + *

    + *
  • Create → Get → List → Update → ListVersions → Delete
  • + *
+ * + *

Environment: + *

+ *   export ARK_API_KEY=...
+ *   export ARK_MODEL_ID=seed-2-0-lite-260428   # or whatever you have access to
+ * 
+ */ +public class AgentsLifecycleExample { + + public static void main(String[] args) { + String apiKey = System.getenv("ARK_API_KEY"); + if (apiKey == null || apiKey.isEmpty()) { + throw new IllegalStateException("set ARK_API_KEY"); + } + String modelId = System.getenv().getOrDefault("ARK_MODEL_ID", "${YOUR_MODEL_ID}"); + + ArkService service = ArkService.byteplus().apiKey(apiKey).build(); + + // 1. Create + String name = "example-agent-" + System.nanoTime(); + CreateAgentRequest createReq = new CreateAgentRequest(); + createReq.setName(name); + ModelConfig model = new ModelConfig(); + model.setId(modelId); + createReq.setModel(model); + createReq.setDescription("created by ark-runtime-java example"); + Agent created = service.createAgent(createReq); + System.out.printf("created: id=%s version=%d name=%s%n", + created.getId(), created.getVersion(), created.getName()); + + try { + // 2. Get + Agent got = service.getAgent(created.getId()); + System.out.printf("get: id=%s name=%s%n", got.getId(), got.getName()); + + // 3. List — takes limit / page / created_at_gte / created_at_lte. + ListAgentsResponse listed = service.listAgents(5, null, null, null); + System.out.printf("list: %d items, next_page=%s%n", + listed.getData().size(), listed.getNextPage()); + + // 4. Update — bumps version. Requires the previous version for + // optimistic concurrency control. + UpdateAgentRequest updateReq = new UpdateAgentRequest(); + updateReq.setVersion(created.getVersion()); + updateReq.setDescription("updated by ark-runtime-java example"); + Agent updated = service.updateAgent(created.getId(), updateReq); + System.out.printf("updated: id=%s version=%d (was %d)%n", + updated.getId(), updated.getVersion(), created.getVersion()); + + // 5. List versions — should see at least v1 (create) + v2 (update). + ListAgentsResponse versions = service.listAgentVersions(created.getId(), 10, null); + System.out.printf("versions: %d items%n", versions.getData().size()); + } finally { + // 6. Delete + DeleteAgentResponse deleted = service.deleteAgent(created.getId()); + System.out.printf("deleted: id=%s%n", deleted.getId()); + service.shutdownExecutor(); + } + } +} diff --git a/examples/byteplus/src/main/java/com/volcengine/ark/runtime/examples/byteplus/BatchChatCompletionsExample.java b/examples/byteplus/src/main/java/com/volcengine/ark/runtime/examples/byteplus/BatchChatCompletionsExample.java new file mode 100644 index 0000000..fb8d8c9 --- /dev/null +++ b/examples/byteplus/src/main/java/com/volcengine/ark/runtime/examples/byteplus/BatchChatCompletionsExample.java @@ -0,0 +1,81 @@ +package com.volcengine.ark.runtime.examples.byteplus; + +import com.volcengine.ark.runtime.models.chat.ChatCompletionMessageContent; +import com.volcengine.ark.runtime.models.chat.ChatCompletionRequest; +import com.volcengine.ark.runtime.models.chat.ChatCompletionRequestMessage; +import com.volcengine.ark.runtime.models.chat.ChatCompletionRequestMessageType; +import com.volcengine.ark.runtime.models.chat.ChatCompletionRequestSystemMessage; +import com.volcengine.ark.runtime.models.chat.ChatCompletionRequestUserMessage; +import com.volcengine.ark.runtime.models.chat.ChatCompletionResponse; +import com.volcengine.ark.runtime.service.ArkService; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +/** + * Demonstrates the parallel synchronous batch inference endpoint + * (/api/v3/batch/chat/completions). Unlike the standard batch-job flow, each + * call is a regular request; the SDK just gates on the per-model + * {@code Retry-After} response header via {@link + * com.volcengine.ark.runtime.interceptor.BatchInterceptor}. + * + *

Streaming is not supported on the batch endpoint — passing + * {@code stream=true} to {@code createBatchChatCompletion} will throw + * {@link com.volcengine.ark.runtime.exception.ArkException}.

+ */ +public class BatchChatCompletionsExample { + + static String apiKey = System.getenv("ARK_API_KEY"); + static ArkService service = ArkService.byteplus().apiKey(apiKey).build(); + + public static void main(String[] args) throws Exception { + System.out.println("\n----- batch chat completion: parallel fan-out -----"); + + List prompts = Arrays.asList( + "常见的十字花科植物有哪些?", + "推荐几道家常菜", + "用一句话介绍字节跳动", + "春天适合去哪里旅游?" + ); + + ExecutorService pool = Executors.newFixedThreadPool(Math.min(prompts.size(), 8)); + try { + List> futures = new ArrayList<>(); + for (String prompt : prompts) { + futures.add(CompletableFuture.supplyAsync(() -> { + List messages = new ArrayList<>(); + messages.add(ChatCompletionRequestSystemMessage.builder() + .role(ChatCompletionRequestMessageType.SYSTEM) + .content(ChatCompletionMessageContent.ofString( + "你是豆包,是由字节跳动开发的 AI 人工智能助手")) + .build()); + messages.add(ChatCompletionRequestUserMessage.builder() + .role(ChatCompletionRequestMessageType.USER) + .content(ChatCompletionMessageContent.ofString(prompt)) + .build()); + + ChatCompletionRequest req = ChatCompletionRequest.builder() + .model("${YOUR_ENDPOINT_ID}") + .messages(messages) + .build(); + + return service.createBatchChatCompletion(req); + }, pool)); + } + + for (int i = 0; i < futures.size(); i++) { + ChatCompletionResponse result = futures.get(i).get(); + System.out.println("\nprompt[" + i + "]: " + prompts.get(i)); + result.getChoices().forEach(choice -> + System.out.println(" -> " + choice.getMessage().getContent())); + } + } finally { + pool.shutdown(); + service.shutdownExecutor(); + } + } +} diff --git a/examples/byteplus/src/main/java/com/volcengine/ark/runtime/examples/byteplus/ChatCompletionsExample.java b/examples/byteplus/src/main/java/com/volcengine/ark/runtime/examples/byteplus/ChatCompletionsExample.java new file mode 100644 index 0000000..4005443 --- /dev/null +++ b/examples/byteplus/src/main/java/com/volcengine/ark/runtime/examples/byteplus/ChatCompletionsExample.java @@ -0,0 +1,79 @@ +package com.volcengine.ark.runtime.examples.byteplus; + +import com.volcengine.ark.runtime.models.chat.ChatCompletionMessageContent; +import com.volcengine.ark.runtime.models.chat.ChatCompletionRequest; +import com.volcengine.ark.runtime.models.chat.ChatCompletionRequestMessage; +import com.volcengine.ark.runtime.models.chat.ChatCompletionRequestMessageType; +import com.volcengine.ark.runtime.models.chat.ChatCompletionRequestSystemMessage; +import com.volcengine.ark.runtime.models.chat.ChatCompletionRequestUserMessage; +import com.volcengine.ark.runtime.service.ArkService; +import okhttp3.ConnectionPool; +import okhttp3.Dispatcher; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.TimeUnit; + +public class ChatCompletionsExample { + + /** + * Authentication + * 1.If you authorize your endpoint using an API key, you can set your api key to environment variable "ARK_API_KEY" + * String apiKey = System.getenv("ARK_API_KEY"); + * ArkService service = ArkService.byteplus().apiKey(apiKey).build(); + * Note: If you use an API key, this API key will not be refreshed. + * To prevent the API from expiring and failing after some time, choose an API key with no expiration date. + *

+ * 2.If you authorize your endpoint with BytePlus Identity and Access Management (IAM), + * set your access key and secret key in "BYTEPLUS_ACCESSKEY" and "BYTEPLUS_SECRETKEY". + */ + + static String apiKey = System.getenv("ARK_API_KEY"); + static ConnectionPool connectionPool = new ConnectionPool(5, 1, TimeUnit.SECONDS); + static Dispatcher dispatcher = new Dispatcher(); + static ArkService service = ArkService.byteplus().dispatcher(dispatcher).connectionPool(connectionPool).apiKey(apiKey).build(); + + public static void main(String[] args) { + System.out.println("\n----- standard request -----"); + final List messages = new ArrayList<>(); + messages.add(ChatCompletionRequestSystemMessage.builder() + .role(ChatCompletionRequestMessageType.SYSTEM) + .content(ChatCompletionMessageContent.ofString("你是豆包,是由字节跳动开发的 AI 人工智能助手")) + .build()); + messages.add(ChatCompletionRequestUserMessage.builder() + .role(ChatCompletionRequestMessageType.USER) + .content(ChatCompletionMessageContent.ofString("常见的十字花科植物有哪些?")) + .build()); + + ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder() + .model("seed-2-0-lite-260428") + .messages(messages) + .build(); + + service.createChatCompletion(chatCompletionRequest).getChoices().forEach( + choice -> System.out.println(choice.getMessage().getContent())); + + System.out.println("\n----- streaming request -----"); + ChatCompletionRequest streamChatCompletionRequest = ChatCompletionRequest.builder() + .model("seed-2-0-lite-260428") + .messages(messages) + .build(); + + service.streamChatCompletion(streamChatCompletionRequest) + .doOnError(Throwable::printStackTrace) + .blockingForEach( + chunk -> { + if (chunk.getChoices() == null || chunk.getChoices().isEmpty()) { + return; + } + String content = chunk.getChoices().get(0).getDelta().getContent(); + if (content != null) { + System.out.print(content); + } + } + ); + + // shutdown service after all requests is finished + service.shutdownExecutor(); + } +} diff --git a/examples/byteplus/src/main/java/com/volcengine/ark/runtime/examples/byteplus/ChatCompletionsFunctionCallExample.java b/examples/byteplus/src/main/java/com/volcengine/ark/runtime/examples/byteplus/ChatCompletionsFunctionCallExample.java new file mode 100644 index 0000000..c3b774c --- /dev/null +++ b/examples/byteplus/src/main/java/com/volcengine/ark/runtime/examples/byteplus/ChatCompletionsFunctionCallExample.java @@ -0,0 +1,81 @@ +package com.volcengine.ark.runtime.examples.byteplus; + +import com.volcengine.ark.runtime.models.chat.ChatCompletionMessageContent; +import com.volcengine.ark.runtime.models.chat.ChatCompletionRequest; +import com.volcengine.ark.runtime.models.chat.ChatCompletionRequestMessage; +import com.volcengine.ark.runtime.models.chat.ChatCompletionRequestMessageType; +import com.volcengine.ark.runtime.models.chat.ChatCompletionRequestUserMessage; +import com.volcengine.ark.runtime.models.chat.ChatCompletionTool; +import com.volcengine.ark.runtime.models.chat.FunctionObject; +import com.volcengine.ark.runtime.models.chat.ToolType; +import com.volcengine.ark.runtime.service.ArkService; +import okhttp3.ConnectionPool; +import okhttp3.Dispatcher; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +public class ChatCompletionsFunctionCallExample { + + /** + * Authentication + * 1.If you authorize your endpoint using an API key, you can set your api key to environment variable "ARK_API_KEY" + */ + + static String apiKey = System.getenv("ARK_API_KEY"); + static ConnectionPool connectionPool = new ConnectionPool(5, 1, TimeUnit.SECONDS); + static Dispatcher dispatcher = new Dispatcher(); + static ArkService service = ArkService.byteplus().dispatcher(dispatcher).connectionPool(connectionPool).apiKey(apiKey).build(); + + public static void main(String[] args) { + System.out.println("\n----- function call request -----"); + final List messages = new ArrayList<>(); + messages.add(ChatCompletionRequestUserMessage.builder() + .role(ChatCompletionRequestMessageType.USER) + .content(ChatCompletionMessageContent.ofString("What's the weather like in Boston today?")) + .build()); + + Map parameters = new HashMap<>(); + parameters.put("type", "object"); + Map properties = new HashMap<>(); + Map location = new HashMap<>(); + location.put("type", "string"); + location.put("description", "The city and state, e.g. San Francisco, CA"); + properties.put("location", location); + parameters.put("properties", properties); + parameters.put("required", Collections.singletonList("location")); + + FunctionObject weatherFn = FunctionObject.builder() + .name("get_current_weather") + .description("Get the current weather in a given location") + .parameters(parameters) + .build(); + + final List tools = Arrays.asList( + ChatCompletionTool.builder() + .type(ToolType.FUNCTION) + .function(weatherFn) + .build() + ); + + ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder() + .model("seed-2-0-lite-260428") + .messages(messages) + .tools(tools) + .build(); + + service.createChatCompletion(chatCompletionRequest).getChoices().forEach(System.out::println); + + service.streamChatCompletion(chatCompletionRequest) + .doOnError(Throwable::printStackTrace) + .blockingForEach(System.out::println); + + // shutdown service after all requests is finished + service.shutdownExecutor(); + } +} diff --git a/examples/src/main/java/com/volcengine/ark/runtime/examples/ChatCompletionsReasoningExample.java b/examples/byteplus/src/main/java/com/volcengine/ark/runtime/examples/byteplus/ChatCompletionsReasoningExample.java similarity index 93% rename from examples/src/main/java/com/volcengine/ark/runtime/examples/ChatCompletionsReasoningExample.java rename to examples/byteplus/src/main/java/com/volcengine/ark/runtime/examples/byteplus/ChatCompletionsReasoningExample.java index 16e6f20..578592c 100644 --- a/examples/src/main/java/com/volcengine/ark/runtime/examples/ChatCompletionsReasoningExample.java +++ b/examples/byteplus/src/main/java/com/volcengine/ark/runtime/examples/byteplus/ChatCompletionsReasoningExample.java @@ -1,4 +1,4 @@ -package com.volcengine.ark.runtime.examples; +package com.volcengine.ark.runtime.examples.byteplus; import com.volcengine.ark.runtime.models.chat.ChatCompletionMessageContent; import com.volcengine.ark.runtime.models.chat.ChatCompletionRequest; @@ -25,7 +25,7 @@ public class ChatCompletionsReasoningExample { static String apiKey = System.getenv("ARK_API_KEY"); static ConnectionPool connectionPool = new ConnectionPool(5, 1, TimeUnit.SECONDS); static Dispatcher dispatcher = new Dispatcher(); - static ArkService service = ArkService.builder().dispatcher(dispatcher).connectionPool(connectionPool).apiKey(apiKey).build(); + static ArkService service = ArkService.byteplus().dispatcher(dispatcher).connectionPool(connectionPool).apiKey(apiKey).build(); public static void main(String[] args) { System.out.println("\n----- streaming request -----"); @@ -36,7 +36,7 @@ public static void main(String[] args) { .build()); ChatCompletionRequest streamChatCompletionRequest = ChatCompletionRequest.builder() - .model("${YOUR_ENDPOINT_ID}") + .model("seed-2-0-lite-260428") .messages(streamMessages) .thinking(Thinking.builder().type(ThinkingMode.ENABLED).build()) .build(); @@ -66,7 +66,7 @@ public static void main(String[] args) { .build()); ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder() - .model("${YOUR_ENDPOINT_ID}") + .model("seed-2-0-lite-260428") .messages(messages) .thinking(Thinking.builder().type(ThinkingMode.ENABLED).build()) .build(); diff --git a/examples/byteplus/src/main/java/com/volcengine/ark/runtime/examples/byteplus/ChatCompletionsStructuredOutputsExample.java b/examples/byteplus/src/main/java/com/volcengine/ark/runtime/examples/byteplus/ChatCompletionsStructuredOutputsExample.java new file mode 100644 index 0000000..6a5cd84 --- /dev/null +++ b/examples/byteplus/src/main/java/com/volcengine/ark/runtime/examples/byteplus/ChatCompletionsStructuredOutputsExample.java @@ -0,0 +1,80 @@ +package com.volcengine.ark.runtime.examples.byteplus; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.volcengine.ark.runtime.models.chat.ChatCompletionMessageContent; +import com.volcengine.ark.runtime.models.chat.ChatCompletionRequest; +import com.volcengine.ark.runtime.models.chat.ChatCompletionRequestMessage; +import com.volcengine.ark.runtime.models.chat.ChatCompletionRequestMessageType; +import com.volcengine.ark.runtime.models.chat.ChatCompletionRequestUserMessage; +import com.volcengine.ark.runtime.models.chat.ChatCompletionResponseFormat; +import com.volcengine.ark.runtime.models.chat.ChatCompletionResponseFormatJsonSchema; +import com.volcengine.ark.runtime.models.chat.ResponseFormatType; +import com.volcengine.ark.runtime.service.ArkService; +import okhttp3.ConnectionPool; +import okhttp3.Dispatcher; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +public class ChatCompletionsStructuredOutputsExample { + + /** + * Authentication + * 1.If you authorize your endpoint using an API key, you can set your api key to environment variable "ARK_API_KEY" + */ + + static String apiKey = System.getenv("ARK_API_KEY"); + static ConnectionPool connectionPool = new ConnectionPool(5, 1, TimeUnit.SECONDS); + static Dispatcher dispatcher = new Dispatcher(); + static ArkService service = ArkService.byteplus().dispatcher(dispatcher).connectionPool(connectionPool).apiKey(apiKey).build(); + + public static void main(String[] args) throws JsonProcessingException { + System.out.println("\n----- standard request -----"); + final List messages = new ArrayList<>(); + messages.add(ChatCompletionRequestUserMessage.builder() + .role(ChatCompletionRequestMessageType.USER) + .content(ChatCompletionMessageContent.ofString("Describe the ENIAC: who built it and what year.")) + .build()); + + // The schema can be loaded from any source; here we build it inline. + String schemaJson = "{" + + "\"type\":\"object\"," + + "\"properties\":{" + + " \"name\":{\"type\":\"string\"}," + + " \"year_built\":{\"type\":\"integer\"}," + + " \"organization\":{\"type\":\"string\"}" + + "}," + + "\"required\":[\"name\",\"year_built\",\"organization\"]," + + "\"additionalProperties\":false" + + "}"; + ObjectMapper mapper = new ObjectMapper(); + Map schema = mapper.readValue(schemaJson, new TypeReference>() {}); + + final ChatCompletionResponseFormat responseFormat = ChatCompletionResponseFormat.builder() + .type(ResponseFormatType.JSON_SCHEMA) + .jsonSchema(ChatCompletionResponseFormatJsonSchema.builder() + .name("historical_computer") + .description("Notable information about a historical computer") + .schema(schema) + .strict(true) + .build()) + .build(); + + ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder() + .model("seed-2-0-pro-260328") + .messages(messages) + .responseFormat(responseFormat) + .build(); + + service.createChatCompletion(chatCompletionRequest).getChoices().forEach( + choice -> System.out.println(choice.getMessage().getContent()) + ); + + // shutdown service after all requests is finished + service.shutdownExecutor(); + } +} diff --git a/examples/byteplus/src/main/java/com/volcengine/ark/runtime/examples/byteplus/ChatCompletionsVisionExample.java b/examples/byteplus/src/main/java/com/volcengine/ark/runtime/examples/byteplus/ChatCompletionsVisionExample.java new file mode 100644 index 0000000..d03cfaf --- /dev/null +++ b/examples/byteplus/src/main/java/com/volcengine/ark/runtime/examples/byteplus/ChatCompletionsVisionExample.java @@ -0,0 +1,65 @@ +package com.volcengine.ark.runtime.examples.byteplus; + +import com.volcengine.ark.runtime.models.chat.ChatCompletionContentPart; +import com.volcengine.ark.runtime.models.chat.ChatCompletionContentPartImage; +import com.volcengine.ark.runtime.models.chat.ChatCompletionContentPartImageImageUrl; +import com.volcengine.ark.runtime.models.chat.ChatCompletionContentPartText; +import com.volcengine.ark.runtime.models.chat.ChatCompletionContentPartType; +import com.volcengine.ark.runtime.models.chat.ChatCompletionMessageContent; +import com.volcengine.ark.runtime.models.chat.ChatCompletionRequest; +import com.volcengine.ark.runtime.models.chat.ChatCompletionRequestMessage; +import com.volcengine.ark.runtime.models.chat.ChatCompletionRequestMessageType; +import com.volcengine.ark.runtime.models.chat.ChatCompletionRequestUserMessage; +import com.volcengine.ark.runtime.service.ArkService; +import okhttp3.ConnectionPool; +import okhttp3.Dispatcher; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.TimeUnit; + +public class ChatCompletionsVisionExample { + + /** + * Authentication + * 1.If you authorize your endpoint using an API key, you can set your api key to environment variable "ARK_API_KEY" + * String apiKey = System.getenv("ARK_API_KEY"); + * ArkService service = ArkService.byteplus().apiKey(apiKey).build(); + */ + + static String apiKey = System.getenv("ARK_API_KEY"); + static ConnectionPool connectionPool = new ConnectionPool(5, 1, TimeUnit.SECONDS); + static Dispatcher dispatcher = new Dispatcher(); + static ArkService service = ArkService.byteplus().dispatcher(dispatcher).connectionPool(connectionPool).apiKey(apiKey).build(); + + public static void main(String[] args) { + System.out.println("----- image input -----"); + final List messages = new ArrayList<>(); + final List multiParts = new ArrayList<>(); + multiParts.add(ChatCompletionContentPartText.builder() + .type(ChatCompletionContentPartType.TEXT) + .text("这是哪里?") + .build()); + multiParts.add(ChatCompletionContentPartImage.builder() + .type(ChatCompletionContentPartType.IMAGE_URL) + .imageUrl(ChatCompletionContentPartImageImageUrl.builder() + .url("https://ark-project.tos-cn-beijing.volces.com/images/view.jpeg") + .build()) + .build()); + messages.add(ChatCompletionRequestUserMessage.builder() + .role(ChatCompletionRequestMessageType.USER) + .content(ChatCompletionMessageContent.ofList(multiParts)) + .build()); + + ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder() + .model("seed-2-0-lite-260428") + .messages(messages) + .build(); + + service.createChatCompletion(chatCompletionRequest).getChoices().forEach( + choice -> System.out.println(choice.getMessage().getContent())); + + // shutdown service after all requests is finished + service.shutdownExecutor(); + } +} diff --git a/examples/src/main/java/com/volcengine/ark/runtime/examples/ContentGenerationTaskExample.java b/examples/byteplus/src/main/java/com/volcengine/ark/runtime/examples/byteplus/ContentGenerationTaskExample.java similarity index 89% rename from examples/src/main/java/com/volcengine/ark/runtime/examples/ContentGenerationTaskExample.java rename to examples/byteplus/src/main/java/com/volcengine/ark/runtime/examples/byteplus/ContentGenerationTaskExample.java index 6457b7d..097806d 100644 --- a/examples/src/main/java/com/volcengine/ark/runtime/examples/ContentGenerationTaskExample.java +++ b/examples/byteplus/src/main/java/com/volcengine/ark/runtime/examples/byteplus/ContentGenerationTaskExample.java @@ -1,4 +1,4 @@ -package com.volcengine.ark.runtime.examples; +package com.volcengine.ark.runtime.examples.byteplus; import com.volcengine.ark.runtime.models.content_generation.ContentGenerationTask; import com.volcengine.ark.runtime.models.content_generation.ContentItem; @@ -23,16 +23,16 @@ public class ContentGenerationTaskExample { * Authentication * 1. If you authorize your endpoint using an API key, set the API key to environment variable "ARK_API_KEY": * String apiKey = System.getenv("ARK_API_KEY"); - * ArkService service = ArkService.builder().apiKey(apiKey).build(); + * ArkService service = ArkService.byteplus().apiKey(apiKey).build(); * Note: API keys do not refresh — pick one with no expiration. */ static String apiKey = System.getenv("ARK_API_KEY"); static ConnectionPool connectionPool = new ConnectionPool(5, 1, TimeUnit.SECONDS); static Dispatcher dispatcher = new Dispatcher(); - static ArkService service = ArkService.builder().dispatcher(dispatcher).connectionPool(connectionPool).apiKey(apiKey).build(); + static ArkService service = ArkService.byteplus().dispatcher(dispatcher).connectionPool(connectionPool).apiKey(apiKey).build(); public static void main(String[] args) { - String model = "${MODEL EP_ID HERE}"; + String model = System.getenv().getOrDefault("SEEDANCE_MODEL", "dreamina-seedance-2-0-fast-260128"); System.out.println("\n----- CREATE Task Request -----"); List contents = new ArrayList<>(); @@ -51,9 +51,7 @@ public static void main(String[] args) { CreateContentGenerationTaskRequest createRequest = new CreateContentGenerationTaskRequest() .model(model) - .content(contents) - .serviceTier("default") - .executionExpiresAfter(3600L); + .content(contents); // .callbackUrl("YOUR CALLBACK URL"); CreateContentGenerationTaskResponse createResult = service.createContentGenerationTask(createRequest); @@ -70,8 +68,7 @@ public static void main(String[] args) { .pageNum(1) .pageSize(10) .filterStatus(TaskStatus.RUNNING) - .filterModel(model) - .filterServiceTier("default"); + .filterModel(model); // .filterTaskIds(java.util.Arrays.asList(createResult.getId())); ListContentGenerationTasksResponse listResponse = service.listContentGenerationTasks(listRequest); diff --git a/examples/byteplus/src/main/java/com/volcengine/ark/runtime/examples/byteplus/CreateResponseExample.java b/examples/byteplus/src/main/java/com/volcengine/ark/runtime/examples/byteplus/CreateResponseExample.java new file mode 100644 index 0000000..bb19777 --- /dev/null +++ b/examples/byteplus/src/main/java/com/volcengine/ark/runtime/examples/byteplus/CreateResponseExample.java @@ -0,0 +1,377 @@ +package com.volcengine.ark.runtime.examples.byteplus; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.volcengine.ark.runtime.models.responses.CacheMode; +import com.volcengine.ark.runtime.models.responses.FunctionTool; +import com.volcengine.ark.runtime.models.responses.ItemFunctionToolCall; +import com.volcengine.ark.runtime.models.responses.ItemOutputMessage; +import com.volcengine.ark.runtime.models.responses.ItemReasoning; +import com.volcengine.ark.runtime.models.responses.McpApprovalMode; +import com.volcengine.ark.runtime.models.responses.McpRequireApproval; +import com.volcengine.ark.runtime.models.responses.McpTool; +import com.volcengine.ark.runtime.models.responses.OutputContentItem; +import com.volcengine.ark.runtime.models.responses.OutputContentItemText; +import com.volcengine.ark.runtime.models.responses.OutputItem; +import com.volcengine.ark.runtime.models.responses.ReasoningSummaryPart; +import com.volcengine.ark.runtime.models.responses.Response; +import com.volcengine.ark.runtime.models.responses.ResponseCaching; +import com.volcengine.ark.runtime.models.responses.ResponseCompletedEvent; +import com.volcengine.ark.runtime.models.responses.ResponseFunctionCallArgumentsDoneEvent; +import com.volcengine.ark.runtime.models.responses.ResponseOutputItemAddedEvent; +import com.volcengine.ark.runtime.models.responses.ResponseOutputItemDoneEvent; +import com.volcengine.ark.runtime.models.responses.ResponseReasoningSummaryTextDeltaEvent; +import com.volcengine.ark.runtime.models.responses.ResponseStreamEvent; +import com.volcengine.ark.runtime.models.responses.ResponseTextConfig; +import com.volcengine.ark.runtime.models.responses.ResponseTextDeltaEvent; +import com.volcengine.ark.runtime.models.responses.ResponseTextDoneEvent; +import com.volcengine.ark.runtime.models.responses.ResponsesInput; +import com.volcengine.ark.runtime.models.responses.ResponsesRequest; +import com.volcengine.ark.runtime.models.responses.TextFormat; +import com.volcengine.ark.runtime.models.responses.TextFormatType; +import com.volcengine.ark.runtime.models.responses.Thinking; +import com.volcengine.ark.runtime.models.responses.ThinkingMode; +import com.volcengine.ark.runtime.models.responses.Tool; +import com.volcengine.ark.runtime.service.ArkService; +import io.reactivex.Flowable; +import okhttp3.ConnectionPool; +import okhttp3.Dispatcher; + +import java.time.Duration; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; + +public class CreateResponseExample { + + private static final String modelName = "seed-2-0-lite-260428"; + private static final String testSchema = "{\"type\":\"object\",\"properties\":{\"steps\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"properties\":{\"explanation\":{\"type\":\"string\"},\"output\":{\"type\":\"string\"}},\"required\":[\"explanation\",\"output\"],\"additionalProperties\":false}},\"final_answer\":{\"type\":\"string\"}},\"required\":[\"steps\",\"final_answer\"],\"additionalProperties\":false}"; + + public static void main(String[] args) { + String apiKey = System.getenv("ARK_API_KEY"); + if (apiKey == null) { + System.out.println("ARK_API_KEY environment variable not set"); + return; + } + + ConnectionPool connectionPool = new ConnectionPool(5, 1, TimeUnit.SECONDS); + Dispatcher dispatcher = new Dispatcher(); + dispatcher.setMaxRequests(5000); + dispatcher.setMaxRequestsPerHost(5000); + ArkService service = ArkService.byteplus().dispatcher(dispatcher).timeout(Duration.ofHours(1)).connectionPool(connectionPool).apiKey(apiKey).build(); + + + System.out.println("\n----- [Standard Usage] Request 1-----"); + + ResponsesRequest request = ResponsesRequest.builder() + .model(modelName) + + .instructions("请使用中文与我沟通") + .input(ResponsesInput.ofString("你好")) + .thinking(Thinking.builder().type(ThinkingMode.ENABLED).build()) + .build(); + + Response response1; + + try { + response1 = service.createResponse(request); + printResponseObject(response1); + } catch (Exception e) { + System.err.println("Create Response 1 Error " + e.getMessage()); + return; + } + + System.out.println("\n----- [With Previous Response] Request 2-----"); + + // NOTICE: the response store is async, so need a latency here + try { + Thread.sleep(200); + } catch (Throwable e) { + // ignore + } + + ResponsesRequest request2 = ResponsesRequest.builder() + .model(modelName) + + .previousResponseId(response1.getId()) // with previous response id + .instructions("请使用中文与我沟通") + .input(ResponsesInput.ofString("继续")) + .thinking(Thinking.builder().type(ThinkingMode.DISABLED).build()) + .build(); + + Response response2; + + try { + response2 = service.createResponse(request2); + printResponseObject(response2); + } catch (Exception e) { + System.err.println("Create Response 2 Error: " + e.getMessage()); + } + + System.out.println("\n----- [With MultiMedia Input] Request 3-----"); + + // Multi-media input uses the union ResponsesInput list form. We build a + // list of InputItem variants (ItemEasyMessage here with text content). + ResponsesRequest request3 = ResponsesRequest.builder() + .model(modelName) + + .input(ResponsesInput.ofList(Collections.singletonList( + com.volcengine.ark.runtime.models.responses.ItemEasyMessage.builder() + .role(com.volcengine.ark.runtime.models.responses.MessageRole.USER) + .content(com.volcengine.ark.runtime.models.responses.MessageContent.ofString("介绍一下你自己")) + .build()))) + .thinking(Thinking.builder().type(ThinkingMode.ENABLED).build()) + .build(); + + Response response3; + + try { + response3 = service.createResponse(request3); + printResponseObject(response3); + } catch (Exception e) { + System.err.println("Create Response 3 Error: " + e.getMessage()); + } + + + System.out.println("\n----- [Stream Request] Request 4-----"); + + ResponsesRequest request4 = ResponsesRequest.builder() + .model(modelName) + + .instructions("请使用中文与我沟通") + .input(ResponsesInput.ofString("你好")) + .thinking(Thinking.builder().type(ThinkingMode.ENABLED).build()) + .build(); + + try { + service.streamResponse(request4) + .doOnError(Throwable::printStackTrace) + .blockingForEach( + CreateResponseExample::printStreamEvent + ); + } catch (Exception e) { + System.err.println("Create Response 4 Error " + e.getMessage()); + } + + System.out.println("\n----- [Stream FunctionCall Request] Request 5-----"); + + try { + Map weatherParams = new HashMap<>(); + weatherParams.putAll(new ObjectMapper().readValue( + "{\"type\":\"object\",\"properties\":{\"a\":{\"type\":\"integer\",\"description\":\"first number to add\"},\"b\":{\"type\":\"integer\",\"description\":\"second number to add\"}},\"required\":[\"a\",\"b\"]}", + Map.class)); + Tool weatherTool = FunctionTool.builder() + .name("sum") + .description("add two integers and get sum") + .parameters(weatherParams) + .build(); + + // Query is shaped to trigger the `sum` tool: ask the model to add + // two specific integers so it has a clear reason to invoke the + // function rather than answer in plain text. + ResponsesRequest fcRequest = ResponsesRequest.builder() + .model(modelName) + + .input(ResponsesInput.ofString("请用 sum 工具帮我计算 1 + 2 等于多少")) + .thinking(Thinking.builder().type(ThinkingMode.ENABLED).build()) + .tools(Collections.singletonList(weatherTool)) + .build(); + + AtomicReference fcResponseId = new AtomicReference<>(); + AtomicReference fcCallbackId = new AtomicReference<>(); + + Flowable fcResponse = service.streamResponse(fcRequest); + fcResponse.doOnError(Throwable::printStackTrace) + .blockingForEach( + event -> { + printStreamEvent(event); + if (event instanceof ResponseOutputItemDoneEvent) { + if (((ResponseOutputItemDoneEvent) event).getItem() instanceof ItemFunctionToolCall) { + fcCallbackId.set(((ItemFunctionToolCall) ((ResponseOutputItemDoneEvent) event).getItem()).getCallId()); + } + } + if (event instanceof ResponseCompletedEvent) { + fcResponseId.set(((ResponseCompletedEvent) event).getResponse().getId()); + } + } + ); + + // The tool-call output flow uses the union ResponsesInput list form + // to attach the function-call output back into the conversation. + ResponsesRequest fcOutputRequest = ResponsesRequest.builder() + .model(modelName) + + .previousResponseId(fcResponseId.get()) // use the context before + .input(ResponsesInput.ofList(Collections.singletonList( + com.volcengine.ark.runtime.models.responses.ItemFunctionToolCallOutput.builder() + .callId(fcCallbackId.get()) + .output(com.volcengine.ark.runtime.models.responses.MessageContent.ofString("3")) + .build()))) + .thinking(Thinking.builder().type(ThinkingMode.ENABLED).build()) + .tools(Collections.singletonList(weatherTool)) + .build(); + + System.out.println(new ObjectMapper().writeValueAsString(fcOutputRequest)); + + System.out.println("=== fc final response ==="); + + service.streamResponse(fcOutputRequest) + .doOnError(Throwable::printStackTrace) + .blockingForEach( + CreateResponseExample::printStreamEvent + ); + + } catch (Exception e) { + System.err.println("Create Response 4 Error " + e.getMessage()); + } + + System.out.println("\n----- [Stream Request with MCP] Request 5-----"); + + ResponsesRequest request5 = ResponsesRequest.builder() + .model(modelName) + + .tools(Collections.singletonList(McpTool.builder() + .serverLabel("deepwiki-test") + .serverUrl("https://mcp.deepwiki.com/mcp") + .requireApproval(McpRequireApproval.ofMcpApprovalMode(McpApprovalMode.NEVER)) + .build())) + .input(ResponsesInput.ofString("你好")) + .thinking(Thinking.builder().type(ThinkingMode.ENABLED).build()) + .build(); + + try { + Map mcpHeaders = new HashMap<>(); + mcpHeaders.put("ark-beta-mcp", "true"); + service.streamResponse(request5, mcpHeaders) + .doOnError(Throwable::printStackTrace) + .blockingForEach( + CreateResponseExample::printStreamEvent + ); + } catch (Exception e) { + System.err.println("Create Response 5 Error " + e.getMessage()); + } + + System.out.println("\n----- [Request with Caching] Request 7-----"); + StringBuilder longPromptBuilder = new StringBuilder("你是豆包,你必须用4个字回答我的问题"); + for (int i = 0; i < 1000; i++) { + longPromptBuilder.append("你是豆包,你必须用4个字回答我的问题"); + } + String longPrompt = longPromptBuilder.toString(); + ResponsesRequest request7 = ResponsesRequest.builder() + .model(modelName) + + .caching(ResponseCaching.builder().type(CacheMode.ENABLED).prefix(true).build()) + .input(ResponsesInput.ofString(longPrompt)) + .thinking(Thinking.builder().type(ThinkingMode.DISABLED).build()) + .build(); + + String cacheResponseId = null; + + try { + Response cachePrefix = service.createResponse(request7); + System.out.println("=== cache prefix response ==="); + printResponseObject(cachePrefix); + cacheResponseId = cachePrefix.getId(); + } catch (Exception e) { + System.err.println("Create Response 7 Error " + e.getMessage()); + } + + ResponsesRequest cachedRequest = ResponsesRequest.builder() + .model(modelName) + + .previousResponseId(cacheResponseId) + .input(ResponsesInput.ofString("你好")) + .thinking(Thinking.builder().type(ThinkingMode.DISABLED).build()) + .build(); + + try { + Response cacheHitResponse = service.createResponse(cachedRequest); + System.out.println("=== cache hit response ==="); + printResponseObject(cacheHitResponse); + } catch (Exception e) { + System.err.println("Create Cached Response Error " + e.getMessage()); + } + + try { + System.out.println("\n----- [Request with JsonSchema] Request 8-----"); + Map schema = new ObjectMapper().readValue(testSchema, Map.class); + ResponsesRequest request8 = ResponsesRequest.builder() + .input(ResponsesInput.ofString("你好")) + .model(modelName) + + .text(ResponseTextConfig.builder().format(TextFormat.builder() + .type(TextFormatType.fromValue("json_schema")) + .name("math_reasoning") + .schema(schema) + .build()).build()) + .build(); + + Response response8 = service.createResponse(request8); + System.out.println("=== response 8 ==="); + printResponseObject(response8); + } catch (Exception e) { + System.err.println("Create Response 8 Error " + e.getMessage()); + } + + + service.shutdownExecutor(); + } + + private static void printStreamEvent(ResponseStreamEvent event) { + if (event instanceof ResponseReasoningSummaryTextDeltaEvent) { + System.out.print(((ResponseReasoningSummaryTextDeltaEvent) event).getDelta()); + } + if (event instanceof ResponseOutputItemAddedEvent) { + System.out.println("OutputItem " + (((ResponseOutputItemAddedEvent) event).getItem().getType()) + " Start: "); + } + if (event instanceof ResponseTextDeltaEvent) { + System.out.print(((ResponseTextDeltaEvent) event).getDelta()); + } + if (event instanceof ResponseTextDoneEvent) { + System.out.print("\nOutputText End.\n"); + } + if (event instanceof ResponseOutputItemDoneEvent) { + System.out.println("\nOutputItem " + ((ResponseOutputItemDoneEvent) event).getItem().getType() + " End.\n"); + } + if (event instanceof ResponseFunctionCallArgumentsDoneEvent) { + System.out.println("FunctionCall Arguments: " + ((ResponseFunctionCallArgumentsDoneEvent) event).getArguments()); + } + if (event instanceof ResponseCompletedEvent) { + System.out.println("Response Completed. Usage = " + ((ResponseCompletedEvent) event).getResponse().getUsage()); + } + } + + private static void printResponseObject(Response responseObject) { + System.out.println("Response ID: " + responseObject.getId()); + System.out.println("Status: " + responseObject.getStatus()); + if (responseObject.getOutput() != null && !responseObject.getOutput().isEmpty()) { + for (OutputItem outputItem : responseObject.getOutput()) { + if (outputItem instanceof ItemReasoning) { + ItemReasoning itemReasoning = (ItemReasoning) outputItem; + System.out.println("Reasoning Summary:"); + if (itemReasoning.getSummary() != null) { + for (ReasoningSummaryPart summaryPart : itemReasoning.getSummary()) { + System.out.println(summaryPart.getText()); + } + } + } + if (outputItem instanceof ItemOutputMessage) { + ItemOutputMessage itemOutputMessage = (ItemOutputMessage) outputItem; + System.out.println("Output Message:"); + if (itemOutputMessage.getContent() != null) { + for (OutputContentItem item : itemOutputMessage.getContent()) { + if (item instanceof OutputContentItemText) { + OutputContentItemText textItem = (OutputContentItemText) item; + System.out.println(textItem.getText()); + } + } + } + } + } + } + if (responseObject.getUsage() != null) { + System.out.println("Usage: " + responseObject.getUsage()); + } + } +} diff --git a/examples/byteplus/src/main/java/com/volcengine/ark/runtime/examples/byteplus/EnvironmentsLifecycleExample.java b/examples/byteplus/src/main/java/com/volcengine/ark/runtime/examples/byteplus/EnvironmentsLifecycleExample.java new file mode 100644 index 0000000..ce77972 --- /dev/null +++ b/examples/byteplus/src/main/java/com/volcengine/ark/runtime/examples/byteplus/EnvironmentsLifecycleExample.java @@ -0,0 +1,72 @@ +package com.volcengine.ark.runtime.examples.byteplus; + +import com.volcengine.ark.runtime.models.environment.CreateEnvironmentRequest; +import com.volcengine.ark.runtime.models.environment.DeleteEnvironmentResponse; +import com.volcengine.ark.runtime.models.environment.EnvConfig; +import com.volcengine.ark.runtime.models.environment.EnvConfigType; +import com.volcengine.ark.runtime.models.environment.Environment; +import com.volcengine.ark.runtime.models.environment.ListEnvironmentsResponse; +import com.volcengine.ark.runtime.models.environment.NetworkingConfig; +import com.volcengine.ark.runtime.models.environment.NetworkingType; +import com.volcengine.ark.runtime.models.environment.UpdateEnvironmentRequest; +import com.volcengine.ark.runtime.service.ArkService; + +/** + * Managed Agents — Environment lifecycle example. + * + *

An Environment is the sandbox (network + filesystem policy) an Agent runs + * inside during a Session. This example uses the cloud environment with + * unrestricted networking; production usage will typically restrict either. + * + *

Environment: + *

+ *   export ARK_API_KEY=...
+ * 
+ */ +public class EnvironmentsLifecycleExample { + + public static void main(String[] args) { + String apiKey = System.getenv("ARK_API_KEY"); + if (apiKey == null || apiKey.isEmpty()) { + throw new IllegalStateException("set ARK_API_KEY"); + } + + ArkService service = ArkService.byteplus().apiKey(apiKey).build(); + + // 1. Create — cloud + unrestricted network. + CreateEnvironmentRequest createReq = new CreateEnvironmentRequest(); + createReq.setName("example-env-" + System.nanoTime()); + EnvConfig cfg = new EnvConfig(); + cfg.setType(EnvConfigType.CLOUD); + NetworkingConfig net = new NetworkingConfig(); + net.setType(NetworkingType.UNRESTRICTED); + cfg.setNetworking(net); + createReq.setConfig(cfg); + Environment created = service.createEnvironment(createReq); + System.out.printf("created: id=%s name=%s%n", created.getId(), created.getName()); + + try { + // 2. Get + Environment got = service.getEnvironment(created.getId()); + System.out.printf("get: id=%s name=%s type=%s%n", + got.getId(), got.getName(), got.getType()); + + // 3. List + ListEnvironmentsResponse listed = service.listEnvironments(5, null); + System.out.printf("list: %d items, next_page=%s%n", + listed.getData().size(), listed.getNextPage()); + + // 4. Update — attach a description. + UpdateEnvironmentRequest updateReq = new UpdateEnvironmentRequest(); + updateReq.setDescription("updated by ark-runtime-java example"); + Environment updated = service.updateEnvironment(created.getId(), updateReq); + System.out.printf("updated: id=%s description=%s%n", + updated.getId(), updated.getDescription()); + } finally { + // 5. Delete + DeleteEnvironmentResponse deleted = service.deleteEnvironment(created.getId()); + System.out.printf("deleted: id=%s%n", deleted.getId()); + service.shutdownExecutor(); + } + } +} diff --git a/examples/byteplus/src/main/java/com/volcengine/ark/runtime/examples/byteplus/FileUploadExample.java b/examples/byteplus/src/main/java/com/volcengine/ark/runtime/examples/byteplus/FileUploadExample.java new file mode 100644 index 0000000..fc3070c --- /dev/null +++ b/examples/byteplus/src/main/java/com/volcengine/ark/runtime/examples/byteplus/FileUploadExample.java @@ -0,0 +1,61 @@ +package com.volcengine.ark.runtime.examples.byteplus; + +import com.volcengine.ark.runtime.models.file.FileCreateRequest; +import com.volcengine.ark.runtime.models.file.FileDeleted; +import com.volcengine.ark.runtime.models.file.FileListRequest; +import com.volcengine.ark.runtime.models.file.FileListResponse; +import com.volcengine.ark.runtime.models.file.FileObject; +import com.volcengine.ark.runtime.models.file.Purpose; +import com.volcengine.ark.runtime.service.ArkService; + +import java.io.File; + +public class FileUploadExample { + + /** + * Authentication + * 1.If you authorize your endpoint using an API key, you can set your api key to environment variable "ARK_API_KEY" + * String apiKey = System.getenv("ARK_API_KEY"); + * ArkService service = ArkService.byteplus().apiKey(apiKey).build(); + * Note: If you use an API key, this API key will not be refreshed. + * To prevent the API from expiring and failing after some time, choose an API key with no expiration date. + *

+ * 2.If you authorize your endpoint with BytePlus Identity and Access Management (IAM), + * set your access key and secret key in "BYTEPLUS_ACCESSKEY" and "BYTEPLUS_SECRETKEY". + */ + + public static void main(String[] args) { + if (args.length < 1) { + System.err.println("usage: FileUploadExample "); + System.exit(1); + } + String apiKey = System.getenv("ARK_API_KEY"); + if (apiKey == null || apiKey.isEmpty()) { + System.err.println("set ARK_API_KEY"); + System.exit(1); + } + + ArkService service = ArkService.byteplus().apiKey(apiKey).build(); + + // Upload a file + FileCreateRequest request = FileCreateRequest.builder() + .purpose(Purpose.USER_DATA) + .build(); + FileObject uploaded = service.uploadFile(request, new File(args[0])); + System.out.println("uploaded: id=" + uploaded.getId() + " status=" + uploaded.getStatus()); + + // Wait for processing to complete + FileObject ready = service.waitForFileProcessing(uploaded.getId()); + System.out.println("ready: status=" + ready.getStatus()); + + // List files + FileListResponse list = service.listFiles(FileListRequest.builder().limit(5L).build()); + System.out.println("listed " + list.getData().size() + " files; has_more=" + list.getHasMore()); + + // Delete the uploaded file + FileDeleted deleted = service.deleteFile(uploaded.getId()); + System.out.println("deleted: id=" + deleted.getId() + " ok=" + deleted.getDeleted()); + + service.shutdownExecutor(); + } +} diff --git a/examples/byteplus/src/main/java/com/volcengine/ark/runtime/examples/byteplus/FileVideoResponsesExample.java b/examples/byteplus/src/main/java/com/volcengine/ark/runtime/examples/byteplus/FileVideoResponsesExample.java new file mode 100644 index 0000000..5fef33e --- /dev/null +++ b/examples/byteplus/src/main/java/com/volcengine/ark/runtime/examples/byteplus/FileVideoResponsesExample.java @@ -0,0 +1,143 @@ +package com.volcengine.ark.runtime.examples.byteplus; + +import com.volcengine.ark.runtime.models.file.FileCreateRequest; +import com.volcengine.ark.runtime.models.file.FileObject; +import com.volcengine.ark.runtime.models.file.PreprocessConfigs; +import com.volcengine.ark.runtime.models.file.Purpose; +import com.volcengine.ark.runtime.models.file.Status; +import com.volcengine.ark.runtime.models.file.Video; +import com.volcengine.ark.runtime.models.responses.ContentItem; +import com.volcengine.ark.runtime.models.responses.ContentItemText; +import com.volcengine.ark.runtime.models.responses.ContentItemType; +import com.volcengine.ark.runtime.models.responses.ContentItemVideo; +import com.volcengine.ark.runtime.models.responses.InputItem; +import com.volcengine.ark.runtime.models.responses.ItemEasyMessage; +import com.volcengine.ark.runtime.models.responses.MessageContent; +import com.volcengine.ark.runtime.models.responses.MessageRole; +import com.volcengine.ark.runtime.models.responses.ResponseCreatedEvent; +import com.volcengine.ark.runtime.models.responses.ResponseStreamEvent; +import com.volcengine.ark.runtime.models.responses.ResponseTextDeltaEvent; +import com.volcengine.ark.runtime.models.responses.ResponseTextDoneEvent; +import com.volcengine.ark.runtime.models.responses.ResponsesInput; +import com.volcengine.ark.runtime.models.responses.ResponsesRequest; +import com.volcengine.ark.runtime.service.ArkService; + +import java.io.File; +import java.util.Arrays; +import java.util.Collections; +import java.util.concurrent.atomic.AtomicReference; + +/** + * Upload a video, wait for preprocessing, then run a 2-turn Responses session + * referencing the uploaded file_id. + * + * Demonstrates: + * - service.uploadFile(FileCreateRequest, java.io.File) with PreprocessConfigs (video.fps = 0.3) + * - service.waitForFileProcessing(fileId) for the active/failed terminal state + * - ContentItemVideo as input with file_id (no video_url) inside a streaming + * Responses call, plus previousResponseId for multi-turn + */ +public class FileVideoResponsesExample { + + private static final String MODEL = "seed-2-0-lite-260428"; + + public static void main(String[] args) { + if (args.length < 1) { + System.err.println("usage: FileVideoResponsesExample "); + System.exit(1); + } + String apiKey = System.getenv("ARK_API_KEY"); + if (apiKey == null || apiKey.isEmpty()) { + System.err.println("set ARK_API_KEY"); + System.exit(1); + } + + ArkService service = ArkService.byteplus().apiKey(apiKey).build(); + + File video = new File(args[0]); + System.out.println("Uploading " + video.getAbsolutePath()); + FileCreateRequest request = FileCreateRequest.builder() + .purpose(Purpose.USER_DATA) + .preprocessConfigs(PreprocessConfigs.builder() + .video(Video.builder().fps(0.3).build()) + .build()) + .build(); + FileObject uploaded = service.uploadFile(request, video); + System.out.println(" uploaded id=" + uploaded.getId() + " status=" + uploaded.getStatus()); + + FileObject ready = service.waitForFileProcessing(uploaded.getId()); + System.out.println(" processed status=" + ready.getStatus()); + if (!Status.ACTIVE.equals(ready.getStatus())) { + System.err.println("file " + ready.getId() + " did not become active: status=" + ready.getStatus()); + service.shutdownExecutor(); + System.exit(1); + } + + // ----- Turn 1: video + text input, streaming ----- + System.out.println("\nTurn 1: ask the model to analyze the video frame-by-frame"); + + ContentItemVideo videoPart = new ContentItemVideo(); + videoPart.setType(ContentItemType.INPUT_VIDEO); + videoPart.setFileId(ready.getId()); + + ContentItemText textPart = new ContentItemText(); + textPart.setType(ContentItemType.INPUT_TEXT); + textPart.setText("请逐帧分析视频内容"); + + ItemEasyMessage userMessage = new ItemEasyMessage(); + userMessage.setRole(MessageRole.USER); + userMessage.setContent(MessageContent.ofList(Arrays.asList(videoPart, textPart))); + + ResponsesRequest req1 = ResponsesRequest.builder() + .model(MODEL) + .input(ResponsesInput.ofList(Collections.singletonList(userMessage))) + + .store(true) + .build(); + + AtomicReference responseId = new AtomicReference<>(""); + service.streamResponse(req1) + .doOnNext(event -> { + printEvent(event); + if (event instanceof ResponseCreatedEvent) { + responseId.set(((ResponseCreatedEvent) event).getResponse().getId()); + } + }) + .blockingSubscribe(); + + // Response store is async; brief pause before referencing it + try { + Thread.sleep(200); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + + // ----- Turn 2: follow-up via previousResponseId ----- + System.out.println("\nTurn 2: follow-up referencing prior turn's response"); + ResponsesRequest req2 = ResponsesRequest.builder() + .model(MODEL) + .input(ResponsesInput.ofString("上一轮对话里视频里的内容是")) + .previousResponseId(responseId.get()) + + .store(true) + .build(); + + service.streamResponse(req2) + .doOnNext(FileVideoResponsesExample::printEvent) + .blockingSubscribe(); + + service.shutdownExecutor(); + } + + private static void printEvent(ResponseStreamEvent event) { + if (event instanceof ResponseTextDeltaEvent) { + String delta = ((ResponseTextDeltaEvent) event).getDelta(); + if (delta != null) { + System.out.print(delta); + } + } else if (event instanceof ResponseTextDoneEvent) { + String text = ((ResponseTextDoneEvent) event).getText(); + System.out.println("\n[done] " + (text != null ? text : "")); + } + } +} diff --git a/examples/byteplus/src/main/java/com/volcengine/ark/runtime/examples/byteplus/ImageGenerationExample.java b/examples/byteplus/src/main/java/com/volcengine/ark/runtime/examples/byteplus/ImageGenerationExample.java new file mode 100644 index 0000000..2188608 --- /dev/null +++ b/examples/byteplus/src/main/java/com/volcengine/ark/runtime/examples/byteplus/ImageGenerationExample.java @@ -0,0 +1,46 @@ +package com.volcengine.ark.runtime.examples.byteplus; + +import com.volcengine.ark.runtime.models.images.CreateImageGenerationRequest; +import com.volcengine.ark.runtime.models.images.ImageGenerationResponse; +import com.volcengine.ark.runtime.models.images.ResponseFormat; +import com.volcengine.ark.runtime.service.ArkService; +import okhttp3.ConnectionPool; +import okhttp3.Dispatcher; + +import java.util.concurrent.TimeUnit; + +public class ImageGenerationExample { + + /** + * Authentication + * 1. If you authorize your endpoint using an API key, set the API key to environment variable "ARK_API_KEY": + * String apiKey = System.getenv("ARK_API_KEY"); + * ArkService service = ArkService.byteplus().apiKey(apiKey).build(); + * Note: API keys do not refresh — pick one with no expiration. + */ + static String apiKey = System.getenv("ARK_API_KEY"); + static ConnectionPool connectionPool = new ConnectionPool(5, 1, TimeUnit.SECONDS); + static Dispatcher dispatcher = new Dispatcher(); + static ArkService service = ArkService.byteplus().dispatcher(dispatcher).connectionPool(connectionPool).apiKey(apiKey).build(); + + public static void main(String[] args) { + String seedreamModel = System.getenv().getOrDefault("SEEDREAM_MODEL", "dola-seedream-5-0-pro-260628"); + + System.out.println("\n----- [Seedream] Generate Images Request -----"); + CreateImageGenerationRequest request = new CreateImageGenerationRequest() + .model(seedreamModel) + .prompt("龙与地下城女骑士背景是起伏的平原,目光从镜头转向平原") + .responseFormat(ResponseFormat.URL) + .seed(1234567890L) + .watermark(true) + .size("1024x1024"); + + ImageGenerationResponse response = service.generateImages(request); + if (response.getError() != null) { + System.err.println("Error: " + response.getError().getCode() + " — " + response.getError().getMessage()); + } else if (response.getData() != null && !response.getData().isEmpty()) { + System.out.println("Image URL: " + response.getData().get(0).getUrl()); + } + service.shutdownExecutor(); + } +} diff --git a/examples/byteplus/src/main/java/com/volcengine/ark/runtime/examples/byteplus/MemoryStoresLifecycleExample.java b/examples/byteplus/src/main/java/com/volcengine/ark/runtime/examples/byteplus/MemoryStoresLifecycleExample.java new file mode 100644 index 0000000..7fa19ad --- /dev/null +++ b/examples/byteplus/src/main/java/com/volcengine/ark/runtime/examples/byteplus/MemoryStoresLifecycleExample.java @@ -0,0 +1,79 @@ +package com.volcengine.ark.runtime.examples.byteplus; + +import com.volcengine.ark.runtime.models.memory.CreateMemoryRequest; +import com.volcengine.ark.runtime.models.memory.CreateMemoryStoreRequest; +import com.volcengine.ark.runtime.models.memory.ListMemoriesResponse; +import com.volcengine.ark.runtime.models.memory.Memory; +import com.volcengine.ark.runtime.models.memory.MemoryStore; +import com.volcengine.ark.runtime.models.memory.UpdateMemoryRequest; +import com.volcengine.ark.runtime.service.ArkService; + +/** + * Managed Agents — MemoryStore + Memory lifecycle example. + * + *

A MemoryStore is a namespace of Memory documents keyed by path. Covers + * the full CRUD on both levels — creates a store, creates a memory in it, + * gets/lists/updates that memory (SHA256 bumps), and cleans up. + * + *

Environment: + *

+ *   export ARK_API_KEY=...
+ * 
+ */ +public class MemoryStoresLifecycleExample { + + public static void main(String[] args) { + String apiKey = System.getenv("ARK_API_KEY"); + if (apiKey == null || apiKey.isEmpty()) { + throw new IllegalStateException("set ARK_API_KEY"); + } + + ArkService service = ArkService.byteplus().apiKey(apiKey).build(); + + // 1. Create a memory store. + CreateMemoryStoreRequest storeReq = new CreateMemoryStoreRequest(); + storeReq.setName("example-store-" + System.nanoTime()); + MemoryStore store = service.createMemoryStore(storeReq); + System.out.printf("store: id=%s name=%s%n", store.getId(), store.getName()); + + Memory mem = null; + try { + // 2. Create a memory doc inside it. + CreateMemoryRequest memReq = new CreateMemoryRequest(); + memReq.setPath("/example/note-" + System.nanoTime() + ".md"); + memReq.setContent("hello from ark-runtime-java example"); + mem = service.createMemory(store.getId(), memReq); + System.out.printf("memory: id=%s path=%s sha256=%s%n", + mem.getId(), mem.getPath(), mem.getContentSha256()); + + // 3. Get + list. + Memory got = service.getMemory(store.getId(), mem.getId()); + System.out.printf("get: id=%s path=%s%n", got.getId(), got.getPath()); + + ListMemoriesResponse listed = service.listMemories( + store.getId(), null, null, null, 10, null); + System.out.printf("list: %d items in store%n", listed.getData().size()); + + // 4. Update — the SHA256 should change after new content. + UpdateMemoryRequest updReq = new UpdateMemoryRequest(); + updReq.setContent("updated content"); + service.updateMemory(store.getId(), mem.getId(), updReq); + Memory got2 = service.getMemory(store.getId(), mem.getId()); + System.out.printf("updated: id=%s new_sha256=%s (was %s)%n", + got2.getId(), got2.getContentSha256(), mem.getContentSha256()); + + // 5. Delete memory (store cleaned up in `finally`). + service.deleteMemory(store.getId(), mem.getId()); + System.out.printf("memory: deleted id=%s%n", mem.getId()); + mem = null; + } finally { + try { + service.deleteMemoryStore(store.getId()); + System.out.printf("store: deleted id=%s%n", store.getId()); + } catch (Exception e) { + System.err.printf("cleanup deleteMemoryStore(%s): %s%n", store.getId(), e); + } + service.shutdownExecutor(); + } + } +} diff --git a/examples/byteplus/src/main/java/com/volcengine/ark/runtime/examples/byteplus/MultiModalEmbeddingsExample.java b/examples/byteplus/src/main/java/com/volcengine/ark/runtime/examples/byteplus/MultiModalEmbeddingsExample.java new file mode 100644 index 0000000..ffbaa61 --- /dev/null +++ b/examples/byteplus/src/main/java/com/volcengine/ark/runtime/examples/byteplus/MultiModalEmbeddingsExample.java @@ -0,0 +1,61 @@ +package com.volcengine.ark.runtime.examples.byteplus; + +import com.volcengine.ark.runtime.models.multimodal_embedding.EmbeddingInput; +import com.volcengine.ark.runtime.models.multimodal_embedding.EmbeddingInputType; +import com.volcengine.ark.runtime.models.multimodal_embedding.ImageURL; +import com.volcengine.ark.runtime.models.multimodal_embedding.MultiModalEmbeddingRequest; +import com.volcengine.ark.runtime.models.multimodal_embedding.MultiModalEmbeddingResponse; +import com.volcengine.ark.runtime.service.ArkService; +import okhttp3.ConnectionPool; +import okhttp3.Dispatcher; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.TimeUnit; + +public class MultiModalEmbeddingsExample { + + /** + * Authentication + * 1.If you authorize your endpoint using an API key, you can set your api key to environment variable "ARK_API_KEY" + * String apiKey = System.getenv("ARK_API_KEY"); + * ArkService service = ArkService.byteplus().apiKey(apiKey).build(); + * Note: If you use an API key, this API key will not be refreshed. + * To prevent the API from expiring and failing after some time, choose an API key with no expiration date. + *

+ * 2.If you authorize your endpoint with BytePlus Identity and Access Management (IAM), + * set your access key and secret key in "BYTEPLUS_ACCESSKEY" and "BYTEPLUS_SECRETKEY". + */ + + static String apiKey = System.getenv("ARK_API_KEY"); + static ConnectionPool connectionPool = new ConnectionPool(5, 1, TimeUnit.SECONDS); + static Dispatcher dispatcher = new Dispatcher(); + static ArkService service = ArkService.byteplus().dispatcher(dispatcher).connectionPool(connectionPool).apiKey(apiKey).build(); + + public static void main(String[] args) { + System.out.println("\n----- multimodal embeddings request -----"); + + List inputs = new ArrayList<>(); + inputs.add(EmbeddingInput.builder() + .type(EmbeddingInputType.TEXT) + .text("把图中的蓝天换成白云") + .build()); + inputs.add(EmbeddingInput.builder() + .type(EmbeddingInputType.IMAGE_URL) + .imageUrl(ImageURL.builder() + .url("https://ark-project.tos-cn-beijing.volces.com/images/view.jpeg") + .build()) + .build()); + + MultiModalEmbeddingRequest multiModalEmbeddingRequest = MultiModalEmbeddingRequest.builder() + .model("skylark-embedding-vision-251215") + .input(inputs) + .build(); + + MultiModalEmbeddingResponse res = service.createMultiModalEmbeddings(multiModalEmbeddingRequest); + System.out.println(res); + + // shutdown service after all requests is finished + service.shutdownExecutor(); + } +} diff --git a/examples/byteplus/src/main/java/com/volcengine/ark/runtime/examples/byteplus/ResponseOperationsExample.java b/examples/byteplus/src/main/java/com/volcengine/ark/runtime/examples/byteplus/ResponseOperationsExample.java new file mode 100644 index 0000000..bdd4459 --- /dev/null +++ b/examples/byteplus/src/main/java/com/volcengine/ark/runtime/examples/byteplus/ResponseOperationsExample.java @@ -0,0 +1,95 @@ +package com.volcengine.ark.runtime.examples.byteplus; + +import com.volcengine.ark.runtime.models.responses.DeleteResponseResponse; +import com.volcengine.ark.runtime.models.responses.ResponseIncludable; +import com.volcengine.ark.runtime.models.responses.ListInputItemsResponse; +import com.volcengine.ark.runtime.models.responses.Response; +import com.volcengine.ark.runtime.models.responses.ResponsesInput; +import com.volcengine.ark.runtime.models.responses.ResponsesRequest; +import com.volcengine.ark.runtime.models.responses.Thinking; +import com.volcengine.ark.runtime.models.responses.ThinkingMode; +import com.volcengine.ark.runtime.service.ArkService; +import com.volcengine.ark.runtime.models.responses.DeleteResponseRequest; +import com.volcengine.ark.runtime.models.responses.GetResponseRequest; +import com.volcengine.ark.runtime.models.responses.ListInputItemsRequest; +import okhttp3.ConnectionPool; +import okhttp3.Dispatcher; + +import java.time.Duration; +import java.util.Collections; +import java.util.concurrent.TimeUnit; + +public class ResponseOperationsExample { + + private static final String modelName = "seed-2-0-lite-260428"; + + public static void main(String[] args) { + String apiKey = System.getenv("ARK_API_KEY"); + if (apiKey == null) { + System.out.println("ARK_API_KEY environment variable not set"); + return; + } + + ConnectionPool connectionPool = new ConnectionPool(5, 1, TimeUnit.SECONDS); + Dispatcher dispatcher = new Dispatcher(); + dispatcher.setMaxRequests(5000); + dispatcher.setMaxRequestsPerHost(5000); + ArkService service = ArkService.byteplus().dispatcher(dispatcher).timeout(Duration.ofHours(1)).connectionPool(connectionPool).apiKey(apiKey).build(); + + System.out.println("===== CreateResponse Example====="); + + // NOTE: The file-upload API has not been wired in the new SDK yet. The + // request below uses the string variant of ResponsesInput; extend once the + // file APIs land and multi-media input items can be attached. + ResponsesRequest request = ResponsesRequest.builder() + .model(modelName) + + .input(ResponsesInput.ofString("你好")) + .thinking(Thinking.builder().type(ThinkingMode.DISABLED).build()) + .build(); + Response resp = service.createResponse(request); + + try { + Thread.sleep(200); // the response object write is async, so need a latency here + } catch (Throwable e) { + // ignore + } + + System.out.println("===== GetResponse Example====="); + + Response getResult = service.getResponse( + GetResponseRequest.builder().responseId(resp.getId()).build() + ); + System.out.println(getResult); + + // List Input Items + System.out.println("===== List Input Items Example====="); + + ListInputItemsResponse listResult = service.listResponseInputItems( + ListInputItemsRequest.builder().responseId(getResult.getId()) + .include(Collections.singletonList(ResponseIncludable.MESSAGE_INPUT_IMAGE_IMAGE_URL)) + .build() + ); + + System.out.println(listResult); + + System.out.println("===== DeleteResponse Example====="); + + DeleteResponseResponse deleteResult = service.deleteResponse( + DeleteResponseRequest.builder().responseId(getResult.getId()).build() + ); + + System.out.println(deleteResult); + + // when response deleted, get again will throw exception + try { + service.getResponse( + GetResponseRequest.builder().responseId(getResult.getId()).build() + ); + } catch (Exception e) { + System.out.println("GetResponse after delete: " + e.getMessage()); + } + + service.shutdownExecutor(); + } +} diff --git a/examples/byteplus/src/main/java/com/volcengine/ark/runtime/examples/byteplus/SessionsLoopExample.java b/examples/byteplus/src/main/java/com/volcengine/ark/runtime/examples/byteplus/SessionsLoopExample.java new file mode 100644 index 0000000..cc9befc --- /dev/null +++ b/examples/byteplus/src/main/java/com/volcengine/ark/runtime/examples/byteplus/SessionsLoopExample.java @@ -0,0 +1,190 @@ +package com.volcengine.ark.runtime.examples.byteplus; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.volcengine.ark.runtime.models.agent.Agent; +import com.volcengine.ark.runtime.models.agent.CreateAgentRequest; +import com.volcengine.ark.runtime.models.agent.ModelConfig; +import com.volcengine.ark.runtime.models.agent.ToolItem; +import com.volcengine.ark.runtime.models.environment.CreateEnvironmentRequest; +import com.volcengine.ark.runtime.models.environment.EnvConfig; +import com.volcengine.ark.runtime.models.environment.EnvConfigType; +import com.volcengine.ark.runtime.models.environment.Environment; +import com.volcengine.ark.runtime.models.environment.NetworkingConfig; +import com.volcengine.ark.runtime.models.environment.NetworkingType; +import com.volcengine.ark.runtime.models.session.AgentIdentifier; +import com.volcengine.ark.runtime.models.session.ContentBlockType; +import com.volcengine.ark.runtime.models.session.CreateSessionRequest; +import com.volcengine.ark.runtime.models.session.ManagedAgentsEventParams; +import com.volcengine.ark.runtime.models.session.ManagedAgentsEventParamsType; +import com.volcengine.ark.runtime.models.session.ManagedAgentsMessageContentBlock; +import com.volcengine.ark.runtime.models.session.ManagedAgentsTextBlock; +import com.volcengine.ark.runtime.models.session.ManagedAgentsUserMessageEventParams; +import com.volcengine.ark.runtime.models.session.SendSessionEventsRequest; +import com.volcengine.ark.runtime.models.session.Session; +import com.volcengine.ark.runtime.service.ArkService; +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import okhttp3.ResponseBody; +import retrofit2.Call; +import retrofit2.Response; + +/** + * Managed Agents — end-to-end agent-loop example. + * + *

Create Agent + Environment + Session, open the SSE stream, send a text + * prompt, drain events until the loop settles (session.status_idle / + * terminated / error), and print the assistant's response. + * + *

Environment: + *

+ *   export ARK_API_KEY=...
+ *   export ARK_MODEL_ID=seed-2-0-lite-260428
+ * 
+ */ +public class SessionsLoopExample { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final Set STOP_TYPES = new HashSet<>(Arrays.asList( + "session.status_idle", "session.status_terminated", "session.error")); + + public static void main(String[] args) throws Exception { + String apiKey = System.getenv("ARK_API_KEY"); + if (apiKey == null || apiKey.isEmpty()) { + throw new IllegalStateException("set ARK_API_KEY"); + } + String modelId = System.getenv().getOrDefault("ARK_MODEL_ID", "${YOUR_MODEL_ID}"); + + ArkService service = ArkService.byteplus().apiKey(apiKey).build(); + + // 1. Agent + CreateAgentRequest agReq = new CreateAgentRequest(); + agReq.setName("example-loop-agent-" + System.nanoTime()); + ModelConfig model = new ModelConfig(); + model.setId(modelId); + agReq.setModel(model); + agReq.setSystem("You are a helpful assistant. Answer the user's question briefly."); + ToolItem toolset = new ToolItem(); + toolset.setType("agent_toolset_20260401"); + agReq.setTools(Arrays.asList(toolset)); + Agent ag = service.createAgent(agReq); + System.out.printf("agent: id=%s%n", ag.getId()); + + // 2. Environment + CreateEnvironmentRequest envReq = new CreateEnvironmentRequest(); + envReq.setName("example-loop-env-" + System.nanoTime()); + EnvConfig cfg = new EnvConfig(); + cfg.setType(EnvConfigType.CLOUD); + NetworkingConfig net = new NetworkingConfig(); + net.setType(NetworkingType.UNRESTRICTED); + cfg.setNetworking(net); + envReq.setConfig(cfg); + Environment env = service.createEnvironment(envReq); + System.out.printf("env: id=%s%n", env.getId()); + + // 3. Session + CreateSessionRequest sessReq = new CreateSessionRequest(); + sessReq.setAgent(new AgentIdentifier(ag.getId())); + sessReq.setEnvironmentId(env.getId()); + sessReq.setTitle("ark-runtime-java example loop"); + Session sess = service.createSession(sessReq); + System.out.printf("session: id=%s%n%n", sess.getId()); + + StringBuilder assistantOut = new StringBuilder(); + try { + // 4. Open SSE first, then fire the user.message from a background + // thread so we don't race and miss the earliest events. + Thread sender = new Thread(() -> { + try { + Thread.sleep(500); + ManagedAgentsTextBlock textBlock = new ManagedAgentsTextBlock(); + textBlock.setType(ContentBlockType.TEXT); + textBlock.setText("What's the tallest mountain? One sentence."); + ManagedAgentsUserMessageEventParams msg = new ManagedAgentsUserMessageEventParams(); + msg.setType(ManagedAgentsEventParamsType.USER_MESSAGE); + msg.setContent(Arrays.asList(textBlock)); + SendSessionEventsRequest req = new SendSessionEventsRequest(); + req.setEvents(Arrays.asList(msg)); + service.sendSessionEvents(sess.getId(), req); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } catch (Throwable t) { + System.err.println("send user.message: " + t); + } + }, "example-sender"); + sender.setDaemon(true); + sender.start(); + + // 5. Drain the stream. + Call call = service.streamSessionEvents(sess.getId()); + Response resp = call.execute(); + try (ResponseBody body = resp.body()) { + if (!resp.isSuccessful() || body == null) { + throw new RuntimeException("open stream failed: HTTP " + resp.code()); + } + try (BufferedReader br = new BufferedReader( + new InputStreamReader(body.byteStream(), StandardCharsets.UTF_8))) { + String line; + StringBuilder dataBuf = new StringBuilder(); + boolean done = false; + while (!done && (line = br.readLine()) != null) { + if (line.isEmpty()) { + if (dataBuf.length() > 0) { + Map ev = parseFrame(dataBuf.toString()); + dataBuf.setLength(0); + if (ev != null) { + String type = String.valueOf(ev.get("type")); + System.out.printf("[EVT] %s%n", type); + if ("agent.message".equals(type)) { + Object content = ev.get("content"); + if (content instanceof List) { + for (Object block : (List) content) { + if (block instanceof Map) { + Object text = ((Map) block).get("text"); + if (text != null) { + assistantOut.append(text); + } + } + } + } + } + if (STOP_TYPES.contains(type)) { + done = true; + } + } + } + } else if (line.startsWith("data:")) { + dataBuf.append(line.substring(5).trim()); + } + } + } + } + } finally { + try { service.deleteSession(sess.getId()); } catch (Exception ignore) {} + try { service.deleteEnvironment(env.getId()); } catch (Exception ignore) {} + try { service.deleteAgent(ag.getId()); } catch (Exception ignore) {} + service.shutdownExecutor(); + } + + String joined = assistantOut.toString().trim(); + if (!joined.isEmpty()) { + System.out.printf("%nassistant → %s%n", joined); + } else { + System.out.println("\n(no assistant text captured — check the [EVT] trace above)"); + } + } + + private static Map parseFrame(String data) { + try { + return MAPPER.readValue(data, new TypeReference>() {}); + } catch (Exception e) { + return null; + } + } +} diff --git a/examples/byteplus/src/main/java/com/volcengine/ark/runtime/examples/byteplus/SparseEmbeddingsExample.java b/examples/byteplus/src/main/java/com/volcengine/ark/runtime/examples/byteplus/SparseEmbeddingsExample.java new file mode 100644 index 0000000..e3d6354 --- /dev/null +++ b/examples/byteplus/src/main/java/com/volcengine/ark/runtime/examples/byteplus/SparseEmbeddingsExample.java @@ -0,0 +1,59 @@ +package com.volcengine.ark.runtime.examples.byteplus; + +import com.volcengine.ark.runtime.models.multimodal_embedding.EmbeddingInput; +import com.volcengine.ark.runtime.models.multimodal_embedding.EmbeddingInputType; +import com.volcengine.ark.runtime.models.multimodal_embedding.MultiModalEmbeddingRequest; +import com.volcengine.ark.runtime.models.multimodal_embedding.MultiModalEmbeddingResponse; +import com.volcengine.ark.runtime.models.multimodal_embedding.SparseEmbeddingConfig; +import com.volcengine.ark.runtime.models.multimodal_embedding.SparseEmbeddingMode; +import com.volcengine.ark.runtime.service.ArkService; +import okhttp3.ConnectionPool; +import okhttp3.Dispatcher; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.TimeUnit; + +public class SparseEmbeddingsExample { + + /** + * Authentication + * 1.If you authorize your endpoint using an API key, you can set your api key to environment variable "ARK_API_KEY" + * String apiKey = System.getenv("ARK_API_KEY"); + * ArkService service = ArkService.byteplus().apiKey(apiKey).build(); + * Note: If you use an API key, this API key will not be refreshed. + * To prevent the API from expiring and failing after some time, choose an API key with no expiration date. + *

+ * 2.If you authorize your endpoint with BytePlus Identity and Access Management (IAM), + * set your access key and secret key in "BYTEPLUS_ACCESSKEY" and "BYTEPLUS_SECRETKEY". + */ + + static String apiKey = System.getenv("ARK_API_KEY"); + static ConnectionPool connectionPool = new ConnectionPool(5, 1, TimeUnit.SECONDS); + static Dispatcher dispatcher = new Dispatcher(); + static ArkService service = ArkService.byteplus().dispatcher(dispatcher).connectionPool(connectionPool).apiKey(apiKey).build(); + + public static void main(String[] args) { + System.out.println("\n----- sparse embeddings request -----"); + + List inputs = new ArrayList<>(); + inputs.add(EmbeddingInput.builder() + .type(EmbeddingInputType.TEXT) + .text("花椰菜又称菜花、花菜,是一种常见的蔬菜。") + .build()); + + MultiModalEmbeddingRequest request = MultiModalEmbeddingRequest.builder() + .model("skylark-embedding-vision-251215") + .input(inputs) + .sparseEmbedding(SparseEmbeddingConfig.builder() + .type(SparseEmbeddingMode.ENABLED) + .build()) + .build(); + + MultiModalEmbeddingResponse res = service.createMultiModalEmbeddings(request); + System.out.println(res.getData().getSparseEmbedding()); + + // shutdown service after all requests is finished + service.shutdownExecutor(); + } +} diff --git a/examples/byteplus/src/main/java/com/volcengine/ark/runtime/examples/byteplus/TokenizationExample.java b/examples/byteplus/src/main/java/com/volcengine/ark/runtime/examples/byteplus/TokenizationExample.java new file mode 100644 index 0000000..996911f --- /dev/null +++ b/examples/byteplus/src/main/java/com/volcengine/ark/runtime/examples/byteplus/TokenizationExample.java @@ -0,0 +1,48 @@ +package com.volcengine.ark.runtime.examples.byteplus; + +import com.volcengine.ark.runtime.models.tokenization.TokenizationInput; +import com.volcengine.ark.runtime.models.tokenization.TokenizationRequest; +import com.volcengine.ark.runtime.models.tokenization.TokenizationResponse; +import com.volcengine.ark.runtime.service.ArkService; +import okhttp3.ConnectionPool; +import okhttp3.Dispatcher; + +import java.util.Collections; +import java.util.concurrent.TimeUnit; + +public class TokenizationExample { + + /** + * Authentication + * 1.If you authorize your endpoint using an API key, you can set your api key to environment variable "ARK_API_KEY" + * String apiKey = System.getenv("ARK_API_KEY"); + * ArkService service = ArkService.byteplus().apiKey(apiKey).build(); + * Note: If you use an API key, this API key will not be refreshed. + * To prevent the API from expiring and failing after some time, choose an API key with no expiration date. + *

+ * 2.If you authorize your endpoint with BytePlus Identity and Access Management (IAM), + * set your access key and secret key in "BYTEPLUS_ACCESSKEY" and "BYTEPLUS_SECRETKEY". + */ + + static String apiKey = System.getenv("ARK_API_KEY"); + static ConnectionPool connectionPool = new ConnectionPool(5, 1, TimeUnit.SECONDS); + static Dispatcher dispatcher = new Dispatcher(); + static ArkService service = ArkService.byteplus().dispatcher(dispatcher).connectionPool(connectionPool).apiKey(apiKey).build(); + + public static void main(String[] args) { + System.out.println("\n----- tokenization request -----"); + + TokenizationRequest request = TokenizationRequest.builder() + .model("${YOUR_ENDPOINT_ID}") + .text(TokenizationInput.ofList(Collections.singletonList( + "花椰菜又称菜花、花菜,是一种常见的蔬菜。" + ))) + .build(); + + TokenizationResponse res = service.createTokenization(request); + System.out.println(res); + + // shutdown service after all requests is finished + service.shutdownExecutor(); + } +} diff --git a/examples/src/main/java/com/volcengine/ark/runtime/examples/ImageGenerationExample.java b/examples/src/main/java/com/volcengine/ark/runtime/examples/ImageGenerationExample.java deleted file mode 100644 index 886a0d0..0000000 --- a/examples/src/main/java/com/volcengine/ark/runtime/examples/ImageGenerationExample.java +++ /dev/null @@ -1,119 +0,0 @@ -package com.volcengine.ark.runtime.examples; - -import com.volcengine.ark.runtime.models.images.CreateImageGenerationRequest; -import com.volcengine.ark.runtime.models.images.ImageGenerationResponse; -import com.volcengine.ark.runtime.models.images.ImageGenerationStreamEventType; -import com.volcengine.ark.runtime.models.images.ResponseFormat; -import com.volcengine.ark.runtime.models.images.SequentialImageGenerationMode; -import com.volcengine.ark.runtime.models.images.SequentialImageGenerationOptions; -import com.volcengine.ark.runtime.service.ArkService; -import okhttp3.ConnectionPool; -import okhttp3.Dispatcher; - -import java.util.Arrays; -import java.util.concurrent.TimeUnit; - -public class ImageGenerationExample { - - /** - * Authentication - * 1. If you authorize your endpoint using an API key, set the API key to environment variable "ARK_API_KEY": - * String apiKey = System.getenv("ARK_API_KEY"); - * ArkService service = ArkService.builder().apiKey(apiKey).build(); - * Note: API keys do not refresh — pick one with no expiration. - */ - static String apiKey = System.getenv("ARK_API_KEY"); - static ConnectionPool connectionPool = new ConnectionPool(5, 1, TimeUnit.SECONDS); - static Dispatcher dispatcher = new Dispatcher(); - static ArkService service = ArkService.builder().dispatcher(dispatcher).connectionPool(connectionPool).apiKey(apiKey).build(); - - public static void main(String[] args) { - String model = "${YOUR_ENDPOINT_ID}"; - - System.out.println("\n----- [Seedream] Generate Images Request -----"); - CreateImageGenerationRequest request = new CreateImageGenerationRequest() - .model(model) - .prompt("龙与地下城女骑士背景是起伏的平原,目光从镜头转向平原") - .responseFormat(ResponseFormat.URL) - .seed(1234567890L) - .watermark(true) - .size("1024x1024"); - - ImageGenerationResponse response = service.generateImages(request); - if (response.getError() != null) { - System.err.println("Error: " + response.getError().getCode() + " — " + response.getError().getMessage()); - } else if (response.getData() != null && !response.getData().isEmpty()) { - System.out.println("Image URL: " + response.getData().get(0).getUrl()); - } - - System.out.println("\n----- [Seededit] Generate Images Request (with input image) -----"); - request = new CreateImageGenerationRequest() - .model(model) - .prompt("把背景换成黄昏的沙漠") - .image(Arrays.asList("${YOUR_IMAGE_URL_HERE}")) - .responseFormat(ResponseFormat.URL) - .seed(1234567890L) - .watermark(true) - .size("adaptive"); - response = service.generateImages(request); - if (response.getError() != null) { - System.err.println("Error: " + response.getError().getCode() + " — " + response.getError().getMessage()); - } else if (response.getData() != null && !response.getData().isEmpty()) { - System.out.println("Edited Image URL: " + response.getData().get(0).getUrl()); - } - - System.out.println("\n----- [Seedream] Sequential Image Generation -----"); - SequentialImageGenerationOptions seqOpts = new SequentialImageGenerationOptions().maxImages(3); - request = new CreateImageGenerationRequest() - .model(model) - .prompt("星球大战, 场面壮观, 需要描述3个连续场面") - .responseFormat(ResponseFormat.URL) - .seed(1234567890L) - .watermark(true) - .size("1024x1024") - .sequentialImageGeneration(SequentialImageGenerationMode.AUTO) - .sequentialImageGenerationOptions(seqOpts); - response = service.generateImages(request); - if (response.getError() != null) { - System.err.println("Error: " + response.getError().getCode() + " — " + response.getError().getMessage()); - } else if (response.getData() != null) { - for (int i = 0; i < response.getData().size(); i++) { - System.out.printf("[%d] size=%s url=%s%n", i, - response.getData().get(i).getSize(), - response.getData().get(i).getUrl()); - } - } - - System.out.println("\n----- [Seedream] Streaming Sequential Image Generation -----"); - SequentialImageGenerationOptions streamSeqOpts = new SequentialImageGenerationOptions().maxImages(2); - CreateImageGenerationRequest streamRequest = new CreateImageGenerationRequest() - .model(model) - .prompt("星球大战 三个连续场面") - .responseFormat(ResponseFormat.URL) - .seed(1234567890L) - .watermark(false) - .size("1024x1024") - .sequentialImageGeneration(SequentialImageGenerationMode.AUTO) - .sequentialImageGenerationOptions(streamSeqOpts); - service.streamGenerateImages(streamRequest) - .doOnError(Throwable::printStackTrace) - .blockingForEach(event -> { - if (event == null) return; - if (event.getType() == ImageGenerationStreamEventType.IMAGE_GENERATION_PARTIAL_FAILED) { - if (event.getError() != null) { - System.err.println("partial_failed: " + event.getError().getCode() + " — " + event.getError().getMessage()); - } - } else if (event.getType() == ImageGenerationStreamEventType.IMAGE_GENERATION_PARTIAL_SUCCEEDED) { - if (event.getError() == null && event.getUrl() != null) { - System.out.printf("recv.Size=%s recv.Url=%s%n", event.getSize(), event.getUrl()); - } - } else if (event.getType() == ImageGenerationStreamEventType.IMAGE_GENERATION_COMPLETED) { - if (event.getUsage() != null) { - System.out.println("recv.Usage=" + event.getUsage()); - } - } - }); - - service.shutdownExecutor(); - } -} diff --git a/examples/volc/pom.xml b/examples/volc/pom.xml new file mode 100644 index 0000000..f30bd31 --- /dev/null +++ b/examples/volc/pom.xml @@ -0,0 +1,35 @@ + + + 4.0.0 + + com.volcengine + ark-runtime-volc-examples + 0.1.0 + + + 0.4.0 + 8 + 8 + UTF-8 + + + + + com.volcengine + ark-runtime + ${ark-runtime.version} + + + + + + + org.codehaus.mojo + exec-maven-plugin + 3.1.0 + + + + diff --git a/examples/src/main/java/com/volcengine/ark/runtime/examples/AgentsLifecycleExample.java b/examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/AgentsLifecycleExample.java similarity index 96% rename from examples/src/main/java/com/volcengine/ark/runtime/examples/AgentsLifecycleExample.java rename to examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/AgentsLifecycleExample.java index e2be86b..ab97f5b 100644 --- a/examples/src/main/java/com/volcengine/ark/runtime/examples/AgentsLifecycleExample.java +++ b/examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/AgentsLifecycleExample.java @@ -1,4 +1,4 @@ -package com.volcengine.ark.runtime.examples; +package com.volcengine.ark.runtime.examples.volc; import com.volcengine.ark.runtime.models.agent.Agent; import com.volcengine.ark.runtime.models.agent.CreateAgentRequest; @@ -33,7 +33,7 @@ public static void main(String[] args) { } String modelId = System.getenv().getOrDefault("ARK_MODEL_ID", "${YOUR_MODEL_ID}"); - ArkService service = ArkService.builder().apiKey(apiKey).build(); + ArkService service = ArkService.volc().apiKey(apiKey).build(); // 1. Create String name = "example-agent-" + System.nanoTime(); diff --git a/examples/src/main/java/com/volcengine/ark/runtime/examples/BatchChatCompletionsExample.java b/examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/BatchChatCompletionsExample.java similarity index 96% rename from examples/src/main/java/com/volcengine/ark/runtime/examples/BatchChatCompletionsExample.java rename to examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/BatchChatCompletionsExample.java index 76e5869..ab0ba29 100644 --- a/examples/src/main/java/com/volcengine/ark/runtime/examples/BatchChatCompletionsExample.java +++ b/examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/BatchChatCompletionsExample.java @@ -1,4 +1,4 @@ -package com.volcengine.ark.runtime.examples; +package com.volcengine.ark.runtime.examples.volc; import com.volcengine.ark.runtime.models.chat.ChatCompletionMessageContent; import com.volcengine.ark.runtime.models.chat.ChatCompletionRequest; @@ -30,7 +30,7 @@ public class BatchChatCompletionsExample { static String apiKey = System.getenv("ARK_API_KEY"); - static ArkService service = ArkService.builder().apiKey(apiKey).build(); + static ArkService service = ArkService.volc().apiKey(apiKey).build(); public static void main(String[] args) throws Exception { System.out.println("\n----- batch chat completion: parallel fan-out -----"); diff --git a/examples/src/main/java/com/volcengine/ark/runtime/examples/ChatCompletionsExample.java b/examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/ChatCompletionsExample.java similarity index 91% rename from examples/src/main/java/com/volcengine/ark/runtime/examples/ChatCompletionsExample.java rename to examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/ChatCompletionsExample.java index acd5880..7729810 100644 --- a/examples/src/main/java/com/volcengine/ark/runtime/examples/ChatCompletionsExample.java +++ b/examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/ChatCompletionsExample.java @@ -1,4 +1,4 @@ -package com.volcengine.ark.runtime.examples; +package com.volcengine.ark.runtime.examples.volc; import com.volcengine.ark.runtime.models.chat.ChatCompletionMessageContent; import com.volcengine.ark.runtime.models.chat.ChatCompletionRequest; @@ -20,7 +20,7 @@ public class ChatCompletionsExample { * Authentication * 1.If you authorize your endpoint using an API key, you can set your api key to environment variable "ARK_API_KEY" * String apiKey = System.getenv("ARK_API_KEY"); - * ArkService service = ArkService.builder().apiKey(apiKey).build(); + * ArkService service = ArkService.volc().apiKey(apiKey).build(); * Note: If you use an API key, this API key will not be refreshed. * To prevent the API from expiring and failing after some time, choose an API key with no expiration date. *

@@ -32,7 +32,7 @@ public class ChatCompletionsExample { static String apiKey = System.getenv("ARK_API_KEY"); static ConnectionPool connectionPool = new ConnectionPool(5, 1, TimeUnit.SECONDS); static Dispatcher dispatcher = new Dispatcher(); - static ArkService service = ArkService.builder().dispatcher(dispatcher).connectionPool(connectionPool).apiKey(apiKey).build(); + static ArkService service = ArkService.volc().dispatcher(dispatcher).connectionPool(connectionPool).apiKey(apiKey).build(); public static void main(String[] args) { System.out.println("\n----- standard request -----"); @@ -47,7 +47,7 @@ public static void main(String[] args) { .build()); ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder() - .model("${YOUR_ENDPOINT_ID}") + .model("doubao-seed-2-1-pro-260628") .messages(messages) .build(); @@ -56,7 +56,7 @@ public static void main(String[] args) { System.out.println("\n----- streaming request -----"); ChatCompletionRequest streamChatCompletionRequest = ChatCompletionRequest.builder() - .model("${YOUR_ENDPOINT_ID}") + .model("doubao-seed-2-1-pro-260628") .messages(messages) .build(); diff --git a/examples/src/main/java/com/volcengine/ark/runtime/examples/ChatCompletionsFunctionCallExample.java b/examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/ChatCompletionsFunctionCallExample.java similarity index 93% rename from examples/src/main/java/com/volcengine/ark/runtime/examples/ChatCompletionsFunctionCallExample.java rename to examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/ChatCompletionsFunctionCallExample.java index 3061fb6..83a7d4a 100644 --- a/examples/src/main/java/com/volcengine/ark/runtime/examples/ChatCompletionsFunctionCallExample.java +++ b/examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/ChatCompletionsFunctionCallExample.java @@ -1,4 +1,4 @@ -package com.volcengine.ark.runtime.examples; +package com.volcengine.ark.runtime.examples.volc; import com.volcengine.ark.runtime.models.chat.ChatCompletionMessageContent; import com.volcengine.ark.runtime.models.chat.ChatCompletionRequest; @@ -30,7 +30,7 @@ public class ChatCompletionsFunctionCallExample { static String apiKey = System.getenv("ARK_API_KEY"); static ConnectionPool connectionPool = new ConnectionPool(5, 1, TimeUnit.SECONDS); static Dispatcher dispatcher = new Dispatcher(); - static ArkService service = ArkService.builder().dispatcher(dispatcher).connectionPool(connectionPool).apiKey(apiKey).build(); + static ArkService service = ArkService.volc().dispatcher(dispatcher).connectionPool(connectionPool).apiKey(apiKey).build(); public static void main(String[] args) { System.out.println("\n----- function call request -----"); @@ -64,7 +64,7 @@ public static void main(String[] args) { ); ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder() - .model("${YOUR_ENDPOINT_ID}") + .model("doubao-seed-2-1-pro-260628") .messages(messages) .tools(tools) .build(); diff --git a/examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/ChatCompletionsReasoningExample.java b/examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/ChatCompletionsReasoningExample.java new file mode 100644 index 0000000..6b0dc14 --- /dev/null +++ b/examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/ChatCompletionsReasoningExample.java @@ -0,0 +1,84 @@ +package com.volcengine.ark.runtime.examples.volc; + +import com.volcengine.ark.runtime.models.chat.ChatCompletionMessageContent; +import com.volcengine.ark.runtime.models.chat.ChatCompletionRequest; +import com.volcengine.ark.runtime.models.chat.ChatCompletionRequestMessage; +import com.volcengine.ark.runtime.models.chat.ChatCompletionRequestMessageType; +import com.volcengine.ark.runtime.models.chat.ChatCompletionRequestUserMessage; +import com.volcengine.ark.runtime.models.chat.Thinking; +import com.volcengine.ark.runtime.models.chat.ThinkingMode; +import com.volcengine.ark.runtime.service.ArkService; +import okhttp3.ConnectionPool; +import okhttp3.Dispatcher; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.TimeUnit; + +public class ChatCompletionsReasoningExample { + + /** + * Authentication + * 1.If you authorize your endpoint using an API key, you can set your api key to environment variable "ARK_API_KEY" + */ + + static String apiKey = System.getenv("ARK_API_KEY"); + static ConnectionPool connectionPool = new ConnectionPool(5, 1, TimeUnit.SECONDS); + static Dispatcher dispatcher = new Dispatcher(); + static ArkService service = ArkService.volc().dispatcher(dispatcher).connectionPool(connectionPool).apiKey(apiKey).build(); + + public static void main(String[] args) { + System.out.println("\n----- streaming request -----"); + final List streamMessages = new ArrayList<>(); + streamMessages.add(ChatCompletionRequestUserMessage.builder() + .role(ChatCompletionRequestMessageType.USER) + .content(ChatCompletionMessageContent.ofString("How many Rs are there in the word 'strawberry'?")) + .build()); + + ChatCompletionRequest streamChatCompletionRequest = ChatCompletionRequest.builder() + .model("doubao-seed-2-1-pro-260628") + .messages(streamMessages) + .thinking(Thinking.builder().type(ThinkingMode.ENABLED).build()) + .build(); + + service.streamChatCompletion(streamChatCompletionRequest) + .doOnError(Throwable::printStackTrace) + .blockingForEach( + chunk -> { + if (chunk.getChoices() == null || chunk.getChoices().isEmpty()) { + return; + } + String reasoning = chunk.getChoices().get(0).getDelta().getReasoningContent(); + String content = chunk.getChoices().get(0).getDelta().getContent(); + if (reasoning != null && !reasoning.isEmpty()) { + System.out.print(reasoning); + } else if (content != null) { + System.out.print(content); + } + } + ); + + System.out.println("\n----- standard request -----"); + final List messages = new ArrayList<>(); + messages.add(ChatCompletionRequestUserMessage.builder() + .role(ChatCompletionRequestMessageType.USER) + .content(ChatCompletionMessageContent.ofString("How many Rs are there in the word 'strawberry'?")) + .build()); + + ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder() + .model("doubao-seed-2-1-pro-260628") + .messages(messages) + .thinking(Thinking.builder().type(ThinkingMode.ENABLED).build()) + .build(); + + service.createChatCompletion(chatCompletionRequest).getChoices().forEach( + choice -> { + System.out.println(choice.getMessage().getReasoningContent()); + System.out.println(choice.getMessage().getContent()); + } + ); + + // shutdown service after all requests is finished + service.shutdownExecutor(); + } +} diff --git a/examples/src/main/java/com/volcengine/ark/runtime/examples/ChatCompletionsStructuredOutputsExample.java b/examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/ChatCompletionsStructuredOutputsExample.java similarity index 93% rename from examples/src/main/java/com/volcengine/ark/runtime/examples/ChatCompletionsStructuredOutputsExample.java rename to examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/ChatCompletionsStructuredOutputsExample.java index ca45605..ea9c679 100644 --- a/examples/src/main/java/com/volcengine/ark/runtime/examples/ChatCompletionsStructuredOutputsExample.java +++ b/examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/ChatCompletionsStructuredOutputsExample.java @@ -1,4 +1,4 @@ -package com.volcengine.ark.runtime.examples; +package com.volcengine.ark.runtime.examples.volc; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; @@ -30,7 +30,7 @@ public class ChatCompletionsStructuredOutputsExample { static String apiKey = System.getenv("ARK_API_KEY"); static ConnectionPool connectionPool = new ConnectionPool(5, 1, TimeUnit.SECONDS); static Dispatcher dispatcher = new Dispatcher(); - static ArkService service = ArkService.builder().dispatcher(dispatcher).connectionPool(connectionPool).apiKey(apiKey).build(); + static ArkService service = ArkService.volc().dispatcher(dispatcher).connectionPool(connectionPool).apiKey(apiKey).build(); public static void main(String[] args) throws JsonProcessingException { System.out.println("\n----- standard request -----"); @@ -65,7 +65,7 @@ public static void main(String[] args) throws JsonProcessingException { .build(); ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder() - .model("${YOUR_ENDPOINT_ID}") + .model("doubao-seed-2-1-pro-260628") .messages(messages) .responseFormat(responseFormat) .build(); diff --git a/examples/src/main/java/com/volcengine/ark/runtime/examples/ChatCompletionsVisionExample.java b/examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/ChatCompletionsVisionExample.java similarity index 90% rename from examples/src/main/java/com/volcengine/ark/runtime/examples/ChatCompletionsVisionExample.java rename to examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/ChatCompletionsVisionExample.java index 3f4a3bc..1b1bb1b 100644 --- a/examples/src/main/java/com/volcengine/ark/runtime/examples/ChatCompletionsVisionExample.java +++ b/examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/ChatCompletionsVisionExample.java @@ -1,4 +1,4 @@ -package com.volcengine.ark.runtime.examples; +package com.volcengine.ark.runtime.examples.volc; import com.volcengine.ark.runtime.models.chat.ChatCompletionContentPart; import com.volcengine.ark.runtime.models.chat.ChatCompletionContentPartImage; @@ -24,13 +24,13 @@ public class ChatCompletionsVisionExample { * Authentication * 1.If you authorize your endpoint using an API key, you can set your api key to environment variable "ARK_API_KEY" * String apiKey = System.getenv("ARK_API_KEY"); - * ArkService service = ArkService.builder().apiKey(apiKey).build(); + * ArkService service = ArkService.volc().apiKey(apiKey).build(); */ static String apiKey = System.getenv("ARK_API_KEY"); static ConnectionPool connectionPool = new ConnectionPool(5, 1, TimeUnit.SECONDS); static Dispatcher dispatcher = new Dispatcher(); - static ArkService service = ArkService.builder().dispatcher(dispatcher).connectionPool(connectionPool).apiKey(apiKey).build(); + static ArkService service = ArkService.volc().dispatcher(dispatcher).connectionPool(connectionPool).apiKey(apiKey).build(); public static void main(String[] args) { System.out.println("----- image input -----"); @@ -52,7 +52,7 @@ public static void main(String[] args) { .build()); ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder() - .model("${YOUR_ENDPOINT_ID}") + .model("doubao-seed-2-1-pro-260628") .messages(messages) .build(); diff --git a/examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/ContentGenerationTaskExample.java b/examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/ContentGenerationTaskExample.java new file mode 100644 index 0000000..c01d244 --- /dev/null +++ b/examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/ContentGenerationTaskExample.java @@ -0,0 +1,92 @@ +package com.volcengine.ark.runtime.examples.volc; + +import com.volcengine.ark.runtime.models.content_generation.ContentGenerationTask; +import com.volcengine.ark.runtime.models.content_generation.ContentItem; +import com.volcengine.ark.runtime.models.content_generation.ContentType; +import com.volcengine.ark.runtime.models.content_generation.CreateContentGenerationTaskRequest; +import com.volcengine.ark.runtime.models.content_generation.CreateContentGenerationTaskResponse; +import com.volcengine.ark.runtime.models.content_generation.ImageURL; +import com.volcengine.ark.runtime.models.content_generation.ListContentGenerationTasksResponse; +import com.volcengine.ark.runtime.models.content_generation.TaskStatus; +import com.volcengine.ark.runtime.service.ArkService; +import com.volcengine.ark.runtime.models.content_generation.ListContentGenerationTasksRequest; +import okhttp3.ConnectionPool; +import okhttp3.Dispatcher; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.TimeUnit; + +public class ContentGenerationTaskExample { + + /** + * Authentication + * 1. If you authorize your endpoint using an API key, set the API key to environment variable "ARK_API_KEY": + * String apiKey = System.getenv("ARK_API_KEY"); + * ArkService service = ArkService.volc().apiKey(apiKey).build(); + * Note: API keys do not refresh — pick one with no expiration. + */ + static String apiKey = System.getenv("ARK_API_KEY"); + static ConnectionPool connectionPool = new ConnectionPool(5, 1, TimeUnit.SECONDS); + static Dispatcher dispatcher = new Dispatcher(); + static ArkService service = ArkService.volc().dispatcher(dispatcher).connectionPool(connectionPool).apiKey(apiKey).build(); + + public static void main(String[] args) { + String model = System.getenv().getOrDefault("SEEDANCE_MODEL", "doubao-seedance-2-0-fast-260128"); + + System.out.println("\n----- CREATE Task Request -----"); + List contents = new ArrayList<>(); + + // Text content + contents.add(new ContentItem() + .type(ContentType.TEXT) + .text("制作一段展示美丽自然风光的视频,包括山川、河流、森林和天空,充满平和与宁静的氛围,适合用于冥想或放松场景。 --ratio 1:1")); + + // Image URL content + contents.add(new ContentItem() + .type(ContentType.IMAGE_URL) + .imageUrl(new ImageURL().url("${IMAGE URL HERE}")) + // .role("first_frame") + ); + + CreateContentGenerationTaskRequest createRequest = new CreateContentGenerationTaskRequest() + .model(model) + .content(contents); + // .callbackUrl("YOUR CALLBACK URL"); + + CreateContentGenerationTaskResponse createResult = service.createContentGenerationTask(createRequest); + System.out.println(createResult); + + System.out.println("\n----- GET Task Request -----"); + ContentGenerationTask getResult = service.getContentGenerationTask(createResult.getId()); + System.out.println(getResult); + System.out.println("ServiceTier: " + getResult.getServiceTier()); + System.out.println("ExecutionExpiresAfter: " + getResult.getExecutionExpiresAfter()); + + System.out.println("\n----- LIST Task Request -----"); + ListContentGenerationTasksRequest listRequest = new ListContentGenerationTasksRequest() + .pageNum(1) + .pageSize(10) + .filterStatus(TaskStatus.RUNNING) + .filterModel(model); + // .filterTaskIds(java.util.Arrays.asList(createResult.getId())); + + ListContentGenerationTasksResponse listResponse = service.listContentGenerationTasks(listRequest); + System.out.println(listResponse); + if (listResponse.getItems() != null && !listResponse.getItems().isEmpty()) { + ContentGenerationTask item = listResponse.getItems().get(0); + System.out.println("List Item ServiceTier: " + item.getServiceTier()); + System.out.println("List Item ExecutionExpiresAfter: " + item.getExecutionExpiresAfter()); + } + + System.out.println("\n----- DELETE Task Request -----"); + try { + service.deleteContentGenerationTask(getResult.getId()); + System.out.println("deleted: " + getResult.getId()); + } catch (Exception e) { + System.out.println(e.getMessage()); + } + + service.shutdownExecutor(); + } +} diff --git a/examples/src/main/java/com/volcengine/ark/runtime/examples/CreateResponseExample.java b/examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/CreateResponseExample.java similarity index 97% rename from examples/src/main/java/com/volcengine/ark/runtime/examples/CreateResponseExample.java rename to examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/CreateResponseExample.java index 25e58ad..15a86a5 100644 --- a/examples/src/main/java/com/volcengine/ark/runtime/examples/CreateResponseExample.java +++ b/examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/CreateResponseExample.java @@ -1,4 +1,4 @@ -package com.volcengine.ark.runtime.examples; +package com.volcengine.ark.runtime.examples.volc; import com.fasterxml.jackson.databind.ObjectMapper; import com.volcengine.ark.runtime.models.responses.CacheMode; @@ -59,7 +59,7 @@ public static void main(String[] args) { Dispatcher dispatcher = new Dispatcher(); dispatcher.setMaxRequests(5000); dispatcher.setMaxRequestsPerHost(5000); - ArkService service = ArkService.builder().dispatcher(dispatcher).timeout(Duration.ofHours(1)).connectionPool(connectionPool).apiKey(apiKey).build(); + ArkService service = ArkService.volc().dispatcher(dispatcher).timeout(Duration.ofHours(1)).connectionPool(connectionPool).apiKey(apiKey).build(); System.out.println("\n----- [Standard Usage] Request 1-----"); @@ -172,7 +172,7 @@ public static void main(String[] args) { // function rather than answer in plain text. ResponsesRequest fcRequest = ResponsesRequest.builder() .model(modelName) - + .input(ResponsesInput.ofString("请用 sum 工具帮我计算 1 + 2 等于多少")) .thinking(Thinking.builder().type(ThinkingMode.ENABLED).build()) .tools(Collections.singletonList(weatherTool)) @@ -201,7 +201,7 @@ public static void main(String[] args) { // to attach the function-call output back into the conversation. ResponsesRequest fcOutputRequest = ResponsesRequest.builder() .model(modelName) - + .previousResponseId(fcResponseId.get()) // use the context before .input(ResponsesInput.ofList(Collections.singletonList( com.volcengine.ark.runtime.models.responses.ItemFunctionToolCallOutput.builder() @@ -241,7 +241,9 @@ public static void main(String[] args) { .build(); try { - service.streamResponse(request5) + Map mcpHeaders = new HashMap<>(); + mcpHeaders.put("ark-beta-mcp", "true"); + service.streamResponse(request5, mcpHeaders) .doOnError(Throwable::printStackTrace) .blockingForEach( CreateResponseExample::printStreamEvent @@ -297,7 +299,7 @@ public static void main(String[] args) { ResponsesRequest request8 = ResponsesRequest.builder() .input(ResponsesInput.ofString("你好")) .model(modelName) - + .text(ResponseTextConfig.builder().format(TextFormat.builder() .type(TextFormatType.fromValue("json_schema")) .name("math_reasoning") diff --git a/examples/src/main/java/com/volcengine/ark/runtime/examples/DoubaoAppCreateResponsesExample.java b/examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/DoubaoAppCreateResponsesExample.java similarity index 98% rename from examples/src/main/java/com/volcengine/ark/runtime/examples/DoubaoAppCreateResponsesExample.java rename to examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/DoubaoAppCreateResponsesExample.java index ee35f63..8137d0b 100644 --- a/examples/src/main/java/com/volcengine/ark/runtime/examples/DoubaoAppCreateResponsesExample.java +++ b/examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/DoubaoAppCreateResponsesExample.java @@ -1,4 +1,4 @@ -package com.volcengine.ark.runtime.examples; +package com.volcengine.ark.runtime.examples.volc; import com.volcengine.ark.runtime.models.responses.DoubaoAppCallBlock; import com.volcengine.ark.runtime.models.responses.DoubaoAppCallBlockOutputText; @@ -50,7 +50,7 @@ public static void main(String[] args) { Dispatcher dispatcher = new Dispatcher(); dispatcher.setMaxRequests(5000); dispatcher.setMaxRequestsPerHost(5000); - ArkService service = ArkService.builder().dispatcher(dispatcher).timeout(Duration.ofHours(1)).connectionPool(connectionPool).apiKey(apiKey).build(); + ArkService service = ArkService.volc().dispatcher(dispatcher).timeout(Duration.ofHours(1)).connectionPool(connectionPool).apiKey(apiKey).build(); Map headers = new HashMap<>(); // add this header to enable the beta feature diff --git a/examples/src/main/java/com/volcengine/ark/runtime/examples/EmbeddingsExample.java b/examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/EmbeddingsExample.java similarity index 86% rename from examples/src/main/java/com/volcengine/ark/runtime/examples/EmbeddingsExample.java rename to examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/EmbeddingsExample.java index 5015262..14f54c5 100644 --- a/examples/src/main/java/com/volcengine/ark/runtime/examples/EmbeddingsExample.java +++ b/examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/EmbeddingsExample.java @@ -1,4 +1,4 @@ -package com.volcengine.ark.runtime.examples; +package com.volcengine.ark.runtime.examples.volc; import com.volcengine.ark.runtime.models.embedding.EmbeddingInput; import com.volcengine.ark.runtime.models.embedding.EmbeddingRequest; @@ -16,7 +16,7 @@ public class EmbeddingsExample { * Authentication * 1.If you authorize your endpoint using an API key, you can set your api key to environment variable "ARK_API_KEY" * String apiKey = System.getenv("ARK_API_KEY"); - * ArkService service = ArkService.builder().apiKey(apiKey).build(); + * ArkService service = ArkService.volc().apiKey(apiKey).build(); * Note: If you use an API key, this API key will not be refreshed. * To prevent the API from expiring and failing after some time, choose an API key with no expiration date. *

@@ -28,13 +28,13 @@ public class EmbeddingsExample { static String apiKey = System.getenv("ARK_API_KEY"); static ConnectionPool connectionPool = new ConnectionPool(5, 1, TimeUnit.SECONDS); static Dispatcher dispatcher = new Dispatcher(); - static ArkService service = ArkService.builder().dispatcher(dispatcher).connectionPool(connectionPool).apiKey(apiKey).build(); + static ArkService service = ArkService.volc().dispatcher(dispatcher).connectionPool(connectionPool).apiKey(apiKey).build(); public static void main(String[] args) { System.out.println("\n----- embeddings request -----"); EmbeddingRequest request = EmbeddingRequest.builder() - .model("${YOUR_ENDPOINT_ID}") + .model("doubao-embedding-large-text-250515") .input(EmbeddingInput.ofList(Arrays.asList("花椰菜又称菜花、花菜,是一种常见的蔬菜。"))) .build(); diff --git a/examples/src/main/java/com/volcengine/ark/runtime/examples/EnvironmentsLifecycleExample.java b/examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/EnvironmentsLifecycleExample.java similarity index 96% rename from examples/src/main/java/com/volcengine/ark/runtime/examples/EnvironmentsLifecycleExample.java rename to examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/EnvironmentsLifecycleExample.java index fd9a90b..d7a03f4 100644 --- a/examples/src/main/java/com/volcengine/ark/runtime/examples/EnvironmentsLifecycleExample.java +++ b/examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/EnvironmentsLifecycleExample.java @@ -1,4 +1,4 @@ -package com.volcengine.ark.runtime.examples; +package com.volcengine.ark.runtime.examples.volc; import com.volcengine.ark.runtime.models.environment.CreateEnvironmentRequest; import com.volcengine.ark.runtime.models.environment.DeleteEnvironmentResponse; @@ -31,7 +31,7 @@ public static void main(String[] args) { throw new IllegalStateException("set ARK_API_KEY"); } - ArkService service = ArkService.builder().apiKey(apiKey).build(); + ArkService service = ArkService.volc().apiKey(apiKey).build(); // 1. Create — cloud + unrestricted network. CreateEnvironmentRequest createReq = new CreateEnvironmentRequest(); diff --git a/examples/src/main/java/com/volcengine/ark/runtime/examples/FileUploadExample.java b/examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/FileUploadExample.java similarity index 93% rename from examples/src/main/java/com/volcengine/ark/runtime/examples/FileUploadExample.java rename to examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/FileUploadExample.java index e313c04..fb537f9 100644 --- a/examples/src/main/java/com/volcengine/ark/runtime/examples/FileUploadExample.java +++ b/examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/FileUploadExample.java @@ -1,4 +1,4 @@ -package com.volcengine.ark.runtime.examples; +package com.volcengine.ark.runtime.examples.volc; import com.volcengine.ark.runtime.models.file.FileCreateRequest; import com.volcengine.ark.runtime.models.file.FileDeleted; @@ -16,7 +16,7 @@ public class FileUploadExample { * Authentication * 1.If you authorize your endpoint using an API key, you can set your api key to environment variable "ARK_API_KEY" * String apiKey = System.getenv("ARK_API_KEY"); - * ArkService service = ArkService.builder().apiKey(apiKey).build(); + * ArkService service = ArkService.volc().apiKey(apiKey).build(); * Note: If you use an API key, this API key will not be refreshed. * To prevent the API from expiring and failing after some time, choose an API key with no expiration date. *

@@ -36,7 +36,7 @@ public static void main(String[] args) { System.exit(1); } - ArkService service = ArkService.builder().apiKey(apiKey).build(); + ArkService service = ArkService.volc().apiKey(apiKey).build(); // Upload a file FileCreateRequest request = FileCreateRequest.builder() diff --git a/examples/src/main/java/com/volcengine/ark/runtime/examples/FileVideoResponsesExample.java b/examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/FileVideoResponsesExample.java similarity index 98% rename from examples/src/main/java/com/volcengine/ark/runtime/examples/FileVideoResponsesExample.java rename to examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/FileVideoResponsesExample.java index 1c9cdf3..e24f1f7 100644 --- a/examples/src/main/java/com/volcengine/ark/runtime/examples/FileVideoResponsesExample.java +++ b/examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/FileVideoResponsesExample.java @@ -1,4 +1,4 @@ -package com.volcengine.ark.runtime.examples; +package com.volcengine.ark.runtime.examples.volc; import com.volcengine.ark.runtime.models.file.FileCreateRequest; import com.volcengine.ark.runtime.models.file.FileObject; @@ -52,7 +52,7 @@ public static void main(String[] args) { System.exit(1); } - ArkService service = ArkService.builder().apiKey(apiKey).build(); + ArkService service = ArkService.volc().apiKey(apiKey).build(); File video = new File(args[0]); System.out.println("Uploading " + video.getAbsolutePath()); diff --git a/examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/ImageGenerationExample.java b/examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/ImageGenerationExample.java new file mode 100644 index 0000000..c308fe8 --- /dev/null +++ b/examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/ImageGenerationExample.java @@ -0,0 +1,46 @@ +package com.volcengine.ark.runtime.examples.volc; + +import com.volcengine.ark.runtime.models.images.CreateImageGenerationRequest; +import com.volcengine.ark.runtime.models.images.ImageGenerationResponse; +import com.volcengine.ark.runtime.models.images.ResponseFormat; +import com.volcengine.ark.runtime.service.ArkService; +import okhttp3.ConnectionPool; +import okhttp3.Dispatcher; + +import java.util.concurrent.TimeUnit; + +public class ImageGenerationExample { + + /** + * Authentication + * 1. If you authorize your endpoint using an API key, set the API key to environment variable "ARK_API_KEY": + * String apiKey = System.getenv("ARK_API_KEY"); + * ArkService service = ArkService.volc().apiKey(apiKey).build(); + * Note: API keys do not refresh — pick one with no expiration. + */ + static String apiKey = System.getenv("ARK_API_KEY"); + static ConnectionPool connectionPool = new ConnectionPool(5, 1, TimeUnit.SECONDS); + static Dispatcher dispatcher = new Dispatcher(); + static ArkService service = ArkService.volc().dispatcher(dispatcher).connectionPool(connectionPool).apiKey(apiKey).build(); + + public static void main(String[] args) { + String seedreamModel = System.getenv().getOrDefault("SEEDREAM_MODEL", "doubao-seedream-5-0-pro-260628"); + + System.out.println("\n----- [Seedream] Generate Images Request -----"); + CreateImageGenerationRequest request = new CreateImageGenerationRequest() + .model(seedreamModel) + .prompt("龙与地下城女骑士背景是起伏的平原,目光从镜头转向平原") + .responseFormat(ResponseFormat.URL) + .seed(1234567890L) + .watermark(true) + .size("1024x1024"); + + ImageGenerationResponse response = service.generateImages(request); + if (response.getError() != null) { + System.err.println("Error: " + response.getError().getCode() + " — " + response.getError().getMessage()); + } else if (response.getData() != null && !response.getData().isEmpty()) { + System.out.println("Image URL: " + response.getData().get(0).getUrl()); + } + service.shutdownExecutor(); + } +} diff --git a/examples/src/main/java/com/volcengine/ark/runtime/examples/KnowledgeSearchCreateResponsesExample.java b/examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/KnowledgeSearchCreateResponsesExample.java similarity index 98% rename from examples/src/main/java/com/volcengine/ark/runtime/examples/KnowledgeSearchCreateResponsesExample.java rename to examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/KnowledgeSearchCreateResponsesExample.java index f8e3909..ac23dff 100644 --- a/examples/src/main/java/com/volcengine/ark/runtime/examples/KnowledgeSearchCreateResponsesExample.java +++ b/examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/KnowledgeSearchCreateResponsesExample.java @@ -1,4 +1,4 @@ -package com.volcengine.ark.runtime.examples; +package com.volcengine.ark.runtime.examples.volc; import com.volcengine.ark.runtime.models.responses.Annotation; import com.volcengine.ark.runtime.models.responses.ItemFunctionKnowledgeSearch; @@ -38,7 +38,7 @@ public class KnowledgeSearchCreateResponsesExample { - private static final String MODEL_NAME = "your-model-name"; + private static final String MODEL_NAME = "doubao-seed-2-1-pro-260628"; private static final String KNOWLEDGE_RESOURCE_ID = "kb-xxxxxxxxxxxxxx"; public static void main(String[] args) { @@ -52,7 +52,7 @@ public static void main(String[] args) { Dispatcher dispatcher = new Dispatcher(); dispatcher.setMaxRequests(5000); dispatcher.setMaxRequestsPerHost(5000); - ArkService service = ArkService.builder() + ArkService service = ArkService.volc() .dispatcher(dispatcher) .timeout(Duration.ofHours(1)) .connectionPool(connectionPool) diff --git a/examples/src/main/java/com/volcengine/ark/runtime/examples/MemoryStoresLifecycleExample.java b/examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/MemoryStoresLifecycleExample.java similarity index 96% rename from examples/src/main/java/com/volcengine/ark/runtime/examples/MemoryStoresLifecycleExample.java rename to examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/MemoryStoresLifecycleExample.java index 41f5f8a..cc9fe5e 100644 --- a/examples/src/main/java/com/volcengine/ark/runtime/examples/MemoryStoresLifecycleExample.java +++ b/examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/MemoryStoresLifecycleExample.java @@ -1,4 +1,4 @@ -package com.volcengine.ark.runtime.examples; +package com.volcengine.ark.runtime.examples.volc; import com.volcengine.ark.runtime.models.memory.CreateMemoryRequest; import com.volcengine.ark.runtime.models.memory.CreateMemoryStoreRequest; @@ -28,7 +28,7 @@ public static void main(String[] args) { throw new IllegalStateException("set ARK_API_KEY"); } - ArkService service = ArkService.builder().apiKey(apiKey).build(); + ArkService service = ArkService.volc().apiKey(apiKey).build(); // 1. Create a memory store. CreateMemoryStoreRequest storeReq = new CreateMemoryStoreRequest(); diff --git a/examples/src/main/java/com/volcengine/ark/runtime/examples/MultiModalEmbeddingsExample.java b/examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/MultiModalEmbeddingsExample.java similarity index 88% rename from examples/src/main/java/com/volcengine/ark/runtime/examples/MultiModalEmbeddingsExample.java rename to examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/MultiModalEmbeddingsExample.java index 4a3e72b..297fb3f 100644 --- a/examples/src/main/java/com/volcengine/ark/runtime/examples/MultiModalEmbeddingsExample.java +++ b/examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/MultiModalEmbeddingsExample.java @@ -1,4 +1,4 @@ -package com.volcengine.ark.runtime.examples; +package com.volcengine.ark.runtime.examples.volc; import com.volcengine.ark.runtime.models.multimodal_embedding.EmbeddingInput; import com.volcengine.ark.runtime.models.multimodal_embedding.EmbeddingInputType; @@ -19,7 +19,7 @@ public class MultiModalEmbeddingsExample { * Authentication * 1.If you authorize your endpoint using an API key, you can set your api key to environment variable "ARK_API_KEY" * String apiKey = System.getenv("ARK_API_KEY"); - * ArkService service = ArkService.builder().apiKey(apiKey).build(); + * ArkService service = ArkService.volc().apiKey(apiKey).build(); * Note: If you use an API key, this API key will not be refreshed. * To prevent the API from expiring and failing after some time, choose an API key with no expiration date. *

@@ -31,7 +31,7 @@ public class MultiModalEmbeddingsExample { static String apiKey = System.getenv("ARK_API_KEY"); static ConnectionPool connectionPool = new ConnectionPool(5, 1, TimeUnit.SECONDS); static Dispatcher dispatcher = new Dispatcher(); - static ArkService service = ArkService.builder().dispatcher(dispatcher).connectionPool(connectionPool).apiKey(apiKey).build(); + static ArkService service = ArkService.volc().dispatcher(dispatcher).connectionPool(connectionPool).apiKey(apiKey).build(); public static void main(String[] args) { System.out.println("\n----- multimodal embeddings request -----"); @@ -44,12 +44,12 @@ public static void main(String[] args) { inputs.add(EmbeddingInput.builder() .type(EmbeddingInputType.IMAGE_URL) .imageUrl(ImageURL.builder() - .url("https://ark-project.tos-cn-beijing.ivolces.com/images/view.jpeg") + .url("https://ark-project.tos-cn-beijing.volces.com/images/view.jpeg") .build()) .build()); MultiModalEmbeddingRequest multiModalEmbeddingRequest = MultiModalEmbeddingRequest.builder() - .model("doubao-embedding-vision-250615") + .model("doubao-embedding-vision-251215") .input(inputs) .build(); diff --git a/examples/src/main/java/com/volcengine/ark/runtime/examples/ResponseOperationsExample.java b/examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/ResponseOperationsExample.java similarity index 94% rename from examples/src/main/java/com/volcengine/ark/runtime/examples/ResponseOperationsExample.java rename to examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/ResponseOperationsExample.java index 73fa8af..31f0f4e 100644 --- a/examples/src/main/java/com/volcengine/ark/runtime/examples/ResponseOperationsExample.java +++ b/examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/ResponseOperationsExample.java @@ -1,4 +1,4 @@ -package com.volcengine.ark.runtime.examples; +package com.volcengine.ark.runtime.examples.volc; import com.volcengine.ark.runtime.models.responses.DeleteResponseResponse; import com.volcengine.ark.runtime.models.responses.ResponseIncludable; @@ -34,7 +34,7 @@ public static void main(String[] args) { Dispatcher dispatcher = new Dispatcher(); dispatcher.setMaxRequests(5000); dispatcher.setMaxRequestsPerHost(5000); - ArkService service = ArkService.builder().dispatcher(dispatcher).timeout(Duration.ofHours(1)).connectionPool(connectionPool).apiKey(apiKey).build(); + ArkService service = ArkService.volc().dispatcher(dispatcher).timeout(Duration.ofHours(1)).connectionPool(connectionPool).apiKey(apiKey).build(); System.out.println("===== CreateResponse Example====="); diff --git a/examples/src/main/java/com/volcengine/ark/runtime/examples/SelfHostedWorkerExample.java b/examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/SelfHostedWorkerExample.java similarity index 92% rename from examples/src/main/java/com/volcengine/ark/runtime/examples/SelfHostedWorkerExample.java rename to examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/SelfHostedWorkerExample.java index ad9f667..558cae0 100644 --- a/examples/src/main/java/com/volcengine/ark/runtime/examples/SelfHostedWorkerExample.java +++ b/examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/SelfHostedWorkerExample.java @@ -5,10 +5,10 @@ // The warning is not a startup failure. To suppress it when running with Maven: // // MAVEN_OPTS="--add-opens=java.base/java.lang.invoke=ALL-UNNAMED" \ -// mvn -q -f examples/pom.xml exec:java \ -// -Dexec.mainClass=com.volcengine.ark.runtime.examples.SelfHostedWorkerExample +// mvn -q -f examples/volc/pom.xml exec:java \ +// -Dexec.mainClass=com.volcengine.ark.runtime.examples.volc.SelfHostedWorkerExample -package com.volcengine.ark.runtime.examples; +package com.volcengine.ark.runtime.examples.volc; import com.volcengine.ark.runtime.selfhosted.EnvironmentWorker; import com.volcengine.ark.runtime.selfhosted.SelfHostedClient; diff --git a/examples/src/main/java/com/volcengine/ark/runtime/examples/SessionsLoopExample.java b/examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/SessionsLoopExample.java similarity index 98% rename from examples/src/main/java/com/volcengine/ark/runtime/examples/SessionsLoopExample.java rename to examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/SessionsLoopExample.java index cf21485..422b430 100644 --- a/examples/src/main/java/com/volcengine/ark/runtime/examples/SessionsLoopExample.java +++ b/examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/SessionsLoopExample.java @@ -1,4 +1,4 @@ -package com.volcengine.ark.runtime.examples; +package com.volcengine.ark.runtime.examples.volc; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; @@ -61,7 +61,7 @@ public static void main(String[] args) throws Exception { } String modelId = System.getenv().getOrDefault("ARK_MODEL_ID", "${YOUR_MODEL_ID}"); - ArkService service = ArkService.builder().apiKey(apiKey).build(); + ArkService service = ArkService.volc().apiKey(apiKey).build(); // 1. Agent CreateAgentRequest agReq = new CreateAgentRequest(); diff --git a/examples/src/main/java/com/volcengine/ark/runtime/examples/SparseEmbeddingsExample.java b/examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/SparseEmbeddingsExample.java similarity index 89% rename from examples/src/main/java/com/volcengine/ark/runtime/examples/SparseEmbeddingsExample.java rename to examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/SparseEmbeddingsExample.java index 68c11e6..352acef 100644 --- a/examples/src/main/java/com/volcengine/ark/runtime/examples/SparseEmbeddingsExample.java +++ b/examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/SparseEmbeddingsExample.java @@ -1,4 +1,4 @@ -package com.volcengine.ark.runtime.examples; +package com.volcengine.ark.runtime.examples.volc; import com.volcengine.ark.runtime.models.multimodal_embedding.EmbeddingInput; import com.volcengine.ark.runtime.models.multimodal_embedding.EmbeddingInputType; @@ -20,7 +20,7 @@ public class SparseEmbeddingsExample { * Authentication * 1.If you authorize your endpoint using an API key, you can set your api key to environment variable "ARK_API_KEY" * String apiKey = System.getenv("ARK_API_KEY"); - * ArkService service = ArkService.builder().apiKey(apiKey).build(); + * ArkService service = ArkService.volc().apiKey(apiKey).build(); * Note: If you use an API key, this API key will not be refreshed. * To prevent the API from expiring and failing after some time, choose an API key with no expiration date. *

@@ -32,7 +32,7 @@ public class SparseEmbeddingsExample { static String apiKey = System.getenv("ARK_API_KEY"); static ConnectionPool connectionPool = new ConnectionPool(5, 1, TimeUnit.SECONDS); static Dispatcher dispatcher = new Dispatcher(); - static ArkService service = ArkService.builder().dispatcher(dispatcher).connectionPool(connectionPool).apiKey(apiKey).build(); + static ArkService service = ArkService.volc().dispatcher(dispatcher).connectionPool(connectionPool).apiKey(apiKey).build(); public static void main(String[] args) { System.out.println("\n----- sparse embeddings request -----"); @@ -44,7 +44,7 @@ public static void main(String[] args) { .build()); MultiModalEmbeddingRequest request = MultiModalEmbeddingRequest.builder() - .model("doubao-embedding-vision-250615") + .model("doubao-embedding-vision-251215") .input(inputs) .sparseEmbedding(SparseEmbeddingConfig.builder() .type(SparseEmbeddingMode.ENABLED) diff --git a/examples/src/main/java/com/volcengine/ark/runtime/examples/TokenizationExample.java b/examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/TokenizationExample.java similarity index 89% rename from examples/src/main/java/com/volcengine/ark/runtime/examples/TokenizationExample.java rename to examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/TokenizationExample.java index 2fc7e5c..970eade 100644 --- a/examples/src/main/java/com/volcengine/ark/runtime/examples/TokenizationExample.java +++ b/examples/volc/src/main/java/com/volcengine/ark/runtime/examples/volc/TokenizationExample.java @@ -1,4 +1,4 @@ -package com.volcengine.ark.runtime.examples; +package com.volcengine.ark.runtime.examples.volc; import com.volcengine.ark.runtime.models.tokenization.TokenizationInput; import com.volcengine.ark.runtime.models.tokenization.TokenizationRequest; @@ -16,7 +16,7 @@ public class TokenizationExample { * Authentication * 1.If you authorize your endpoint using an API key, you can set your api key to environment variable "ARK_API_KEY" * String apiKey = System.getenv("ARK_API_KEY"); - * ArkService service = ArkService.builder().apiKey(apiKey).build(); + * ArkService service = ArkService.volc().apiKey(apiKey).build(); * Note: If you use an API key, this API key will not be refreshed. * To prevent the API from expiring and failing after some time, choose an API key with no expiration date. *

@@ -28,7 +28,7 @@ public class TokenizationExample { static String apiKey = System.getenv("ARK_API_KEY"); static ConnectionPool connectionPool = new ConnectionPool(5, 1, TimeUnit.SECONDS); static Dispatcher dispatcher = new Dispatcher(); - static ArkService service = ArkService.builder().dispatcher(dispatcher).connectionPool(connectionPool).apiKey(apiKey).build(); + static ArkService service = ArkService.volc().dispatcher(dispatcher).connectionPool(connectionPool).apiKey(apiKey).build(); public static void main(String[] args) { System.out.println("\n----- tokenization request -----");